+ 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

3rd Aug 2022, 8:49 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
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)
3rd Aug 2022, 10:44 AM
Solo
Solo - avatar
+ 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
3rd Aug 2022, 8:54 AM
Kreingkrai Luangchaipreeda
Kreingkrai Luangchaipreeda - avatar
+ 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
4th Aug 2022, 1:08 AM
O'neal
O'neal  - avatar
+ 1
Solo, thank you very much!
3rd Aug 2022, 11:29 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
+ 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))
5th Aug 2022, 2:13 AM
Frank Seguí Camacho
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?
3rd Aug 2022, 9:45 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
0
O'neal , thank you!
4th Aug 2022, 10:17 AM
Ruslan Guliyev
Ruslan Guliyev - avatar
5th Aug 2022, 6:54 AM
Ruslan Guliyev
Ruslan Guliyev - avatar