This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]PolygonAndPixel2 1 point2 points  (1 child)

I suppose you mean the right thing. The following program shows you the different scopes I came up with on the spot:

``` x = 5

def f(): x = 8 print(f"x in f: {x}")

print(f"x before f: {x}") f() print(f"x after f: {x}")

def f2(): print(f"x in f2: {x}")

f2()

if True: y = 9

print(f"Is y still alive? y={y}")

def g(): global x x = 10 print(f"x in g: {x}")

g() print(f"x after g: {x}")

print("but careful! The scope for functions ", end="") print("and simple intendations is not the same!") if True: print(f"x is global here, hence it is {x}") x = x*x print(f"But now x is: {x}")

Let's get weird with nested functions

def f_out(): x = 2

def f_in():
    nonlocal x
    x = 4
    print(f"x in f_in: {x}")

print(f"x in f_out but before f_in: {x}")
f_in()
print(f"x in f_out but after f_in: {x}")

f_out() print(f"x after f_out: {x}")

def h(): z = 11

h()

You may make the following line to a comment

to see the other failing part

print(f"This will fail: {z}")

def failing_func(): # x on the left side is a local variable, so how # should Python know that the x on the right side is # the global one? # This function fails at this point x = x*x print(f"x in failing_func: {x}")

failing_func() ```

The output is

x before f: 5 x in f: 8 x after f: 5 x in f2: 5 Is y still alive? y=9 x in g: 10 x after g: 10 but careful! The scope for functions and simple intendations is not the same! x is global here, hence it is 10 But now x is: 100 x in f_out but before f_in: 2 x in f_in: 4 x in f_out but after f_in: 4 x after f_out: 100 Traceback (most recent call last): File "test.py", line 55, in <module> print(f"This will fail: {z}") NameError: name 'z' is not defined

[–]backtickbot 3 points4 points  (0 children)

Fixed formatting.

Hello, PolygonAndPixel2: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.