Functions and scope of variables | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

Functions and scope of variables

Hey, comrades! I would appreciate if somebody helps me to understand the following trick with scope of variables. I took the code from quiz lib. Take a look: x=5 def foo(): print(x) pass foo() The output is 5 actually. Right? Yes, it is a correct answer. I checked it in playground. So, the meaning is we can access "x" inside the function "foo". But if we add some operations on "x" inside the function "foo" like following for example: x=5 def foo(): x += 1 print(x) pass foo() https://code.sololearn.com/c9X499z8dN0Y we get an error "UnboundLocalError: local variable 'x' referenced before assignment"! I am breaking my head on the question: why in the first code we can access the variable "x" and can't in the second example?? I am in a stuck.

2nd Sep 2017, 7:42 PM
Alexander Lebedev
Alexander Lebedev - avatar
4 Answers
+ 18
only assignment creates that problem, but inside print(x+x), gives the same result
3rd Sep 2017, 10:12 AM
Sunil Raj
Sunil Raj - avatar
+ 2
Immortal, thank you for your answer and sample of code but it is still unclear. Let change the question as following: why we don't get the same error when we referencing 'x' in print function? Indeed it looks like - what is the difference between print(x) vs x+=1 in terms of scope of variables?
2nd Sep 2017, 8:16 PM
Alexander Lebedev
Alexander Lebedev - avatar
+ 2
Let look at the following code: x=5 def foo(): y=x y+=1 print(x, y) foo() Yes I can access the global variable 'x' in assignment operation and print function. The code works fine. The output is 5 6 But if try to access global variable 'x' say in arithmetics operations (inside function) it is unreachable.
2nd Sep 2017, 8:33 PM
Alexander Lebedev
Alexander Lebedev - avatar
+ 2
Sunil Raj, thank you for your message. We actually may rewrite the code like this: x=5 def foo(): print(x+1) foo() The output is 6. Fine! You give me new direction to think about it. Yes, if we try to assign to global variable inside function we get error. Looks like we have read only access to global variable. Is there on python.org detailed explanation why it is working this way? I am failed to find out this one.
3rd Sep 2017, 10:29 AM
Alexander Lebedev
Alexander Lebedev - avatar