#!/usr/bin/python
#filename func_global.py
x = 50
def func():
global x
print('x is',x)
x = 2
print('changed global x to',x)
func()
print('Value of x is',x)
结果:
x is 50
changed global x to 2
Value of x is 2
在函数中对全局变量进行修改时,需要声明这个变量时全局的。