Back to questions
JuniorTheoryCommon
What happens when this program runs?
count = 0
def increment():
count = count + 1
return count
print("start")
print(increment())Prints start, then raises UnboundLocalError
- Expecting
1, as ifcount + 1read the global: the assignment makescountlocal in the whole function, and that local has no value yet. - Expecting the error before
start: the function body runs only when it is called, sostartprints first and the error comes on the call.
- How would you change
incrementso that it updates the globalcount? - Why does a function that only reads
count, without assigning it, work?