x=1#全局变量,其实就是模块里面所有的函数都可以使用
def test():
print(x)
x=2
if __name__=='__main__':
test()
输出:
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "C:/Python34/test.py", line 6, in <module>
test()
File "C:/Python34/test.py", line 3, in test
print(x)
UnboundLocalError: local variable 'x' referenced before assignment
>>>
就这样改变是不行的,需要加上global声明
x=1#全局变量,其实就是模块里面所有的函数都可以使用
def test():
print(x)
global x
x=2
print(x)
if __name__=='__main__':
test()
输出:
>>> ================================ RESTART ================================
>>>
1
2
>>>
x=1#全局变量,其实就是模块里面所有的函数都可以使用
def test():
print(x)
global x
x=2
print(x)
def test2():
print(x)
global x
x='abc'
print(x)
if __name__=='__main__':
test()
test2()
现在我们调换一些两个函数的位置
x=1#全局变量,其实就是模块里面所有的函数都可以使用
def test():
print(x)
global x
x=2
print(x)
def test2():
print(x)
global x
x='abc'
print(x)
if __name__=='__main__':
test2()
test()