print函数在python中有更多的“特权”吗?

时间:2015-03-25 04:15:27

标签: python printing global-variables local-variables

def func_print_x():
    ## x += 1    ## if uncomment this line, it will raise UnboundLocalError: local variable 'x' referenced before assignment
    print x
if __name__ = '__main__':
    x = 4
    func_print_x()

在函数 func_print_x()中,有两条规则:

  1. 对于“ x + = 1 ”这一行,变量 x 被视为局部变量;
  2. 当来到“打印x ”这一行时,变量 x 似乎是全局变量。
  3. 打印功能是否有更多'特权'?

1 个答案:

答案 0 :(得分:1)

def f():
    global s
    print s
    s = "That's clear."
    print s 


s = "Python is great!" 
f()
print s

o / p

Python is great!
That's clear.
That's clear.

但是你没有global

def f(): 
    print s
    s = "Me too."
    print s


s = "I hate spam." 
f()
print s

o / p

UnboundLocalError: local variable 's' referenced before assignment

如果您尝试将某些值分配给s

,则会出现上述错误

如果您尝试打印s的值,它将打印在函数