Python—global vs local variables
2015-07-27 09:29
579 查看
# num1 is a global variable num1 = 1 print num1 # num2 is a local variable def fun(): num1 = 2 num2 = num1 + 1 print num2 fun() # the scope of global num1 is the whole program, num 1 remains defined print num1 # the scope of the variable num2 is fun(), num2 is now undefined print num2
结果:
1 3 1
NameError: name 'num2' is not defined
example2:
num = 4 def fun1(): global num num = 5 def fun2(): global num num = 6 # note that num changes after each call with no obvious explanation print num fun1() print num fun2() print num
结果:
4 5 6
在函数外定义的是全局变量,函数内部定义的是局部变量。如果全局变量在函数中使用了并更改了其值,则会生成一个同名的局部变量。所以在函数中引用全局变量并改变其值,要加上global关键字。
相关文章推荐
- Python中特殊函数集锦
- python用于测试的failIf,failUnless
- Python logging模块详解
- Python - 命令行参数
- 【python】hust virtual judge 交题记录抓取
- 获取分享社最新一期的迅雷分享账号
- 用Python模拟浏览器登录
- python 爬图 helloworld
- Python中特殊函数集锦
- 在Python中的Django框架中进行字符串翻译
- 在Python的Django框架中创建语言文件
- Python多线程结合队列下载百度音乐的方法
- Python实现删除当前目录下除当前脚本以外的文件和文件夹实例
- python数组过滤实现方法
- python内建函数a-b部分(一)
- python内置函数(二)
- 走进Python世界(五)数据类型 5. 序列类型-字典(Dictionary)
- python系列------open函数
- 使用python获取实时卫星云图
- C和Python实现冒泡法排序