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.