Python Special Syntax

#!/usr/bin/python
# Filename: for.py

for i in range(1, 5):
    print i
else:
    print The for loop is over

for循环在这个范围内递归——for i in range(1,5)等价于for i in [1, 2, 3, 4]

如果包含else,它总是在for循环结束后执行一次,除非遇到break语句。

 

 

关于局部变量:这个绝对让人震惊!

 

#!/usr/bin/python
# Filename: func_local.py

def func(x):
    print x is, x
    x = 2
    print Changed local x to, x

x = 50
func(x)
print x is still, x

结果是:

x is 50
Changed local x to 2
x is still 50

 

当然可以使用global关键字:

#!/usr/bin/python
# Filename: func_global.py

def func():
    global x

    print x is, x
    x = 2
    print Changed local x to, x

x = 50
func()
print Value of x is, x

输出结果为:

x is 50
Changed global x to 2
Value of x is 2

 

转自:http://woodpecker.org.cn/abyteofpython_cn/chinese/ch07s04.html

Python Special Syntax,布布扣,bubuko.com

Python Special Syntax

上一篇:python学习笔记[1]-凯撒密码


下一篇:Python PIL创建文字图片