3.2 while循环

3.2 while循环

while 条件为True:
代码块

anwser_age=45
age=int(input('请输入你猜测的年龄<<')) 

if age!=anwser_age:
    if age < anwser_age:
        print('猜小了')
    else:
        print('猜大了')
else:
    print('猜对了')

运行结果如下:

请输入你猜测的年龄<< 50


猜大了

缺点:只能猜一次

3.2.1 while +break

猜年龄游戏4.0

#定义奖励
praise={0:'candy',1:'food',2:'water'}
while 1:
    anwser_age=45
    age=int(input('请输入你猜测的年龄<<')) 

    if age!=anwser_age:
        if age < anwser_age:
            print('猜小了')
        else:
            print('猜大了')
    else:
        print(f'猜对了,请选择你心仪的奖品序号{praise}')
        while True:
            choice=int(input())
            if choice != 2:
                print(f'恭喜你获得{praise[choice]}!')
                break
            else:
                print(f'很抱歉,等级不够无法获取{praise[choice]},请重新选择')
        break #不写break无法结束循环

运行结果如下:

请输入你猜测的年龄<< 50


猜大了


请输入你猜测的年龄<< 25


猜小了


请输入你猜测的年龄<< 45


猜对了,请选择你心仪的奖品序号{0: 'candy', 1: 'food', 2: 'water'}


 2


很抱歉,等级不够无法获取water,请重新选择


 0


恭喜你获得candy!

3.2.2 while+continue

#练习 打印1-10 并且跳过5
n=1
while n<=10:
    if n!=5:
        print(n)
    n+=1

运行结果如下:

1
2
3
4
6
7
8
9
10

continue
以上代码等同于

n=1
while n<=10:
    if n==5:
        n+=1
        continue #不执行下面代码,进入下一轮循环
    print(n)
    n+=1

运行结果如下:

1
2
3
4
6
7
8
9
10

区分:break 直接终止整个while循环,continue不执行下面代码,进入下一轮循环

3.2.3 while-else

当while循环没有被break的时候会执行else语句

n=1
while n<=10:
    if n==5:
        n+=1
        continue #不执行下面代码,进入下一轮循环
    print(n)
    n+=1
else:
    print('循环体外')

运行结果如下:

1
2
3
4
6
7
8
9
10
循环体外

当while循环被break的时候,不会执行else语句

n=1
while n<=10:
    if n==5:
        n+=1
        break 
    print(n)
    n+=1
else:
    print('循环体外')

运行结果如下:

1
2
3
4
posted @ 2025-08-03 20:39  bokebanla  阅读(6)  评论(0)    收藏  举报