Python-while语句

本文介绍了Python中while循环的使用,包括如何通过条件判断、break和continue来控制循环流程。示例展示了当输入为0时退出循环、遇到0时结束循环以及仅处理奇数的情况。此外,还演示了如何利用while循环操作列表(移除特定元素)和字典(收集用户输入信息直至指定条件满足)。
摘要由CSDN通过智能技术生成

1 条件不满足退出

通过input输入信息,判断是否继续执行while中的内容

prompt='input number,0 will finished the game:'
message='1'
while int(message)!=0:
    message=input(prompt)
    if message != "0":
         print(f"Your number is {message},game continue")
    elif message=="0":
        print(f"Your number is {message},game finished")

运行结果:

input number,0 will finished the game:1
Your number is 1,game continue
input number,0 will finished the game:2
Your number is 2,game continue
input number,0 will finished the game:0
Your number is 0,game finished

2 通过break退出

prompt='input number,0 will finished the game:'
message='1'
while int(message)!=0:
    message=input(prompt)
    if message=="0":
        print(f"Your number is {message},game finished")
        break

运行结果:

input number,0 will finished the game:1
input number,0 will finished the game:2
input number,0 will finished the game:4
input number,0 will finished the game:0
Your number is 0,game finished

3 通过continue继续while循环

message=1
while message < 10:
    message += 1;
    if int(message) % 2 == 0:
        continue #如果是偶数,则while循环从头执行,不执行下面的语句
    #打印奇数
    print(f"{message} is an even number")

运行结果:

3 is an even number
5 is an even number
7 is an even number
9 is an even number

4 while操作列表和字典

操作列表:

variable=['nmot','rl_w','zwout','rl_w','zwspace','zwout']
print(variable)
while 'rl_w' in variable:
    variable.remove('rl_w')#移除rl_w变量
print(variable)

运行结果:

['nmot', 'rl_w', 'zwout', 'rl_w', 'zwspace', 'zwout']
['nmot', 'zwout', 'zwspace', 'zwout']

操作字典:

students_info={}
flag=True
while flag:
    name=input("Input your name:")
    gender=input("input your sexual distinction:")
    students_info[name]=gender
    repeat=input("Investigation finished (yes/no):")
    if repeat == 'yes':
        flag=False
for name,gender in students_info.items():
    print(f"{name} is a {gender}.")

运行结果:

Input your name:allen
input your sexual distinction:boy
Investigation finished (yes/no):no
Input your name:lucy
input your sexual distinction:girl
Investigation finished (yes/no):no
Input your name:jack
input your sexual distinction:boy
Investigation finished (yes/no):no
Input your name:allen
input your sexual distinction:girl
Investigation finished (yes/no):yes
allen is a girl.
lucy is a girl.
jack is a boy.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值