Middle
counter = 0 def increment(): >>>>counter += 1 increment() print(counter) What will be displayed on the screen and why?
sobes.tech AI
Answer from AI
The code will produce an error UnboundLocalError: local variable 'counter' referenced before assignment.
The reason is that inside the increment() function, there is an attempt to modify the variable counter using counter += 1. By default, Python treats counter inside the function as a local variable. But before assignment, it is not initialized, which causes the error.
To fix this, you need to explicitly specify that counter is a global variable:
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # Will output 1