程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python while statement

編輯:Python

1 Exit if conditions are not met

adopt input Input information , Determine whether to continue while The content in

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")

Running results :

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 adopt break sign out

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

Running results :

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 adopt continue continue while loop

message=1
while message < 10:
message += 1;
if int(message) % 2 == 0:
continue # If it's even , be while The loop executes from scratch , Do not execute the following statement
# Print odd numbers
print(f"{message} is an even number")

Running results :

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

4 while Action lists and dictionaries

Operation list :

variable=['nmot','rl_w','zwout','rl_w','zwspace','zwout']
print(variable)
while 'rl_w' in variable:
variable.remove('rl_w')# remove rl_w Variable
print(variable)

Running results :

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

Operation Dictionary :

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}.")

Running results :

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.


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved