python学习笔记23:基础之控制流

1. if...elif...else...

if xxx:
    a
elif yyy:
    b
else:
    c

2. while...else...

while xxx:
   a
else:
   b

while对应的else语句在while循环正常结束的情况下会被执行.
如果while循环是通过break跳出的,则else不执行。
这种else可以在这种情况下:通过循环寻找某个东西,如果找到,则break退出,如果没找到,则执行完全部循环,然后执行else语句报告没有找到。

例1:

import random  
import re  
  
target = random.randint(0, 100)  
  
cnt = 6  
i = 0  
  
while i<cnt:  
    guess = input('Round {i}, enter a num in [0,100]: '.format(i=i+1))  
    i += 1  
  
    guess = int(guess)  
    if guess>target:  
        print('Too large')  
    elif guess<target:  
        print('Too small')  
    elif guess==target:  
         print('Pass, target is {target}'.format(target=target))  
    break # 如果猜中数字,则跳出循环,不会执行else语句  
else:  
    # 如果循环正常结束仍没猜中,执行else语句,报告Fail  
    print('Fail, target is {target}, You Have try for {cnt} times'.format(target=target, cnt=cnt))   
  
输出:  
Round 1,enter a num in [0,100]: 50  
Too small  
Round 2,enter a num in [0,100]: 75  
Too small  
Round 3,enter a num in [0,100]: 88  
Too small  
Round 4,enter a num in [0,100]: 96  
Too small  
Round 5,enter a num in [0,100]: 98  
Too small  
Round 6,enter a num in [0,100]: 99  
Too small  
Fail: target is 100, You Have Try for 6 times  

3. for...else...

#range返回一个列表,不包含结束值。  
for i in range(1,5):  
    print(i)  
else:  
    print('over')  

for对应的else语句类似于while对应的else语句,在for循环正常结束的情况下会被执行,具体解释见while处的解释。

4. break 和 continue

break: 终止循环
continue: 进入下一轮循环

原文地址:https://www.cnblogs.com/gaiqingfeng/p/13254645.html