Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function inside a function - global and nonlocal scope

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)

like image 865
Tharanga Abeyseela Avatar asked Jun 12 '26 11:06

Tharanga Abeyseela


2 Answers

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.

like image 120
user2357112 supports Monica Avatar answered Jun 13 '26 23:06

user2357112 supports Monica


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.

like image 32
BrenBarn Avatar answered Jun 14 '26 00:06

BrenBarn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!