以下内容为Python Crash Course: A Hands-On, Project-Based Introduction to Programming一书的摘录。
此书不需要编程基础,极易上手(对有编程基础的朋友可能过于简单,但代码中仍有许多值得借鉴的地方),代码示例绝大多数为现实生活中鲜活的例子,读来兴味盎然。
① 首字母大写,其他位置小写:title()
函数
message = "i lOVE you"
print(message.title())
运行结果:
I Love You
② 全部大写/小写:upper()和lower()
message = "i lOVE you"
print(message.upper())
print(message.lower())
运行结果:
I LOVE YOU
i love you
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(full_name)
print(f"Hello, {full_name.title()}!") #python 3.6
运行结果:
ada lovelace
Hello, Ada Lovelace!
full_name = "{} {}".format(first_name, last_name)
① 除去字符串一侧/两边的whitespace(无法打印的字符:空格,tab,结束符等)
s = ' p '
print(len(s.rstrip()))
print(len(s.lstrip()))
print(len(s.strip()))
运行结果:2, 2, 1
print(2 ** 3)
运行结果:8
print(4 / 2)
运行结果:2.0
universe_age = 14_000_000_000
print(universe_age)
运行结果:14000000000
x, y, z = 0, 0, 0
MAX_CONNECTIONS = 5000
If you don’t have anything specific to write because your programs are too simple at this point, just add your name and the current date at the top of each program file. Then write one sentence describing what the program does.
养成写注释的好习惯,即使程序很简单,也尽量写上自己的名字、日期以及程序的作用。
① 取最后一个元素:index = -1
(可扩展至index = -2…)
bicycles = ['trek', 'cannnondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[-1]) #取最后一个元素
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
运行结果:
['trek', 'cannnondale', 'redline', 'specialized']
trek
specialized
My first bicycle was a Trek.
① 在list末尾添加元素:append(value)
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')
print(motorcycles)
运行结果:
['honda', 'yamaha', 'suzuki', 'ducati']
向空的list添加元素:
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)
运行结果:
['honda', 'yamaha', 'suzuki']
② 向list指定位置插入元素:insert(index, value)
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
运行结果:
['ducati', 'honda', 'yamaha', 'suzuki']
① 删除指定位置元素,且不再使用:del
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles)
运行结果:
['yamaha', 'suzuki']
② 取出最后一个元素的值并删除:pop()
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
运行结果:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
③ 删除指定位置元素,且需要使用:pop(index)
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first bicycle I owned was a {first_owned.title()}.")
运行结果:
The first bicycle I owned was a Honda.
④ 按值删除元素(不知道下标):remove(value)
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
运行结果:
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']
注意:remove仅仅移除第一个出现的值元素,如果要确保全部删除,应使用loop。
以下两种方法均区分大小写。
① permanent sort:sort()
(改变原序列)
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
cars.sort(reverse=True) #设置reverse=True逆序排列
print(cars)
运行结果:
['audi', 'bmw', 'subaru', 'toyota']
['toyota', 'subaru', 'bmw', 'audi']
② temporal sort:sorted(list)
(不改变原序列)
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(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']
reverse()
方法。
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
运行结果:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
len()
方法。
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))
运行结果:
4
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!") #intended
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!
① 连续数字:range(start, end)
for value in range(1, 5):
print(value)
运行结果:
1
2
3
4
range(index)
:单参数从0开始
for value in range(5):
print(value)
运行结果:
0
1
2
3
4
range(start, end, step)
:3参数加入步长
for value in range(1, 5, 2):
print(value)
运行结果:
1
3
② range转list
numbers = list(range(1, 6))
print(numbers)
运行结果:
[1, 2, 3, 4, 5]
③ range的应用:打印平方数
#打印平方数
squares = []
for value in range(1, 11):
squares.append(value ** 2)
print(squares)
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#min, max, sum
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits), max(digits), sum(digits))
运行结果:
0 9 45
squares = [value**2 for value in range(1, 11)]
print(squares)
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) #取出前3项
print(players[:3]) #与上述代码结果相同
print(players[2:]) #省略第二个下标号,默认一直到最后一项
print(players[-3:]) #取出列表的最后3项
print(players[0:3:2]) #第3个参数,表明步长
#对列表一部分循环操作
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
运行结果:
['charles', 'martina', 'michael']
['charles', 'martina', 'michael']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
['charles', 'michael']
Here are the first three players on my team:
Charles
Martina
Michael
要注意使用[:]
slice操作,否则直接赋值将起不到复制出一个新的list的效果。
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:] #复制整个list
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']
错误示例:
my_foods = ['pizza', 'falafel', 'carrot cake']
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', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
tuples指值不可更改的list(immutable list)。
dimensions = (200, 50) #tuple使用括号
print(dimensions[0]) #下标访问
print(dimensions[1])
for dimension in dimensions: #tuple的循环值访问
print(dimension)
注意:定义只含一个元素的tuple时要加逗号,如my_t = (200,)
tuple的更改只能通过tuple整体赋值得到。
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
部分语法:
① 且:age_0 >= 21 and age_1 >= 21
② 检查元素是否在list中,使用关键词in/not in
:
if element in list:
if element not in list:
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.")
运行结果:
Your admission cost is $25.
一个更好的版本:
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
else:
price = 40
#在此情况下,若需改变输出的text,只需要改动一次
print(f"Your admission cost is ${price}.")
万全之策:不在最后使用else
在有明确的匹配范围时,全程使用elif有以下好处:
1.可读性强;
2.明确的elif可以防止接收恶意值(e.g.在此例子中,age=1_000可以被else接收)
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age >= 18:
price = 40
#在此情况下,若需改变输出的text,只需要改动一次
print(f"Your admission cost is ${price}.")
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!
① 检查list是否非空
requested_toppings = []
if requested_toppings: #检查list是否非空
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?")
② 多List操作
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}
print(alien_0['color'])
print(alien_0['points'])
运行结果:
green
5
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}
向空字典添加元素。
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow' #改变value
print(f"The alien is now {alien_0['color']}.")
运行结果:
The alien is green.
The alien is now yellow.
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")
# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# This must be a fast alien.
x_increment = 3
# The new position is the old position plus the increment.
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")
运行结果:
Original position: 0
New position: 2
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
#删除points
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.
避免使用[key]
方法访问不存在的键值对,导致KeyError。
alien_0 = {'color': 'green', 'speed': 'slow'}
#第2个参数(optional)可以用来存放参数不存在的返回信息,不填写则返回None
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',
}
for k, v in user_0.items(): #用.items()取键值对
print(f"Key: {k}")
print(f"Value: {v}\n")
运行结果:
Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items(): #用.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 Ruby.
Phil's favorite language is Python.
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys(): #用.keys()取键,也可以省略.keys()
print(name.title())
运行结果:
Jen
Sarah
Edward
Phil
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values(): #遍历value
print(language.title())
运行结果:
The following languages have been mentioned:
Python
C
Ruby
Python
使用set()
可避免重复。
for language in set(favorite_languages.values()): #遍历value,不重复
print(language.title())
运行结果:
The following languages have been mentioned:
Python
Ruby
C
set()
的定义。
languages = {'python', 'ruby', 'python', 'c'}
print(languages)
运行结果:
{'c', 'ruby', 'python'}
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.
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)
运行结果:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
# Make an empty list to store aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# Show the first 5 aliens.
for alien in aliens[:5]:
print(alien)
print("...")
# Show how many aliens have been created.
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
# Store information about a pizza being ordered.
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# Summarize the order.
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
#人名缩写+具体信息
#嵌套字典尽量设置结构一致
users = {
'aeinstein':{
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie':{
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print(f"Username: {username}")
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()}\n")
运行结果:
Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris
name = input("Please enter your name: ")
print(f"\nHello, {name}!")
运行结果:
Please enter your name: Charlene
Hello, Charlene!
# 提示多于一行
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"Hello, {name}!")
运行结果:
If you tell mus who you are, we can personalize the messages you see.
What is your first name? Charlene
Hello, Charlene!
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? 15
You'll be able to ride when you're a little older.
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
# Letting the user choose when to quit
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)
# using a flag
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)
# using 'break' to exit a loop
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()}!")
# using 'continue' in a loop
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
使用for循环时修改list可能会导致顺序追踪list中元素时(items方法)产生异常。因此,尽量使用while循环。
# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
# Display all confirmed users.
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 = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response.
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# Store the response in the dictionary.
responses[name] = response
# Find out if anyone else is going to take the poll.
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False
# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")
运行结果:
What is your name? Charlene`在这里插入代码片`
Which mountain would you like to climb someday? yellow mountain
Would you like to let another person respond? (yes/ no) yes
What is your name? Bob
Which mountain would you like to climb someday? Fuji mountain
Would you like to let another person respond? (yes/ no) no
--- Poll Results ---
Charlene would like to climb yellow mountain.
Bob would like to climb Fuji mountain.
使用docstring简述函数功能。
def greet_user():
"""Display a simple greeting"""
print("Hello!")
greet_user()
带参数的函数。
def greet_user(username):
"""Display a simple greeting"""
print(f"Hello, {username.title()}!")
greet_user('jesse')
def describe_pet(animal_type, pet_name):
"""Display information about a pet"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster', 'harry') # The order matters.
运行结果:
I have a hamster.
My hamster's name is Harry.
def describe_pet(animal_type, pet_name):
"""Display information about a pet"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster', pet_name='harry') # The order does not matter.
describe_pet(pet_name='harry', animal_type='hamster') # Equivalent
# Default values must be placed backwords,
# so that Python can interpret positional arguments correctly.
def describe_pet(pet_name, animal_type='dog'):
"""Display information about a pet"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')
def get_formatted_name(first_name, last_name):
"""Return a fill name, neatly formatted"""
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
运行结果:Jimi Hendrix
def get_formatted_name(first_name, last_name, middle_name=''): # Making an Argument Optional
"""Return a fill name, neatly formatted"""
if middle_name:
full_name = f"{first_name} {last_name} {middle_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 Hooker Lee
def build_person(first_name, last_name, age=None): # placeholder
"""Return a dictionary of information about a person."""
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 greet_users(names):
"""Print a simple greeting to each user in the list"""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
运行结果:
Hello, Hannah!
Hello, Ty!
Hello, Margot!
List内容被永久改变:
print_models(unprinted_designs, completed_models)
List内容不变:
print_models(unprinted_designs[:], completed_models)
# In function print_models, completed_models(List) changes permanently.
def print_models(unprinted_designs, completed_models):
"""
Simulate printing each design, until none are left.
Move each design to completed_models after printing.
"""
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):
"""Show all the models that were printed."""
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 = []
"""
By using
print_models(unprinted_designs[:], completed_models),
the original list remains intact.
But it is not recommended to avoid excessive time and memory.
"""
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
*toppings
tells python to make an empty tuple called toppings and pack whatever values it receives into this tuple.
def make_pizza(*toppings):
"""Print the list of toppings that have been requested."""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
运行结果:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(*toppings):
"""Summarize the pizza we are about to make"""
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
函数定义时,Arbitrary Arguments要放在最后。
在匹配参数时,Python总是先匹配 Positional & Keyword Arguments,然后再到Arbitrary Arguments。
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make"""
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
You’ll often see the generic parameter name *args, which collects arbitrary positional arguments like this.
**user_info
tells python to create an empty dictionary called user_info and pack whatever name-value pairs it receives into this dictionary.
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
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'}
You’ll often see the parameter name **kwargs used to collect non-specific keyword arguments.
Module是一个独立的.py文件。
将函数存储在另一个文件中,需要时import到主函数即可。
import整个模块:import module_name
调用模块中的函数:module_name.function_name()
# pizza.py
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make"""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
# main.py
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')
import模块中的某个函数:from module_name import function_name
import模块中的多个函数:from module_name import function0, function1, function2
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')
from module_name import function_name as fn
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(21, 'mushrooms', 'green peppers', 'extra cheese')
import module_name as mn
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')
from module_name import *
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')
尽量不要使用此方法,因为可能造成module中的函数与主函数重名导致的错误。最好的方法是import你所需的函数。
__init__()
方法在创建实例时自动被调用。self
,这是对实例本身的引用。 它使单个实例可以访问类中的属性和方法。self.
为前缀的变量在所有类方法中均可用,也可被所有类实例调用。class Dog:
"""A simple attempt to model a dog"""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(f"{self.name} rolled over!")
my_dog = Dog('Willie', 6)
# Accessing attributes
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
# Calling methods
my_dog.sit()
my_dog.roll_over()
# Creating mutiple instances
your_dog = Dog('Lucy', 3)
print(f"\nYour dog's name is {your_dog.name}.")
print(f"Your dog is {your_dog.age} years old.")
your_dog.sit()
your_dog.roll_over()
运行结果:
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie rolled over!
Your dog's name is Lucy.
Your dog is 3 years old.
Lucy is now sitting.
Lucy rolled over!
class Car:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # Set a default value for an attribute
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
# Modifying an attribute's value
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# Modifying an attribute's value through a method
my_new_car.update_odometer(20)
my_new_car.read_odometer()
# Incrementing an attribute's value through a method
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()
运行结果:
2019 Audi A4
This car has 23 miles on it.
You can't roll back an odometer!
This car has 23 miles on it.
2015 Subaru Outback
This car has 23500 miles on it.
This car has 23600 miles on it.
class Car:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # Set a default value for an attribute
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
class Battery:
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=75):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print(f"This car has a {self.battery_size}-kWh battery.")
def get_range(self):
"""Print a statement about the range this battery provides."""
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.")
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize atrributes specific to an alectric car.
"""
super().__init__(make, model, year)
self.battery = Battery() # Instances as attributes
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:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0 # Set a default value for an attribute
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_car.py
from car import Car
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
运行结果:
2019 Audi A4
This car has 23 miles on it.
car.py
class Car:
--snip--
class Battery:
--snip--
class ElectricCar(Car):
--snip--
my_electric_car.py
from car import ElectricCar
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.
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())
运行结果:
2019 Volkswagen Beetle
2019 Tesla Roadster
my_cars.py
from car
my_beetle = Car('volkswagen', 'beetle', 2019)
print(my_beetle.get_descriptive_name())
my_tesla = ElectricCar('tesla', 'roadster', 2019)
print(my_tesla.get_descriptive_name())
from module_name import *
不推荐使用这种import方法。
如果需要从一个模块中导入许多类,则最好导入整个模块并使用module_name.ClassName
语法。
electric_car.py
"""A set of classes that can be used to represent electric cars."""
from car import Car
class Battery:
---snip---
class ElectricCar:
---snip---
car.py
"""A class that can be used to represent a car."""
class Car:
---snip---
my_car.py
from car import Car
from electric_car import 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())
运行结果:
2019 Volkswagen Beetle
2019 Tesla Roadster
from electric_car import ElectricCar as EC
my_tesla = EC('tesla', 'roadster', 2019)