I'm trying out the following code with global, and nonlocal scope. following snippet working wihtout any issues.
def countdown(start):
n = start
def display():
print('--> %d' % n)
def decrement():
nonlocal n ##using python3
n -= 1
while n > 0:
display()
decrement()
countdown(10)
countdown(10)
but why can't i use the global n ? instead of nonlocal n. that gives me
UnboundLocalError: local variable 'n' referenced before assignment
this is the snippet
def countdown(start):
global n ##defined it global
n = start
def display():
print('--> %d' % n)
def decrement():
##no nonlocal varibale here
n -= 1
while n > 0:
display()
decrement()
countdown(10)
The global declaration doesn't automatically apply to nested functions. You need another declaration:
def decrement():
global n
n -= 1
so n in decrement also refers to the global variable.
You need to mark a variable as global in every function where you use it (or rather, every one where you assign to it). You marked n as global in countdown, but decrement still thinks it is local. If you want decrement to also use the global n, you need to put another global n inside decrement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With