Why can functions in Python print variables in enclosing scope but cannot use them in assignment? [duplicate]
If I run the following code: x = 1 class Incr: print(x) x = x + 1 print(x) print(x) It prints: 1 2 1 Okay no problems, that's exactly what I expected. And if I do the following: x = 1 class Incr: global x print(x) x = x + 1 print(x) print(x) It prints: 1 2 2 Also what I expected. No problems there. Now if I start making an increment function as follows: x = 1 def incr(): print(x) incr() It prints 1 just as I expected. I assume it does this because it cannot find x in its local scope, so it searches its enclosing scope and finds x there. So far no problems. Now if I do: x = 1 def incr(): print(
0 upvotes
View original discussion ↗
Comments
Sign in or sign up to comment and upvote.
No comments yet.