Look at the code below. What will it print?
x = 10 def func(): x = 5 print(x) func() print(x)
Remember, variables inside a function are local unless declared global.
The x inside func() is local and set to 5, so print(x) inside prints 5. Outside, x is still 10.
What error will this code produce?
def func(): print(x) x = 3 func()
Python treats variables assigned in a function as local, even if used before assignment.
Because x is assigned inside func(), Python treats it as local. The print(x) tries to access it before assignment, causing UnboundLocalError.
What will this code print?
count = 0 def increment(): global count count += 1 increment() increment() print(count)
Using global allows modifying the variable outside the function.
The global keyword tells Python to use the global count. Each call to increment() adds 1, so after two calls, count is 2.
What will this code print?
def outer(): x = 'outer' def inner(): nonlocal x x = 'inner' inner() print(x) outer()
nonlocal lets inner functions modify variables in the nearest enclosing scope.
The nonlocal keyword allows inner() to change x in outer(). So print(x) prints 'inner'.
Consider this code:
def f():
print(a)
a = 5
f()Why does it raise an error?
Think about how Python decides if a variable is local or global.
Python sees the assignment a = 5 inside f() and treats a as local. The print(a) tries to access this local a before it is assigned, causing an UnboundLocalError.