Python global variable

前端 未结 6 1385
孤城傲影
孤城傲影 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:12

    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 !!! !! !

提交回复
热议问题