跟着我学习-python-02-while循环

while循环

 再之前《跟着我学习-python-01-流程控制语句》中提到过while循环,今天着重讲解一下,希望大家多多支持。

# while 循环
'''
while 判断条件:
代码块
当给定的判断条件的返回值的真值测试结果为True时执行循环体的代码,否则退出循环体。
'''
num = 0
yn = input("死循环开始[y]:")
if yn == "y":   # 输入 y ,进入死循环,输入其他退出。
    # while True:
    while 1:    # 数字中非0,就是True;
        num += 1
        if num == 5:
            continue  # num 等于 5,跳出本次循环,不打印5,接着往下走。
        elif num > 10:
            break  # num 大于 10, 终止整个死循环,死循环结束。
        print(num)
else:
    print("退出")

结果:

死循环开始[y]:y
1
2
3
4
6
7
8
9
10

当num==5时,遇到 continue ,跳出本次循环,接着往下循环,所以不打印5;

当num==11时,大于10了,遇到break,终止整个死循环,死循环结束。所以11 没有打印。

'''
while..else 语句形式:

while 判断条件:
代码块
else:
代码块
else中的代码块会在while循环正常执行完的情况下执行,如果while循环被break中断,else中的代码块不会执行。
'''
num1 = 1
while num1 <= 10:
    print(num1)
    num1 += 1
else:
    print("while循环打印 1到10 ") # 执行了,else中的代码块会在while循环正常执行完的情况下执行

结果:

1
2
3
4
5
6
7
8
9
10
while循环打印 1到10 
执行了,else中的代码块.
num2 = 1
while num2 <= 10:
    print(num2)
    num2 += 1
    if num2 == 3:
        break
else:
    print("while循环打印 1到10 ") # 没有执行,如果while循环被break中断,else中的代码块不会执行。

结果:

1
2
没有执行,如果while循环被break中断,else中的代码块不会执行。
原文地址:https://www.cnblogs.com/daxiong1314/p/13153647.html