+ 1
Questions about function in Python
Hello, Could you please advice why the variable x isn’t increased in following function: x=1 def f(x): x+=2 f(x) print(x) Output: 1
8 odpowiedzi
+ 1
Python doesn't have variables as such, it's just a convention. In this case, x is the name of the object whose memory address is being permanently remapped:
x=1
print('Ident x:',id(x),'value:',x)
def f(x):
x+=2
print('Ident x:',id(x),'value:',x)
f(x)
print('Ident x:',id(x),'value:',x)
+ 4
x inside the function does not relate to x outside function
def f(x):
x+=2 # this mean you add 2 to argument x that function got it
should search about primitive data type and references data type
+ 2
Kreingkrai Luangchaipreeda has given the best explaination about your question …
X inside definition of function named f is not variable like x outside at first line . X inside the function is just for tell to the function what he supposed to do if a value is stored in braket. in this case function tell something like : if you puts some numbers inside my bracket i will increase it by adding 2
+ 1
Solo, thank you very much!
+ 1
x=1 #Is declared outside the function
def f(x): #x it's a parameter of the function. It's not necessary to call the function parameter as x as long as you work with the new name of the parameter
x+=2
print(x) #This output will be 3 because f it's evaluated in 1
f(x)
print (x) #In this step you are printing the value declared at begining x=1
#So, the variables declared inside the function only has his value inside the function.
#If you want get the new value you can do this
x=1
def f(example):
return example + 2
print(f(x))
0
Kreingkrai Luangchaipreeda, Thank you for the answer!
Could please then explain how the value of x inside the function is stored comparing to the usual variables outside function?
0
O'neal , thank you!
0
Frank Seguí Camacho thank you!