Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python global variable

def say_boo_twice():
  global boo
  boo = 'Boo!'
  print boo, boo

boo = 'boo boo'
say_boo_twice()

The output is

Boo! Boo!

Not as I expected. Since I declared boo as global, why is the output not:

boo boo boo boo

like image 503
Don Lun Avatar asked Apr 03 '11 22:04

Don Lun


2 Answers

You've changed boo inside your function, why wouldn't it change? Also, global variables are bad.

like image 59
Dr McKay Avatar answered Oct 12 '22 01:10

Dr McKay


Because you reassign right before hand. Comment out boo = 'Boo!' and you will get what you describe.

def say_boo_twice():
   global boo
   #boo = 'Boo!'
   print boo, boo  

boo = 'boo boo' 
say_boo_twice() 

Also that global boo is unnecessary, boo is already in global scope. This is where the global makes a difference

def say_boo_twice():   
   global boo
   boo = 'Boo!'
   print boo, boo  

say_boo_twice() 
print "outside the function: " + boo #works

Whereas:

def say_boo_twice():   
   #global boo
   boo = 'Boo!'
   print boo, boo  

say_boo_twice() 
print "outside the function: " + boo # ERROR.  boo is only known inside function, not to this scope
like image 23
jon_darkstar Avatar answered Oct 12 '22 02:10

jon_darkstar