Python学习之while循环语法2022.4.2

本文介绍了Python编程中的while循环结构,展示了如何根据条件执行语句。同时,讲解了if-else条件判断在循环中的应用,以及break语句在需要提前退出循环时的作用。通过示例代码,解释了如何设计一个简单的猜数字游戏,并探讨了不同代码结构对循环行为的影响。
摘要由CSDN通过智能技术生成

1.while 条件:

如果条件为真(True)执行这里的语句

>>> counts = 3
>>> while counts > 0:
	print("小雨晴想吃火锅")
	counts = counts - 1	
小雨晴想吃火锅
小雨晴想吃火锅
小雨晴想吃火锅

2.counts = counts + 1与最外层中的else中的语句并列时,那么用户输入任何数字都会循环三次;counts = counts + 1多一个缩进,那么用户只有输入小于3的数字才会循环三次。

"""用Python设计的第一个游戏改进版"""

counts =3

while counts > 0:
    temp = input("不妨猜一下小雨晴现在心里想的是哪个数字:")
    guess= int(temp)

    if guess == 3:
       print("你是小雨晴心里的蛔虫嘛?!")
       print("哼,猜中了也没奖励!") 
    else:
        if guess > 3:
            print("大啦~")
        else:
            print("小啦~")
    counts = counts - 1

print("游戏结束,不玩啦^_^")
"""用Python设计的第一个游戏改进版"""

counts =3

while counts > 0:
    temp = input("不妨猜一下小雨晴现在心里想的是哪个数字:")
    guess= int(temp)

    if guess == 3:
       print("你是小雨晴心里的蛔虫嘛?!")
       print("哼,猜中了也没奖励!") 
    else:
        if guess > 3:
            print("大啦~")
        else:
            print("小啦~")
            counts = counts - 1

print("游戏结束,不玩啦^_^")

3.break语句:跳出一层循环体。

>>> counts = 3
>>> while counts > 0:
	print("小雨晴想吃火锅")
	counts = counts - 1
	break
小雨晴想吃火锅
"""用Python设计的第一个游戏改进版"""

counts =3

while counts > 0:
    temp = input("不妨猜一下小雨晴现在心里想的是哪个数字:")
    guess= int(temp)

    if guess == 3:
       print("你是小雨晴心里的蛔虫嘛?!")
       print("哼,猜中了也没奖励!")
       break
    else:
        if guess > 3:
            print("大啦~")
        else:
            print("小啦~")
        counts = counts - 1

print("游戏结束,不玩啦^_^")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值