number = 23 guess = int(input('Enter an integer : '))
if guess == number: print('Congratulations, you guessed it.') # 新块开始处 print('(but you do not win any prizes!)') # 新块结束处 elif guess < number: print('No, it is a little higher than that') # 另一个块 # 你可以在一个块里做任何你想做的。。。 else: print('No, it is a little lower than that') # 只有guess > number 才会执行到此处
print('Done')
输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
$ python if.py Enter an integer : 50 No, it is a little lower than that Done
$ python if.py Enter an integer : 22 No, it is a little higher than that Done
$ python if.py Enter an integer : 23 Congratulations, you guessed it. (but you do not win any prizes!) Done
while running: guess = int(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.') # Do anything else you want to do here
print('Done')
输出
1 2 3 4 5 6 7 8 9
$ python3 while.py Enter an integer : 50 No, it is a little lower than that. Enter an integer : 22 No, it is a little higher than that. Enter an integer : 23 Congratulations, you guessed it. The while loop is over. Done
C/C++程序员注意: 记住,while循环可以拥有else分支
for…in 语句
for…in是另一种循环语句,用来遍历序列对象,也就是说遍历序列中的每个元素。
1 2
for variable in iterable: suite
示例
1 2 3 4 5 6 7
#!/usr/bin/python # Filename: for.py
for i inrange(1, 5): print(i) else: print('The for loop is over')
whileTrue: s = (input('Enter something : ')) if s == 'quit': break print('Length of the string is', len(s)) print('Done')
输出
1 2 3 4 5 6 7 8 9 10 11
$ python break.py Enter something : Programming is fun Length of the string is 18 Enter something : When the work is done Length of the string is 21 Enter something : if you wanna make your work also fun: Length of the string is 37 Enter something : use Python! Length of the string is 12 Enter something : quit Done
continue 语句
语句continue告诉python跳过当前循环语句块的剩余部分执行下次迭代。
示例
1 2 3 4 5 6 7 8 9 10 11 12
#!/usr/bin/python # Filename: continue.py
whileTrue: s = input('Enter something : ') if s == 'quit': break iflen(s) < 3: print('Too small') continue print('Input is of sufficient length') # Do other kinds of processing here...
输出
1 2 3 4 5 6 7 8
$ python test.py Enter something : a Too small Enter something : 12 Too small Enter something : abc Input is of sufficient length Enter something : quit