+ 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?

19th Nov 2017, 10:57 AM
Yololab
Yololab - avatar
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 šŸ˜‰
19th Nov 2017, 11:03 AM
Zephyr Koo
Zephyr Koo - avatar
+ 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
19th Nov 2017, 2:11 PM
šŸ‘‘ Prometheus šŸ‡øšŸ‡¬
šŸ‘‘ Prometheus šŸ‡øšŸ‡¬ - avatar
+ 1
def funa (x,y): return x+y i = funa(4,5) print (i)
19th Nov 2017, 3:49 PM
Etay Cohen-Solal (ET)
Etay Cohen-Solal (ET) - avatar
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 ...
19th Nov 2017, 2:47 PM
AndrƩ Fortin
0
In your example, your line 1, and line 6, are useless, except to illustrate the difference between local and global variables.
19th Nov 2017, 2:49 PM
AndrƩ Fortin
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Ā Ā»
19th Nov 2017, 5:30 PM
Medhy Vinceslas