第四章、 控制流
控制语句后面要加冒号:
1) if语句
if guess == number:
print 'Congratulations, you guessed it.' # New block starts here
elif guess < number:
print 'No, it is a little higher than that' # Another block
else:
print 'No, it is a little lower than that'
if not False and True: #组合条件
print "OK"
注:Python暂时没有switch语句
2) while语句
注:while语句有一个可选的else从句
while running:
guess = int(raw_input('Enter an integer : '))
if guess == number:
print 'Congratulations, you guessed it.'
running = False # this causes the while loop to stop
elif guess < number:
print 'No, it is a little higher than that'
else:
print 'No, it is a little lower than that'
else:
print 'The while loop is over.'
3) range语句
print range(10) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print range(5,10) #[5, 6, 7, 8, 9]
print range(1,10,3) #[1, 4, 7]
print range(-10, -100, -30) #[-10, -40, -70]
用法参考help(range)
4) for循环
a = ['apple', 'banana', 'carrot']
for i in range(len(a)): #range()和len()一起用于字符串索引
print a[i]
#apple
#banana
#carrot
带逗号的print语句输出的元素之间会自动添加空格
for i in range(len(a)):
print a[i], #带,的print语句
# apple banana carrot
C/C++中的for (int i = 0; i < 5; i++),等价于Python:for i in range(0,5)。
5) break语句
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
6) continue语句
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
continue
print 'Input is of sufficient length'
7) 条件表达式
x, y = 3, 4
small = x if x < y else y
print small #3