Python global variable

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

    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.

提交回复
热议问题