Well, in your second example, it's required to work so that you can have algebraic closure.Hey, I've got a question I was hoping I could get some help with. I'm new to programming and I'm taking an intro CS class in Python 3.6.
I'm having trouble understanding the difference between the following two scenarios.
Code:def f(a,b): sumab = a+b c = c + sumab c = 1 f(1,10)
The above produces an unbound local variable error at c = c + sumab. If I instead wrote c = sumab that would be fine, as would d = c + sumab, because the latter would look in the parent frame for c. But from my understanding , doing c = c + sumab makes python think the c on the right of the = is supposed to refer to a c in the local frame which isn't defined yet, and so it gives me an error. To fix it I could add the line "nonlocal c."
My question now is why the following works:
Code:def countup(): count = [0] def resolve(request): if request == "up": count[0] = count[0]+1 elif request == "down": count[0] = count[0]-1 elif request == "currentvalue": return count return resolve a = countup() a("up")
Why is Python cool with me referring to the first value in the list "count" on both sides of the = in the conditionals even though the list "count" is defined in its parent frame, when it has trouble in the previous code doing something similar? I feel like I'm overlooking something really obvious but this was one of those things I thought I understood until I thought about it more.
Count is local, even if not in the inner function. When you leave the countup function, since the reference count to the list count is not zero, it doesn't get destroyed.
I'd argue the first case is mostly a safeguard against errors when a global clashes with a local name. I was surprised it's not a runtime error but a "static" one at first time (but it makes sense).
I don't think there's an obvious reason behind this. It's... designed this way, because in both cases it seems to be the best choice.
Edit: let me say that if you're new to programming and this is the kind of things that puzzles you, you're doing great...