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(( 中,有两个规则:
- 对于行 'x += 1',变量 x 被视为局部变量;
- 当来到">打印 X"行时,变量 X 似乎是全局变量。
打印功能是否具有更多"特权"?
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
的值,它将打印在函数内部