Python global variable

前端 未结 6 1387
孤城傲影
孤城傲影 2020-12-16 14:49
def say_boo_twice():
  global boo
  boo = \'Boo!\'
  print boo, boo

boo = \'boo boo\'
say_boo_twice()

The output is

Boo! Bo

6条回答
  •  执笔经年
    2020-12-16 15:33

    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
    

提交回复
热议问题