0%

Python学习笔记-4-条件循环

本章节学习Python中的 If 和 While 循环。

1 If 循环

1.1 简单的if语句

一个示例:假设你有一个汽车列表,并想将其中每辆车的名称打印出来。对于大多数汽车,都应以首字母大写的方式打印其名称,但对于汽车名为“bmw”,应以全大写的方式打印。

1
2
3
4
5
6
7
cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
Audi
BMW
Subaru
Toyota

1.2 if-elif-else语句

根据年龄段收费:4岁以下免费;4~18岁收费五元;18岁(含)以上收费10元

1
2
3
4
5
6
7
8
age = 12

if age < 4:
print('Your admission cost is 0.')
elif age < 18:
print('Your admission cost is 5.')
else:
print('Your admission cost is 10.')
Your admission cost is 5.
1
2
3
4
5
6
7
8
9
10
11
# 简洁代码
age = 12

if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10

print('Your admission cost is ' + str(price) + '.')
Your admission cost is 5.
1
2
3
4
5
6
7
8
9
10
11
# 省略else代码块。Python并不要求if-elif-else结构后面必须有else代码块。
age = 12

if age < 4:
price = 0
elif age < 18:
price = 5
elif age >=18:
price = 10

print('Your admission cost is ' + str(price) + '.')
Your admission cost is 5.

在if语句中,将列表名用在条件表达式中时,Python将在列表至少包含一个元素时返回True,并在列表为空时返回False。可用于检查是否时空列表。

1
2
3
4
5
cars = []
if cars:
print("这是一个非空列表")
else:
print("这是一个空列表")
这是一个空列表
  • 使用多个列表。

下面的示例演示了顾客要求的配料和比萨店里有的配料,是否满足顾客需求

1
2
3
4
5
6
7
8
9
10
requested_toppings = ['mushrooms', 'french fish', 'extra cheese']
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']

for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print('Adding ' + requested_topping + '.')
else:
print("Sorry, we don't have " + requested_topping + '.')

print('\nFinished making your pizza!')
Adding mushrooms.
Sorry, we don't have french fish.
Adding extra cheese.

Finished making your pizza!

2 While 循环

2.1 while循环的简单使用

for循环用于针对集合中的每个元素,而while循环不断运行,直到制定的条件不满足为止

1
2
3
4
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
1
2
3
4
5
1
2
3
4
5
6
7
prompt = "\nTell me sth, and I'll repeat it back to you: "
prompt += "\nEnter 'quit' to end program."

message = " "
while message != 'quit':
message = input(prompt)
print(message)
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. Hello,word!


Hello,word!



Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. quit


quit
1
2
3
4
5
6
7
8
prompt = "\nTell me sth, and I'll repeat it back to you: "
prompt += "\nEnter 'quit' to end program."

message = " "
while message != 'quit':
message = input(prompt)
if message != 'quit':
print(message)
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. Hello,world!


Hello,world!

Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. quit

2.2 在while循环中添加标志

在要求很多条件都满足才能继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量被称为标志,充当了程序的交通信号灯。

1
2
3
4
5
6
7
8
9
10
prompt = "\nTell me sth, and I'll repeat it back to you: "
prompt += "\nEnter 'quit' to end program."

active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. Hello,world!


Hello,world!

Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. quit

2.3 使用break退出循环

1
2
3
4
5
6
7
8
9
prompt = "\nTell me sth, and I'll repeat it back to you: "
prompt += "\nEnter 'quit' to end program."

while True:
message = input(prompt)
if message == 'quit':
break
else:
print(message)
Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. Hello,world!


Hello,world!

Tell me sth, and I'll repeat it back to you:
Enter 'quit' to end program. quit

2.4 在循环中使用continue

1
2
3
4
5
6
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
1
3
5
7
9

2.5 while循环处理列表和字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 假设有一个列表,其中包含新注册但还未验证的用户;
# 验证这些用户后,再将他们移动到另一个已验证用户列表中。

# 首先创建一个待验证的用户列表和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = [ ]

# 验证每个用户,直到没有未验证用户为止,将每个经过验证的用户都移动到已验证的用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print("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.title())
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice
1
2
3
4
5
6
7
8
# 使用while和remove()删除包含特定值的所有列表元素
pets = ['dog', 'cat', 'dog', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
pets.remove('cat')

print(pets)
['dog', 'cat', 'dog', 'rabbit', 'cat']
['dog', 'dog', 'rabbit']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 使用用户输入来填充字典

responses = {}

# 设置一个标志,指出调查是否继续
polling_active = True

while polling_active:
# 提示用户输入调查者的名字和回答
name = input("\nWhat's 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("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name.title()} would like to climb {response.title()}.")
What's your name?  jack
Which mountain would you like to climb someday?  jinyun mountain
Would you like to let another person respond? (yes/no) no

--- Poll Results ---
Jack would like to climb Jinyun Mountain.