Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
What does this program show? Say it before you run it.
If it shows an error, explain it and fix it in two different ways.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Inside add_one, the line count = count + 1 assigns to count. An assignment makes count a local variable of the function. But the right side, count + 1, reads the local count before it has a value.
So Python stops with UnboundLocalError: cannot access local variable 'count' where it is not associated with a value.
Fix 1 (best): use a parameter and return.
This shows 6 and then 5. The function has no hidden input.
Fix 2: use global.
This shows 6 and then 6, because the outside count is changed. It works, but the function now depends on the outside, and changes it. Fix 1 is better.
Answer: The program shows an UnboundLocalError. Fix it with a parameter and return, or, less well, with global.
Log in to join the discussion.
Loading…