Don Lun
Don Lun

Reputation: 2777

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

Upvotes: 14

Views: 36368

Answers (6)

NullException
NullException

Reputation: 4510

global boo is global only inside method say_boo_twice and has been re-assigned a value inside of this method. You need to understand the lexical or scope where it can be global or what you want it to be. In this context, just before printing, it was assigned a value of 'Boo!' and that is what it correctly printed.

Upvotes: 0

Azeemali Hashmani
Azeemali Hashmani

Reputation: 155

Before giving an example I want you to understand difference between global and local variable in python

global variable: This is specific to current module

local variable: This is specific to current functions or methods as we call it in python

What if both local and current variable have the same name boo ?

In such case if you don't define your variable boo as global in the same method or function it will by default use it as local variable

Coming to your code

You have defined boo as global in your method say_boo_twice(). The catch is when you try to initialize boo = 'Boo!' in that method you are actually overwriting what you initialized previously as boo = 'boo boo'

Try this code

-- I have not initialized variable boo inside method say_boo_twice()

def say_boo_twice():    
    global boo
    print boo, boo

boo = 'boo boo'    
say_boo_twice()

All the Best !!! !! !

Upvotes: 0

jon_darkstar
jon_darkstar

Reputation: 16768

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

Upvotes: 18

mcpeterson
mcpeterson

Reputation: 5134

Essentially you reassign boo when you call the function.

Check how this works with the globals() and locals() functions.

Upvotes: 3

josePhoenix
josePhoenix

Reputation: 538

You are re-assigning boo after you declare it as global, so the value is the last one you assigned to it. If you removed line three, you would get the output you expect.

Upvotes: 5

Dr McKay
Dr McKay

Reputation: 2568

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

Upvotes: 29

Related Questions