参考引用
- Python编程:从入门到实践(第2版)
message = "Hello Python world!"
print(message)
message = "Hello Python Crash Course world!"
print(message)
Hello Python world!
Hello Python Crash Course world!
"This is a string."
'This is also a string.'
'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
name = "Ada Lovelace"
print(name.title()) # 单词首字母大写
print(name.upper())
print(name.lower())
Ada Lovelace
ADA LOVELACE
ada lovelace
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
message = f"Hello, {full_name.title()}!"
print(message)
Hello, Ada Lovelace!
print("\tPython")
print("Languages:\nPython\nC\nJavaScript")
Python
Languages:
Python
C
JavaScript
favorite_language = 'python '
print(favorite_language)
favorite_language = favorite_language.rstrip()
print(favorite_language)
'python '
'python'
print(2 + 3, 3 - 2, 2 * 3, 3 / 2, 3 ** 2, (2 + 3) * 4)
5 1 6 1.5 9 20
print(0.1 + 0.1, 2 * 0.1, 0.2 + 0.1, 3 * 0.1)
# 结果包含的小数位数可能是不确定的
0.2 0.2 0.30000000000000004 0.30000000000000004
print(4 / 2, 1 + 2.0, 2 * 3.0, 3.0 ** 2)
2.0 3.0 6.0 9.0
universe_age = 14_000_000_000
print(universe_age)
14000000000
x, y, z = 0, 0, 0
MAX_CONNECTIONS = 5000
print(MAX_CONNECTIONS)
# 向大家问好。
print("Hello Python people!")
Hello Python people!
列表由一系列按特定顺序排列的元素组成
在 Python 中,用方括号([])表示列表,并用逗号分隔其中的元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
print(bicycles[0].title())
trek
Trek
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[1]) # 访问第 2 个元素
print(bicycles[3]) # 访问第 4 个元素
print(bicycles[-1]) # 访问最后一个元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
My first bicycle was a Trek.
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']
在列表末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
['honda', 'yamaha', 'suzuki']
在列表中插入元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
['ducati', 'honda', 'yamaha', 'suzuki']
使用 del 语句删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
使用方法 pop() 删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
弹出列表中任何位置处的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(1)
print(f"The first motorcycle I owned was a {first_owned.title()}.")
The first motorcycle I owned was a Yamaha.
根据值删除元素
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
Python 方法 sort() 能够较为轻松地对列表进行排序。假设有一个汽车列表,并要让其中的汽车按字母顺序排列
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
还可以按与字母顺序相反的顺序排列列表元素
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse = True)
print(cars)
['toyota', 'subaru', 'bmw', 'audi']
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:", cars)
print("Here is the sorted list:", sorted(cars))
print("Here is the original list again:", cars)
Here is the original list: ['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list: ['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again: ['bmw', 'audi', 'toyota', 'subaru']
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[3])
Traceback (most recent call last):
File "motorcycles.py", line 2, in <module>
print(motorcycles[3])
IndexError: list index out of range
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
Thank you, everyone. That was a great magic show!
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
File "magicians.py", line 3
print(magician)
^
IndentationError: expected an indented block
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
message = "Hello Python world!"
print(message)
File "hello_world.py", line 2
print(message)
^
IndentationError: unexpected indent
for value in range(1, 5):
print(value)
1
2
3
4
要创建数字列表,可使用函数 list() 将 range() 的结果直接转换为列表。如果将 range() 作为 list() 的参数,输出将是一个数字列表
numbers = list(range(1, 6))
print(numbers)
[1, 2, 3, 4, 5]
使用函数 range() 时,还可指定步长。为此,可给这个函数指定第三个参数,Python 将根据这个步长来生成数
even_numbers = list(range(2, 11, 2))
print(even_numbers)
[2, 4, 6, 8, 10]
将前 10 个整数的平方加入一个列表中
squares = []
for value in range(1,11):
squares.append(value**2) # 计算每个值的平方,并立即将结果附加到列表 squares 的末尾
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits), max(digits), sum(digits))
0 9 45
# for 循环将值 1~10 提供给表达式 value**2,此处无冒号
squares = [value**2 for value in range(1, 11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数 range() 一样,Python 在到达第二个索引之前的元素后停止。要输出列表中的前三个元素,需要指定索引 0 和 3,这将返回索引为 0、1 和 2 的元素
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
['charles', 'martina', 'michael']
如果没有指定第一个索引,Python 将自动从列表开头开始
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
['charles', 'martina', 'michael', 'florence']
要让切片终止于列表末尾
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
['michael', 'florence', 'eli']
负数索引返回离列表末尾相应距离的元素,因此可以输出列表末尾的任意切片。例如,如果要输出名单上的最后三名队员
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
['michael', 'florence', 'eli']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
Here are the first three players on my team:
Charles
Martina
Michael
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] # 将 my_foods 的元素复制到新列表 friend_foods 中
# 如果只是将 my_foods 赋给 friend_foods ,就不能得到两个列表
# friend_foods = my_foods
# 在每个列表中都添加一种食品
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
200
50
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
200
50
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
Original dimensions:
200
50
Modified dimensions:
400
100
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
Audi
BMW
Subaru
Toyota
car = 'bmw'
print(car == 'bmw')
print(car == 'audi')
True
False
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
Hold the anchovies!
answer = 17
if answer != 42:
print("That is not the correct answer. Please try again!")
print(answer < 21, answer > 21, answer >= 21, answer <= 21)
That is not the correct answer. Please try again!
True False False True
可能想同时检查多个条件。例如,有时候需要在两个条件都为 True 时才执行相应的操作,而有时候只要求一个条件为 True
使用 and 检查多个条件
age_0 = 22
age_1 = 18
print((age_0 >= 21) and (age_1 >= 21))
False
使用 or 检查多个条件
age_0 = 22
age_1 = 18
print((age_0 >= 21) or (age_1 >= 21))
True
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 not in available_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!")
Sorry, we don't have mushrooms.
Adding french fries.
Sorry, we don't have extra cheese.
Finished making your pizza!
age = 19
if age >= 18:
print("You are old enough to vote!")
You are old enough to vote!
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.")
print("Please register to vote as soon as you turn 18!")
Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
print(f"Your admission cost is ${price}.")
Your admission cost is $25.
age = 66
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20
# Python 并不要求 if-elif 结构后面必须有 else 代码块
print(f"Your admission cost is ${price}.")
Your admission cost is $20.
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")
Adding mushrooms.
Adding extra cheese.
Finished making your pizza!
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
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}.")
else:
print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!")
Adding mushrooms.
Sorry, we don't have french fries.
Adding extra cheese.
Finished making your pizza!
alien_0 = {'color' : 'green', 'points' : 5}
alien_0 = {'color': 'green'}
print(alien_0['color'])
green
alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print(f"You just earned {new_points} points!")
You just earned 5 points!
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
{'color': 'green', 'points': 5}
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']}.")
The alien is green.
The alien is now yellow.
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green'}
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")
Sarah's favorite language is C.
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
No point value assigned.
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
# items() 返回一个键值对列表
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
在不需要使用字典中的值时,方法 keys() 可以遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())
Jen
Sarah
Edward
Phil
还可使用方法 keys() 确定某个人是否接受了调查。下面的代码确定 Erin 是否接受了调查
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")
Erin, please take our poll!
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'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.
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'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
Ruby
Python
...
for language in set(favorite_languages.values()):
print(language.title())
...
The following languages have been mentioned:
Ruby
C
Python
可使用一对花括号直接创建集合,并在其中用逗号分隔元素
- 集合和字典很容易混淆,因为它们都是用一对花括号定义的
- 当花括号内没有键值对时,定义的很可能是集合
- 不同于列表和字典,集合不会以特定的顺序存储元素
# 创建一个用于存储外星人的空列表
aliens = []
# 创建 30 个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 使用 for 循环和 if 语句来修改部分外形人的颜色
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# 使用一个切片来打印前 5 个外星人
for alien in aliens[:5]:
print(alien)
print("...")
print(f"Total number of aliens: {len(aliens)}")
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30
# 创建一个字典,存储所点比萨的信息
pizza = {
'crust': 'thick',
# 与 toppings 相关联的值是一个列表
'toppings': ['mushrooms', 'extra cheese'],
}
# 如果函数调用 print() 中的字符串很长,可以在合适的位置分行
# 只需要在每行末尾都加上引号,同时对于除第一行外的其他各行,都在行首加上引号并缩进
print(f"You ordered a {pizza['crust']}-crust pizza "
"with the following toppings:")
# 从字典中提取配料列表
for topping in pizza['toppings']:
print("\t" + topping)
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', '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()}")
Jen's favorite languages are:
Python
Ruby
Sarah's favorite languages are:
C
Edward's favorite languages are:
Ruby
Go
Phil's favorite languages are:
Python
Haskell
# 字典 users 中包含两个键:用户名 'aeinstein' 和 'mcurie'
# 与每个键相关联的值都是一个字典,其中包含用户的名、姓和居住地
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print(f"\nUsername: {username}")
# 开始访问内部的字典。变量 user_info 包含用户信息字典
# 而该字典包含三个键:'first'、'last' 和 'location'
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False # 退出循环
else:
print(message)
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello
Hello
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 48:
print("\nYou're tall enough to ride!")
else:
print("\nYou'll be able to ride when you're a little older.")
How tall are you, in inches? 50
You're tall enough to ride!
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")
Enter a number, and I'll tell you if it's even or odd: 9
The number 9 is odd.
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
1
3
5
7
9
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
# 以 while True 打头的循环将不断运行,直到遇到 break 语句
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I'd love to go to {city.title()}!")
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) Beijing
I'd love to go to Beijing!
Please enter the name of a city you have visited:
(Enter 'quit' when you are finished.) quit
Process finished with exit code 0
# 这个循环将没完没了地运行!
x = 1
while x <= 5:
print(x)
1
1
1
...
# 首先,创建一个待验证用户列表和一个用于存储已验证用户的空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# 验证每个用户,直到列表 unconfirmed_users 变成空的
while unconfirmed_users:
# 从列表 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
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']
# 定义了一个空字典
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? Tom
Which mountain would you like to climb someday? hah
Would you like to let another person respond? (yes/ no) yes
What is your name? Bob
Which mountain would you like to climb someday? haha
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
Tom would like to climb hah.
Bob would like to climb haha.
# 使用关键字 def 来告诉 Python 要定义一个函数
# 紧跟在 def greet_user() 后面的所有缩进行构成了函数体
# 文档字符串用三引号括起,Python 使用它们来生成有关程序中函数的文档
def greet_user(username):
"""显示简单的问候语"""
print(f"Hello, {username.title()}!")
# 要调用函数,可依次指定函数名以及用圆括号括起的必要信息
greet_user('jesse')
Hello, Jesse!
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster', 'harry')
I have a hamster.
My hamster's name is Harry.
def describe_pet(animal_type, pet_name):
"""显示宠物的信息"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
# 明确地指出了各个实参对应的形参
# 关键字实参的顺序无关紧要,因为 Python 知道各个值该赋给哪个形参
describe_pet(animal_type = 'hamster', pet_name = 'harry')
I have a hamster.
My hamster's name is Harry.
# 将形参 animal_type 设置默认值为'dog'
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息。"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name = 'willie')
# 由于显式地给 animal_type 提供了实参,Python 将忽略这个形参的默认值
# describe_pet(pet_name='harry', animal_type='hamster')
I have a dog.
My dog's name is Willie.
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = f"{first_name} {last_name}"
return full_name.title()
# 提供一个变量,以便将返回的值赋给它
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
Jimi Hendrix
# 为了让中间名变成可选的,可给形参 middle_name 指定一个空的默认值
# 并在用户没有提供中间名时不使用这个形参
def get_formatted_name(first_name, last_name, middle_name=''):
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
Jimi Hendrix
John Lee Hooker
# 可将 None 视为占位值
def build_person(first_name, last_name, age=None):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age = 27)
print(musician)
{'first': 'jimi', 'last': 'hendrix', 'age': 27}
def get_formatted_name(first_name, last_name):
full_name = f"{first_name} {last_name}"
return full_name.title()
# 这是一个无限循环!
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!")
Please tell me your name:
(enter 'q' at any time to quit)
First name: Tom
Last name: Bun
Hello, Tom Bun!
...
def greet_users(names):
"""向列表中的每位用户发出简单的问候"""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
Hello, Hannah!
Hello, Ty!
Hello, Margot!
# 包含两个形参:一个需要打印的设计列表和一个打印好的模型列表
def print_models(unprinted_designs, completed_models):
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表 completed_models 中
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
# 包含一个形参:打印好的模型列表
def show_completed_models(completed_models):
# 显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case
The following models have been printed:
dodecahedron
robot pendant
phone case
编写函数时,如果发现它执行的任务太多,请尝试将这些代码划分到两个函数中。总是可以在一个函数中调用另一个函数,这有助于将复杂的任务划分成一系列步骤
# 切片表示法[:] 创建列表的副本
function_name(list_name_[:])
# 在 8.4.1 中,如果不想清空未打印的设计列表,可像下面这样调用 print_models()
print_models(unprinted_designs[:], completed_models)
# 形参名 *toppings 中的星号让 Python 创建一个名为 toppings 的空元组
# 并将收到的所有值都封装到这个元组中
def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
# 不管收到一个值还是三个值,这个函数都能妥善处理
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
Making a pizza with the following toppings:
- pepperoni
Making a pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
def make_pizza(size, *toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
经常会看到通用形参名 *args ,它也收集任意数量的位置实参
# 形参 **user_info 中的两个星号让 Python 创建一个名为 user_info 的空字典
# 并将收到的所有名称值对都放到这个字典中
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含知道的有关用户的一切"""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}
# pizza.py
def make_pizza(size, *toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
# making_pizzas.py(与 pizza.py 处于同一目录)
# 该行代码让 Python 打开文件 pizza.py,并将其中的所有函数都复制到这个程序中
import pizza
# 要调用被导入模块中的函数,可指定被导入模块的名称 pizza 和函数名 make_pizza(),并用句点分隔
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
from module_name import function_name
from module_name import function_0, function_1, function_2
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
class Dog:
# 其中形参 self 必不可少,而且必须位于其他形参的前面
# Python 调用这个方法来创建 Dog 实例时,将自动传入实参 self
def __init__(self, name, age):
"""初始化属性 name 和 age"""
# 以 self 为前缀的变量可供类中的所有方法使用,可以通过类的任何实例来访问
self.name = name
self.age = age
# 每个与实例相关联的方法调用都自动传递实参 self
# 它是一个指向实例本身的引用,让实例能够访问类中的属性和方法
def sit(self):
"""模拟小狗收到命令时蹲下"""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""模拟小狗收到命令时打滚"""
print(f"{self.name} rolled over!")
# 创建表示特定小狗的实例
my_dog = Dog('Willie', 6)
your_dog = Dog('Lucy', 3)
print(f"My dog's name is {my_dog.name}.") # 要访问实例的属性,可使用句点表示法
print(f"My dog is {my_dog.age} years old.")
# 根据 Dog 类创建实例后,就能使用句点表示法来调用 Dog 类中定义的任何方法
my_dog.sit()
my_dog.roll_over()
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie rolled over!
class Car:
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
# 创建实例时,有些属性无须通过形参来定义,可在方法 __init__() 中为其指定默认值
self.odometer_reading = 0
def get_descriptive_name(self):
"""返回整洁的描述性信息"""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""打印一条指出汽车里程的消息"""
print(f"This car has {self.odometer_reading} miles on it.")
# 这个方法接受一个里程值,并将其赋给 self.odometer_reading
def update_odometer(self, mileage):
"""将里程表读数设置为指定的值,禁止将里程表读数往回调"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
# 将属性值递增特定的量,而不是将其设置为全新的值
def increment_odometer(self, miles):
"""将里程表读数增加指定的量"""
self.odometer_reading += miles
# 根据 Car 类创建了一个实例
my_used_car = Car('subaru', 'outback', 2015)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23_500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()
2015 Subaru Outback
This car has 23500 miles on it.
This car has 23600 miles on it.
class Car:
# 在既有类的基础上编写新类时,通常要调用父类的方法 __init__()
# 这将初始化在父类 __init__() 方法中定义的所有属性,从而让子类包含这些属性
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
print(f"This car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class Battery:
def __init__(self, battery_size=75):
"""初始化电瓶的属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print(f"This car has a {self.battery_size}-kWh battery.")
def get_range(self):
"""打印一条消息,指出电瓶的续航里程"""
if self.battery_size == 75:
range = 260
elif self.battery_size == 100:
range = 315
print(f"This car can go about {range} miles on a full charge.")
# 电动汽车是一种特殊的汽车,因此可在前面创建的 Car 类的基础上创建新类 ElectricCar
# 定义子类时,必须在圆括号内指定父类的名称
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self, make, model, year):
"""先初始化父类的属性,再初始化电动汽车特有的属性"""
# 这行代码让 Python 调用 Car 类的方法 __init__()
# 父类也称为超类(superclass),名称 super 由此而来
super().__init__(make, model, year)
self.battery = Battery()
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print(f"This car has a {self.battery_size}-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
2019 Tesla Model S
This car has a 75-kWh battery.
This car can go about 260 miles on a full charge.
# car.py
class Car:
...
# my_car.py
from car import Car
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
...
# car.py
class Car:
...
class Battery:
...
class ElectricCar(Car):
...
# my_electric_car.py
from car import ElectricCar
my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
...
# my_cars.py
from car import Car, ElectricCar
my_beetle = Car('volkswagen', 'beetle', 2019)
print(my_beetle.get_descriptive_name())
my_tesla = ElectricCar('tesla', 'roadster', 2019)
print(my_tesla.get_descriptive_name())
# my_cars.py
import car
my_beetle = car.Car('volkswagen', 'beetle', 2019)
print(my_beetle.get_descriptive_name())
my_tesla = car.ElectricCar('tesla', 'roadster', 2019)
print(my_tesla.get_descriptive_name())
from electric_car import ElectricCar as EC
my_tesla = EC('tesla', 'roadster', 2019) # 使用别名
from random import randint
print(randint(1, 6))
1
from random import choice
players = ['charles', 'martina', 'michael', 'florence', 'eli']
first_up = choice(players)
print(first_up)
michael
# pi_digits.txt
3.1415926535
8979323846
2643383279
# 函数 open() 接受一个参数:要打开的文件的名称
# 关键字 with 在不再需要访问文件后将其关闭
with open('pi_digits.txt') as file_object:
# 使用方法 read() 读取这个文件的全部内容
contents = file_object.read()
# Python 方法 rstrip() 删除字符串末尾的空白
print(contents.rstrip())
3.1415926535
8979323846
2643383279
# 到文件夹 python_work 下的文件夹 text_files 中去查找指定的 .txt 文件
with open('text_files/filename.txt') as file_object:
# 还可以将文件在计算机中的准确位置告诉 Python
# 这样就不用关心当前运行的程序存储在什么地方了,这称为绝对文件路径
file_path = '/home/ehmatthes/other_files/text_files/_filename_.txt'
with open(file_path) as file_object:
filename = 'pi_digits.txt'
with open(filename) as file_object:
# 方法 readlines() 从文件中读取每一行,并将其存储在一个列表中
lines = file_object.readlines()
# 列表 lines 的每个元素都对应于文件中的一行
for line in lines:
print(line.rstrip())
3.1415926535
8979323846
2643383279
filename = 'chapter_10/pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
3.141592653589793238462643383279
32
filename = 'programming.txt'
# 第一个实参也是要打开的文件的名称
# 第二个实参('w')表示要以写入模式打开这个文件
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
# programming.txt
I love programming.
filename = 'programming.txt'
with open(filename, 'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
# programming.txt
I love programming.
I also love finding meaning in large datasets.
I love creating apps that can run in a browser.
print(5 / 0)
Traceback (most recent call last):
File "division_calculator.py", line 1, in <module>
print(5/0)
ZeroDivisionError: division by zero
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
You can't divide by zero!
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
Give me two numbers, and I'll divide them.
Enter 'q' to quit.
First number: 2
Second number: 6
0.3333333333333333
First number: q
Process finished with exit code 0
filename = 'alice.txt'
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
else:
# Count the approximate number of words in the file.
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
Sorry, the file alice.txt does not exist.
# The file alice.txt has about 29465 words.
title = "Alice in Wonderland"
print(title.split())
['Alice', 'in', 'Wonderland']
def count_words(filename):
"""计算一个文件大致包含多少个单词"""
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
# pass 语句还充当了占位符,提醒在程序的某个地方什么都没做,并且以后也许要在这里做什么
pass
else:
words = contents.split()
num_words = len(words)
print(f"The file {filename} has about {num_words} words.")
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
count_words(filename)
The file alice.txt has about 29465 words.
The file siddhartha.txt has about 42172 words.
The file moby_dick.txt has about 215830 words.
The file little_women.txt has about 189079 words.
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f:
# 使用函数 json.dump() 将数字列表存储到文件 numbers.json 中
json.dump(numbers, f)
# numbers.json
[2, 3, 5, 7, 11, 13]
import json
filename = 'numbers.json'
with open(filename) as f:
# 使用函数 json.load() 加载存储在 numbers.json 中的信息
numbers = json.load(f)
print(numbers)
[2, 3, 5, 7, 11, 13]
import json
def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
"""提示用户输入用户名"""
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f:
json.dump(username, f)
return username
def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print(f"Welcome back, {username}!")
else:
username = get_new_username()
print(f"We'll remember you when you come back, {username}!")
greet_user()
Welcome back, eric!