0

in python 3.0 from what i know when i'm using variables that aren't found in the local scope it will go all the way back until it reaches the global scope to look for that variable.

I have this function:

def make_withdraw(balance):
    def withdraw(amount):
        if amount>balance:
            return 'insuffiscient funds'
        balance=balance-amount
        return balance
    return withdraw

p=make_withdraw(100)
print(p(30))

When i insert a line:

nonlocal balance

under the withdraw function definition it works well, but when i don't it will give me an error that i reference local variable 'balance' before assignment, even if i have it in the make_withdraw function scope or in the global scope.

Why in other cases it will find a variable in previous scopes and in this one it won't?

Thanks!

argamanza
  • 1,122
  • 3
  • 14
  • 36
  • Python won't let you *assign to* (i.e. `name = ...`) names it finds in outer scopes, unless you explicitly mark them `global`/`nonlocal`. It will let you *access* them, though (e.g. `... = name`). – jonrsharpe Mar 05 '15 at 13:08
  • There are some interesting (related) details here: http://stackoverflow.com/questions/28129057/how-is-a-python-functions-name-reference-found-inside-its-declaration/28130023#28130023 –  Mar 05 '15 at 17:57

1 Answers1

1

There are too many questions on this topic. You should search before you ask.

Basically, since you have balance=balance-amount in function withdraw, Python thinks balance is defined inside this function, but when code runs to if amount>balance: line, it haven't seen balance's definition/assignment, so it complains local variable 'balance' before assignment.

nonlocal lets you assign values to a variable in an outer (but non-global) scope, it tells python balance is not defined in function withdraw but outside it.

laike9m
  • 18,344
  • 20
  • 107
  • 140