# global variablex = 10def func(): print(x)func()#ans: 10
# local variabledef func(): y = 20 print(y)func()#ans: print(y) # NameError
# modify global variablecount = 0def increment(): global count count += 1increment()#ans: count is 1
# modify enclosing scopedef outer(): x = 10 def inner(): nonlocal x x = 20 inner() return xresult = outer()#ans: 20
# local shadows globalx = 10def func(): x = 5 print(x)func()#ans: 5print(x)#ans: 10
# what is printed?x = 5def func(): print(x)func()#ans: 5
# what happens?x = 5def func(): x = 10func()print(x)#ans: 5 (local x doesn't affect global)
# global keyword?x = 5def func(): global x x = 10func()print(x)#ans: 10
# can you do this?def func(): print(x) x = 5func()#ans: UnboundLocalError
# nonlocal?def outer(): x = 5 def inner(): nonlocal x x = 10 inner() return xouter()#ans: 10
# nested functions?def outer(): x = 5 def inner(): return x return inner()outer()#ans: 5
# what is x?x = 1def func(): x = x + 1func()#ans: UnboundLocalError
# parameter scope?def func(x): x = 10x = 5func(x)print(x)#ans: 5
# global in nested?x = 5def outer(): def inner(): global x x = 10 inner()outer()print(x)#ans: 10
# closure?def outer(x): def inner(y): return x + y return innerf = outer(10)f(5)#ans: 15
Google tag (gtag.js)