《python编程从入门到实践》5-7章
第 5 章 if 语句
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
#Audi
#BMW
#Subaru
#Toyota
5.2 条件测试
5.2.5 检查多个条件
-
使用 and 检查多个条件
age_0 = 22 age_1 = 18 print(age_0 >= 21 and age_1 >= 21) #false age_1 = 22 print(age_0 >= 21 and age_1 >= 21) #true为了改善可读性,可将每个条件测试都分别放在一对括号内
(age_0 >= 21) and (age_1 >= 21) -
使用 or 检查多个条件
age_0 = 22 age_1 = 18 print(age_0 >= 21 or age_1 >= 21) #true age_0 = 18 print(age_0 >= 21 or age_1 >= 21) #false
5.2.6 检查特定的值是否在列表中
if xx in xx
requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings) # true
print('pepperoni' in requested_toppings) # false
requested_toppings = ['mushrooms', 'onions', 'pineapple']
if 'mushrooms' in requested_toppings:
print("aaa") # aaa
5.2.7 检查特定的值是否不在列表中
if xx not in xx
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()}, you can post a response if you wish.")
else:
print(f"{user.title()}, you can do it.")
# Marie, you can post a response if you wish.
5.3 if 语句
5.3.1 简单的 if 语句
if conditional_test:
do something
age = 19
if age >= 18:
print("You are old enough to vote!")
5.3.2 if-else 语句
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.") # 输出这2句
print("Please register to vote as soon as you turn 18!")
5.3.3 if-elif-else 语句
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.") # 执行这句
else:
print("Your admission cost is $40.")
5.4 使用 if 语句处理列表
5.4.2 确定列表非空
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?") # 输出这句
可以这样写
if len(requested_toppings) == 0:
print("Are you sure you want a plain pizza?")
第 6 章 字典
在 Python 中,字典(dictionary)是一系列键值对,字典用放在花括号({})中的一系列键值对表示
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color']) # green
print(alien_0['points']) # 5
6.2 使用字典
6.2.2 添加键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0) # {'color': 'green', 'points': 5}
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0) # {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
6.2.4 修改字典中的值
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")
6.2.5 删除键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0) # {'color': 'green'}
6.2.7 使用 get() 来访问值
如果指定的键不存在,就将出错.
可使用 get() 方法在指定的键不存在时返回一个默认值
alien_0 = {'color': 'green', 'speed': 'slow'}
# print(alien_0['points']) ---- 报错
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
# No point value assigned.
在调用 get() 时,如果没有指定第二个参数且指定的键不存在,Python 将 返回值 None,这个特殊的值表示没有相应的值。这并非错误,None 只是一个表 示所需值不存在的特殊值
6.3 遍历字典
6.3.1 遍历所有的键值对
for 语句的第二部分包含字典名和方法 items(),这个方法返回一个键值对列表
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print(f"\nKey: {key}")
print(f"Value: {value}")
输出
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
在循环中使用变量 name 和 language,而 不是 key 和 value。这让人更容易明白循环的作用:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(f"{name.title()}'s favorite language is {language.title()}.")
输出
Jen's favorite language is Python.
Sarah's favorite language is C.
Edward's favorite language is Rust.
Phil's favorite language is Python.
6.3.2 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
for name in favorite_languages.keys():
相等于
for name in favorite_languages:
但是不建议。
6.3.3 按特定的顺序遍历字典中的所有键
用sorted()特定顺序排序
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(f"{name.title()}, thank you for taking the poll.")
输出
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
6.3.4 遍历字典中的所有值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
输出
The following languages have been mentioned:
Python
C
Rust
Python
这种做法提取字典中所有的值,而没有考虑值是否有重复。当涉及的值很少时,这也许不是问题,但如果被调查者很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set)。集合中的每个元素都必须是独一无二的:
for language in set(favorite_languages.values()):
print(language.title())
6.4 嵌套
6.4.1 字典列表
创建一个包含三个外星人的列表:
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
更符合现实的情形是,外星人不止三个,而且每个外星人都是用代码自动生成的。在下面的示例中,使用 range() 生成了 30 个外星人:
# 创建一个用于存储外星人的空列表
aliens = []
# 创建 30 个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 显示前 5 个外星人
for alien in aliens[:5]:
print(alien)
print("...")
# 显示创建了多少个外星人
print(f"Total number of aliens: {len(aliens)}")
输出
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30
想象一下,随着游戏的进行,有些外星人会变色且加快移动速度。在必要时,可使用 for 循环和 if 语句来修改某些外形人的颜色。例如,要将前三个外星人修改为黄色、速度中等且值 10 分,可这样做:
# 创建一个用于存储外星人的空列表
aliens = []
# 创建 30 个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
# 显示前 5 个外星人
for alien in aliens[:5]:
print(alien)
print("...")
6.4.2 在字典中存储列表
favorite_languages = {
'jen': ['python', 'rust'],
'sarah': ['c'],
'edward': ['rust', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{language.title()}")
注意:列表和字典的嵌套层级不应太多。如果嵌套层级比前面的示例多得多,很可能有更简单的解决方案。
第 7 章 用户输入和 while 循环
如何接受用户输入,让程序对其进行处理。
7.1 input() 函数的工作原理
input() 函数让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python 将其赋给一个变量,以便使用。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
输出:
Tell me something, and I will repeat it back to you: Hello everyone!
Hello everyone! # 输入的 --> Hello everyone!
input() 函数接受一个参数,即要向用户显示的提示(prompt),让用户知道该输入什么样的信息。在这个示例中,当 Python 运行第一行代码时,用户将看到提示“Tellme something, and I will repeat it back to you:”。程序等待用户输入,并在用户按回车键后继续运行。用户的输入被赋给变量 message,接下来的 print(message) 将输入呈现给用户
7.1.1 编写清晰的提示
有时候,提示可能超过一行。例如,你可能需要指出获取特定输入的原因。在这种情况下,可先将提示赋给一个变量,再将这个变量传递给 input() 函数。这样,即便提示超过一行,input() 语句也会非常清晰
prompt = "If you share your name, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")
在第二行中,运算符 += 在赋给变量 prompt 的字符串末尾追加一个字符串
7.1.2 使用 int() 来获取数值输入
age = input("How old are you? ")
print(age >= 18)
报错
TypeError: '>=' not supported between instances of 'str' and 'int'
可使用函数 int() 将输入的字符串转换为数值, 改为
age = input("How old are you? ")
print(int(age) >= 18)
7.1.3 求模运算符 (余数%)
>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7 % 3
1
7.2 while
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
7.2.2 让用户选择何时退出
可以使用 while 循环让程序在用户愿意时不断地运行, 我们在其中定义了一个退出值,只要用户输入的不是这个值,程序就将一直运行
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. ee
ee
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. quit
quit
7.2.4 使用 break 退出循环
break 语句用于控制程序流程,可用来控制哪些代码行将执行、哪些代码行不执行,从而让程序按你的要求执行你要执行的代码。
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I'd love to go to {city.title()}!")
7.2.5 在循环中使用 continue
例如,来看一个从 1 数到 10,只打印其中奇数的循环:
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
输出
1
3
5
7
9
7.3 while 处理列表和字典
7.3.1 在列表之间移动元素
假设有一个列表包含新注册但还未验证的网站用户。验证这些用户后,如何将他们移到已验证用户列表中呢?一种办法是使用一个 while 循环,在验证用户的同时将其从未验证用户列表中提取出来,再将其加入已验证用户列表。代码可能类似于下面这样:
# 首先,创建一个待验证用户列表
# 和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到没有未验证用户为止
# 将每个经过验证的用户都移到已验证用户列表中
while unconfirmed_users:
current_user = unconfirmed_users.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.title())
输出
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
Candace
Brian
Alice
7.3.2 删除为特定值的所有列表元素
我们使用 remove() 函数来删除列表中的特定值。
如果要删除列表中所有为特定值的元素,该怎么办呢?
pets = ['dog', 'cat', 'dog','cat', 'goldfish', 'cat', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat', 'cat']
# print(pets)
# 方案1: 这个只需要执行 4 次 (cat 出现的次数)
while 'cat' in pets:
pets.remove('cat')
print(pets)
# 方案2(错误): 这个需要5次,但是有问题
# for pet in pets:
# if pet == 'cat':
# pets.remove(pet)
# print(pets)
方案一的结果
['dog', 'dog', 'cat', 'goldfish', 'cat', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'cat', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
方案二的结果:当你在遍历列表的同时对其进行删除操作,会使列表的索引发生变化,进而导致部分元素被遗漏
['dog', 'cat', 'dog', 'cat', 'goldfish', 'cat', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'cat', 'goldfish', 'cat', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'cat', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat', 'cat', 'cat']
['dog', 'dog', 'goldfish', 'rabbit', 'cat', 'cat', 'cat']
方案2的修正:
# 方案3:使用切片遍历列表
for pet in pets[:]: # 创建列表的副本进行遍历
if pet == 'cat':
pets.remove(pet)
print(pets) # 输出: ['dog', 'dog', 'goldfish', 'rabbit']
7.3.3 使用用户输入填充字典
可以使用 while 循环提示用户输入任意多的信息。下面创建一个调查程序,其中的循环在每次执行时都提示输入被调查者的名字和回答
responses = {}
# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
# 提示输入被调查者的名字和回答
name = input("\nWhat 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("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
案例
What is your name? tange sansan
Which mountain would you like to climb someday? tai shan
Would you like to let another person respond? (yes/no) yes
What is your name? liu liu
Which mountain would you like to climb someday? e mei shan
Would you like to let another person respond? (yes/no) no
--- Poll Results ---
tange sansan would like to climb tai shan.
liu liu would like to climb e mei shan.
这个程序首先定义了一个空字典(responses),并设置了一个标志(polling_active)用于指出调查是否继续。只要 polling_active 为 True,Python 就运行 while 循环中的代码

浙公网安备 33010602011771号