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
You've changed boo
inside your function, why wouldn't it change? Also, global variables are bad.
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
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