Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
In which language,
14th Apr 2020, 5:09 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
It's simple. x=5 #global variable def f(): d=3 #local variable for function. d+=x #using global variable in function. return d now use this analogy for your code.
14th Apr 2020, 5:17 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
In the first code first, run print(FG) which output 95 because it is printing global FG which is 95.after you call st() function and its printing 15 because of function always first check local variable then preceded to a global variable. after you call again print(FG) which is again printing global variable which is 95.remember that in python variables always use which has more precedencee.
14th Apr 2020, 5:31 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
In second code. When it calls to print(FG) it prints 95 because it refers to a global variable. after you call an st() function in st() now you use global keyword it means to make variable global which is local in function. when it prints FG value it prints 15 because now FG is 15 in function. remeber now global variable FG also become 15 because of you convert FG local variable of function to global variable now when print(FG) again run it print 15 because now FG is 15. I hope you now understand.
14th Apr 2020, 5:35 PM
Maninder $ingh
Maninder $ingh - avatar
+ 2
Øffîcïâl Kîîbõ Ghãyãl yes you are right. global convert local into global or override if the same name of variable already defined.
14th Apr 2020, 5:42 PM
Maninder $ingh
Maninder $ingh - avatar