全局变量和局部变量

 1 a=10
 2 def test():
 3     print("-"*20)
 4     a=100
 5     print(a)
 6     print(id(a))
 7 
 8 
 9 def test2():
10     print("*"*20)
11     print(a)
12     print(id(a))
13 
14 
15 test()
16 test2()
View Code

运行结果:

E:Python35python.exe F:/Exercise/Python/test0731/登陆.py
--------------------
100
1813904272
********************
10
1813901392

Process finished with exit code 0

注意事项:

在python中a+=1时修改。

a=100这句可能时修改也可以时定义,在这个函数当中因为test()不能对全局变量进行修改所以此处是定义,a的id就可以说明这个问题,

在一个函数中如果一个全局变量和一个局部变量名字相同的话,首先选择用局部变量,然后用全局变量。

原文地址:https://www.cnblogs.com/rourou1/p/6240862.html