When does my function will go to previous scopes to look for a variable?
Question:
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!
Answers:
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.
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!
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.