首页 > 代码库 > Python Special Syntax

Python Special Syntax

#!/usr/bin/python# Filename: for.pyfor i in range(1, 5):    print ielse:    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.pydef func(x):    print x is, x    x = 2    print Changed local x to, xx = 50func(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.pydef func():    global x    print x is, x    x = 2    print Changed local x to, xx = 50func()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