if 语句
可能最为人所熟知的编程语句就是
if语句了。例如:
x=int(input("Please enter an integer: "))Please enter an integer: 42>>> ifx<0:... x=0... print('Negative changed to zero')... elifx==0:... print('Zero')... elifx==1:... print('Single')... else:... print('More')...More
可以有零个或多个
elif部分,以及一个可选的
else部分。 关键字 'elif
' 是 'else if' 的缩写,适合用于避免过多的缩进。 一个 if ... elif ... elif ... 序列可以看作是其他语言中的 switch 或 case语句的替代。
for 语句
Python 中的 for 语句与你在 C 或 Pascal 中可能用到的有所不同。 Python 中的 for
语句并不总是对算术递增的数值进行迭代(如同 Pascal),或是给予用户定义迭代步骤和暂停条件的能力(如同 C),而是对任意序列进行迭代(例如列表或字符串),条目的迭代顺序与它们在序列中出现的顺序一致。 例如(此处英文为双关语):
# Measure some strings:... words=['cat','window','defenestrate']>>> forwinwords:... print(w,len(w))...cat 3window 6defenestrate 12
If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
forwinwords[:]:# Loop over a slice copy of the entire list.... iflen(w)>6:... words.insert(0,w)...>>> words['defenestrate', 'cat', 'window', 'defenestrate']
With
forwinwords:
, the example would attempt to create an infinite list, inserting
defenestrate
over and over again.
range() 函数
如果你确实需要遍历一个数字序列,内置函数
range()
会派上用场。它生成算术级数:foriinrange(5):... print(i)...01234
给定的终止数值并不在要生成的序列里;range(10)
会生成10个值,并且是以合法的索引生成一个长度为10的序列。range也可以以另一个数字开头,或者以指定的幅度增加(甚至是负数;有时这也被叫做 '步进')
range(5,10)5,6,7,8,9range(0,10,3)0,3,6,9range(-10,-100,-30)-10,-40,-70
要以序列的索引来迭代,您可以将
range()和 len() 组合如下:
a=['Mary','had','a','little','lamb']>>> foriinrange(len(a)):... print(i,a[i])...0 Mary1 had2 a3 little4 lamb
然而,在大多数这类情况下,使用 enumerate()函数比较方便,请参见 循环的技巧 。
如果你只打印 range,会出现奇怪的结果:
print(range(10))range(0, 10)range()
所返回的对象在许多方面表现得像一个列表,但实际上却并不是。此对象会在你迭代它时基于所希望的序列返回连续的项,但它没有真正生成列表,这样就能节省空间。
We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list()is another; it creates lists from iterables:list(range(5))[0, 1, 2, 3, 4]
Later we will see more functions that return iterables and take iterables as argument.
break 和 continue 语句,以及循环中的 else 子句
break语句,和 C 中的类似,用于跳出最近的 for 或 while 循环.
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with
while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:
(是的,这是正确的代码。仔细看: else子句属于 for 循环, 不属于if 语句。)
When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement's else clause runs when no exception occurs, and a loop's elseclause runs when no break occurs. For more on the try statement and exceptions, see 处理异常.continue
pass 语句
pass 语句什么也不做。当语法上需要一个语句,但程序需要什么动作也不做时,可以使用它。例如:
whileTrue:... pass# Busy-wait for keyboard interrupt (Ctrl+C)...
这通常用于创建最小的类:
classMyEmptyClass:... pass...
pass的另一个可以使用的场合是在你编写新的代码时作为一个函数或条件子句体的占位符,允许你保持在更抽象的层次上进行思考。
pass
会被静默地忽略:
definitlog(*args):... pass# Remember to implement this!...
定义函数
我们可以创建一个输出任意范围内 Fibonacci 数列的函数:
deffib(n):# write Fibonacci series up to n... """Print a Fibonacci series up to n."""... a,b=0,1... whilea