+ 4
I need help in function quick!
i=0 def funa(x,y): i=x+y print(i) funa(4,5) print(i) Result: 9 0 Why doesnāt variable āiā change itās value?
6 Answers
+ 16
It's due to the scope of variables. You can find out detailed answer @ http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html š
+ 3
It is because when the function is called, that i exists in a local scope, say funa.
The i=0 i is a global variable, or it exists in a global scope.
Hence, these 2 don't meet unless you use the global keyword in the function
+ 1
def funa (x,y):
return x+y
i = funa(4,5)
print (i)
0
Variable "i" on line 1 is a global variable. Variable "i" on lines 4 and 5 is local, valid only inside the function "funa". So, print (i) on line 6 prints the global variable, and print(i) on line 5 prints the local variable of function "funa". You set the global variable"i" to zero on line 1, which you print on line 6. When Python is ready for execution of line 6, the local variable "i" already vanished because function "funa" completed its task on line 5 ...
0
In your example, your line 1, and line 6, are useless, except to illustrate the difference between local and global variables.
0
Your funa function already print the result pour you.
So itās not necessary to print it after calling your function.
Then at the beginning of your code, you can forget the Ā«Ā i=0Ā Ā»