Back to questions
JuniorTheoryCommon
What does the program print?
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
c = make_counter()
print(c(), c(), make_counter()())1 2 1
- Expecting
3frommake_counter()(): each call ofmake_countercreates a newcountstarting at0, so the new counter returns1. - Expecting
countto restart on everyc()call:count = 0runs only inmake_counter, andnonlocalmakescounterupdate that one variable.
- What happens if you remove the
nonlocal countline? - How would you make two counters that start at different numbers?