是否打印功能具有在python
问题描述:
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(),有两个规则:是否打印功能具有在python
- 为 '线X + = 1',可变x被视为局部变量;
- 当来到'打印x'时,变量x似乎是全局变量。
是否print函数有更多'特权'?
答
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.
但whne你没有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
值会在函数内部打印
+0
我不知道's'是全球性还是本地性的。 – 2015-03-25 05:09:43
不,'x'成为一个局部变量*当你尝试将功能*内分配给它,如同你'+ ='这里。你可以在函数中使用全局变量'x',只要你不想在其他地方分配它。 – Marius 2015-03-25 04:19:48
@Marius哦,我明白了。 '**不要尝试分配给它**'就行了! 'print x + 1'正常工作。非常感谢! – 2015-03-25 04:26:28