Python之while循环、if语句
while 循环
while 循环在条件为真时,会一直重复执行这段语句块。while 循环也称为无限循环。
在while 循环中使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志(flag),充当程序的交通信号灯。可以让程序在标志为 True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行。
prompt="Enter 'quit' to end the program."
prompt+="\nTell me something,and I will repeat it back to you:"
active=True
while active:
message=input(prompt)
if message=='quit':
active=False
else:
print(message)
输入值及输出结果:
Enter ‘quit’ to end the program.
Tell me something,and I will repeat it back to you:hello
hello
Enter ‘quit’ to end the program.
Tell me something,and I will repeat it back to you:python
python
Enter ‘quit’ to end the program.
Tell me something,and I will repeat it back to you:quit
使用while 循环处理列表和字典
1.在列表之间移动元素
for循环是一种遍历列表的有效方式,但不应在for循环中修改列表,否则将导致python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用while循环。
假设有一个列表包含新注册但还未验证的网站用户。验证这些用户后,如何将他们移动到另一个已验证用户列表中呢?一种方法是使用一个while循环,在验证用户的同时将其从未验证的用户中提取出来,再将其加入另一个已验证用户列表中。
# 创建一个待验证用户列表和用于存储已验证用户列表
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
# 验证每个用户,直到没有未验证用户为止。
# 将每个经过验证的用户都移动到已验证用户列表中。
while unconfirmed_users: #注意:此处while将不断运行,直到该列表变成空时停止运行!!!
print('--',unconfirmed_users,'--')
current_user = unconfirmed_users.pop() # pop()默认弹出列表最后一个元素
print(f"Verifying user:{current_user.title()}")
confirmed_users.append(current_user)
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user)
输出结果:
– [‘alice’, ‘brian’, ‘candace’] –
Verifying user:Candace
– [‘alice’, ‘brian’] –
Verifying user:Brian
– [‘alice’] –
Verifying user:Alice
The following users have been confirmed:
candace
brian
alice
利用whlie循环列表时要注意代码不要写出无限循环!!!
sandwich_orders = ['veggie', 'grilled cheese', 'turkey', 'roast beef']
while sandwich_orders: #注意:此处while将不断运行,直到该列表变成空时停止运行!!
sandwich_orders.pop()
print(sandwich_orders)
输出结果:
[‘veggie’, ‘grilled cheese’, ‘turkey’]
[‘veggie’, ‘grilled cheese’]
[‘veggie’]
[]
2.删除为特定值的所有列表元素
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat'in pets: #当'cat'in pets为True时循环会一直进行,直到'cat'in pets为False时循环结束
pets.remove('cat')
print('删除cat后的列表:',pets)
输出结果:
[‘dog’, ‘cat’, ‘dog’, ‘goldfish’, ‘cat’, ‘rabbit’, ‘cat’]
删除cat后的列表: [‘dog’, ‘dog’, ‘goldfish’, ‘rabbit’]
3.使用用户输入来填充字典
下面创建一个调查程序,收集被调查者名字和回答,并将收集的数据存储在一个字典中。
responses = {}
# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
name = input("What is your name? ")
response = input("Which mountain would you like to climb someday? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/no)")
if repeat == 'no':
polling_active = False
print("--- Poll Results ---")
for name,response in responses.items():
print(f"{name.title()} would like to climb {response.title()}")
输入值及输出结果:
What is your name? eric
Which mountain would you like to climb someday? denali
Would you like to let another person respond? (yes/no)yes
What is your name? lynn
Which mountain would you like to climb someday? devil’s thumb
Would you like to let another person respond? (yes/no)no
— Poll Results —
Eric would like to climb Denali
Lynn would like to climb Devil’S Thumb
while 循环的一种扩展模式
语法格式如下:
while <条件>:
<语句块1>
else:
<语句块2>
当这种扩展模式中的 while 循环执行完成后,程序会继续执行 else 语句的内容。例如:
a, b = 'Python', 0
while b < len(a):
print(a[b])
b += 1
else:
print('程序执行完成!')
输出结果:
P
y
t
h
o
n
程序执行完成!
或者可以理解为在条件语句为 False 时执行 else 后的语句块:
cou = 0
while cou <= 3:
print(cou,'小于等于3')
cou += 1
else:
print(cou,'大于3')
输出结果:
0 小于等于3
1 小于等于3
2 小于等于3
3 小于等于3
4 大于3
注:与 for 循环类似,如果循环体内遇到 break 语句等不正常退出循环,则不执行 else 分支。
pass 在循环中的使用
pass 是空语句,旨在保持程序结构的完整性。pass 不做任何事情,一般用作占位语句。
for letter in 'hello':
if letter == 'l':
pass
print('执行pass语句')
print('当前的字母:',letter)
输出结果:
当前的字母: h
当前的字母: e
执行pass语句
当前的字母: l
执行pass语句
当前的字母: l
当前的字母: o
if 语句
单分支、二分支、多分支结构
语法格式如下:
"""单分支结构"""
if <条件>:
<语句块>
"""二分支结构"""
if <表达式>:
<语句块1>
else:
<语句块2>
"""多分支结构"""
if <条件1>:
<语句块1>
elif <语句1>:
<语句块2>
...
else:
<语句块n>
二分支结构还有一种简洁的表达形式:
"""二分支结构的简洁表达"""
<表达式1> if <条件> else <表达式2>
也就是三元运算符:
"""三元运算符"""
X if C else Y
C 为条件表达式,X 是 C 为 True 时的结果,Y 是 C 为 False 时的结果。
举例说明二分支的简洁表达:
s = eval(input("请输入一个整数:"))
token = "能够" if s%3 == 0 and s%5 == 0 else "不能"
print("这个数字{}{}同时被3和5整除".format(s,token))
输入值及输出结果:
请输入一个整数:30
这个数字30能够同时被3和5整除
举例说明多分支结构和 if 嵌套:
n = eval(input('请输入一个整数:'))
if n%2 == 0:
if n%3 == 0:
print('可以被2和3整除。')
elif n%4 == 0:
print('可以被2和4整除。')
else:
print('可以被2整除,但不能被3和4整除。')
else:
if n%3 == 0:
print('可以被3整除,但不能被2整除。')
else:
print('不能被2和3整除。')
输入值及输出结果:
请输入一个整数:15
可以被3整除,但不能被2整除。
注意:
1.在设置条件时要注意使用 else 语句!else 语句是一条包罗万象的语句,只要不满足任何 if 和 elif 的条件测试,其中的代码块就会执行,但可能引入无效甚至恶意的数据。如果知道最终要测试的条件,应考虑使用一个 elif 代码块来代替 else 代码块。这样就能肯定,仅当满足相应的条件时,代码才会执行。
2.如果只想执行一个代码块,就是用 if - elif - else 结构,如果要执行多个代码块,就使用一系列独立的 if 语句。
3.不管有多少分支,程序执行其中一个分支之后,其他分支不再执行。当多分支中的多个条件都满足时,系统只执行第一个满足条件对应的代码块。
4.在判断条件时,遇到 False、None 、所有类型的数字 0 (包括浮点型、长整型和其他类型)、空序列(空字符串、空元组、空列表、空字典等)都为假或者 0 ,即不执行该语句块。
用 if 语句确定列表不是空的
requested_toppings=[]
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}")
print('\nFinished making your pizza!')
else:
print('Are you sure you want a plain pizza?')
输出结果:
Are you sure you want a plain pizza?
用 if 语句处理多个列表
available_toppings=['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings=['mushrooms','french fries','extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print(f"Adding {requested_topping.title()}")
else:
print(f"Sorry,we don't have {requested_topping.title()}")
print("\nFinished making your pizza!")
输出结果:
Adding Mushrooms
Sorry,we don’t have French Fries
Adding Extra Cheese
Finished making your pizza!