从练习4-11开始。
第四章
练习4-11:
pizzas = ['黄瓜','茄子','西红柿']
friend_pizzas = pizzas[:]
pizzas.append('白菜')
friend_pizzas.append('辣椒')
print(f"My favorite pizzas are:{pizzas}")
print(f"My friend's favorite pizzas are:{friend_pizzas}")
for pizza in pizzas:
print(pizza)
print("\n")
for friend_pizza in friend_pizzas:
print(friend_pizza)
练习4-12:
略
练习4-13:
foods = ('饺子','面条','油条','包子','豆浆')
for food in foods:
print(food)
print('\n')
foods = ('牛肉','羊肉','油条','包子','豆浆')
for food in foods:
print(food)
练习4-14:略
练习4-15:略
第五章
练习5-1
car = 'subaru'
print("Is car == 'subaru'? I predict True.")
print(car == 'subaru')
print("\nIs car == 'audi'? I predict False.")
print(car == 'audi')
练习5-2 略
练习5-3
alien_color = "green"
if alien_color == "green":
print("获得5分")
if alien_color == "yellow":
print("获得10分")
练习5-4
alien_color = "green"
if alien_color == "green":
print("获得5分")
else:
print("获得10分")
练习5-5
alien_color = "green"
if alien_color == "green":
print("获得5分")
elif alien_color == "yellow":
print("获得10分")
else:
print("获得15分")
alien_color = "yellow"
if alien_color == "green":
print("获得5分")
elif alien_color == "yellow":
print("获得10分")
else:
print("获得15分")
alien_color = "red"
if alien_color == "green":
print("获得5分")
elif alien_color == "yellow":
print("获得10分")
else:
print("获得15分")
练习5-6
age = 21
if age < 2:
print("这个人是婴儿。")
elif age >=2 and age < 4:
print("这个人是幼儿。")
elif age >= 4 and age < 13:
print("这个人是儿童。")
elif age >= 13 and age < 20:
print("这个人是青少年。")
elif age >= 20 and age < 65:
print("这个人是成年人。")
else:
print("这个人是老年人。")
练习5-7
favorite_fruits = ['苹果','香蕉','梨']
if '桃' in favorite_fruits:
print(f"You really like 桃!")
if '苹果' in favorite_fruits:
print(f"You really like 苹果!")
if '草莓' in favorite_fruits:
print(f"You really like 草莓!")
if '香蕉' in favorite_fruits:
print(f"You really like 香蕉!")
if '梨' in favorite_fruits:
print(f"You really like 梨!")
练习5-8
users = ['admin','小刘','小张','小王','小李']
for user in users:
if user == 'admin':
print(f"Hello {user}, would you like to see a status report?")
else:
print(f"Hello {user}, thank you for logging in again.")
练习5-9
users = []
if users:
for user in users:
if user == 'admin':
print(f"Hello {user}, would you like to see a status report?")
else:
print(f"Hello {user}, thank you for logging in again.")
else:
print("We need to find some users!")
练习5-10
current_users = ['Liu','Yang','Wang','Zhang','Ma']
new_users = ['Liu','Yang','Li','Gong','Zhao']
b_current_users =[]
for current_user in current_users:
b_current_users.append(current_user.lower())
for new_user in new_users:
if new_user.lower() in b_current_users:
print("已被使用。")
else:
print("未被使用。")
练习5-11
digits = list(range(1,10))
for digit in digits:
if digit == 1:
print(f"{digit}st")
elif digit == 2:
print(f"{digit}nd")
elif digit == 3:
print(f"{digit}rd")
else:
print(f"{digit}th")
练习5-12 略
练习5-13 略
第六章
练习6-1
information = {
'first_name':'Qiang',
'last_name':'Wang',
'city':'Bei jing',
'age':21
}
print(information)
练习6-2
informations = {
'王伟':3,
'刘强':5,
'张帅':1, #想用循环写,不知道可不可以,至少目前还不会。
'李军':8,
'赵坤':11
}
print(f"王伟喜欢的数字是{informations['王伟']}")
print(f"刘强喜欢的数字是{informations['刘强']}")
print(f"张帅喜欢的数字是{informations['张帅']}")
print(f"李军喜欢的数字是{informations['李军']}")
print(f"赵坤喜欢的数字是{informations['赵坤']}")
练习6-3 略
练习6-4 我这里优化练习6-2。
informations = {
'王伟':3,
'刘强':5,
'张帅':1,
'李军':8,
'赵坤':11
}
for name,digits in informations.items():
print(f"{name}最喜欢的数字是{digits}")
练习6-5
rivers = {'Yellow River':' China','Nile':'Egypt','Ganges':'India'}
for river,country in rivers.items():
print(f"{river} runs through {country}.")
for river in rivers.keys():
print(f"{river}")
for country in rivers.values():
print(f"{country}")
练习6-6
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
check_order = ['jen','sarah','long','mei','phil']
for name in check_order:
if name in favorite_languages.keys():
print(f"{name.title()},thank you.")
else:
print(f"{name.title()},wish you come here.")
才发现我用的Sublime Text按Tab等于6个空格,应该能改吧。以后再鼓捣。
练习6-7
people = {
'adbd':{
'first_name':'Qiang',
'last_name':'Wang',
'city':'Bei jing',
'age':21,
},
'asjod':{
'first_name':'dong',
'last_name':'Liu',
'city':'Shang hai',
'age':20,
},
'sdad':{
'first_name':'yun',
'last_name':'Ma',
'city':'Zhe jiang',
'age':18,
}
}
for username, user_info in people.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['last_name']} {user_info['first_name']}"
location = user_info['city']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")
练习6-8
pets = {
'花花':{
'类型':'猫',
'主人名字':'小刘'
},
'旺财':{
'类型':'狗',
'主人名字':'小张'
}
}
for pet,information in pets.items():
print(f"宠物名字:{pet}")
species = information['类型']
owner = information['主人名字']
print(f"类型是:{species}\n主人名字是:{owner}\n")
以后要多学点英语了。
练习6-9
favorite_places = {
'Zhang':['Bei jing','Su zhou'],
'Liu':['Shang hai'],
'Ma':['Hang zhou','Ji nan','Qing dao']
}
for name,places in favorite_places.items():
print(f"{name}'s favorite places as follow:")
for place in places:
print(f"\t{place}")
练习6-10
informations = {
'王伟':[3,4,7],
'刘强':[5,8,11,23],
'张帅':[1,5,32],
'李军':[28,34],
'赵坤':[11,33]
}
for name,digits in informations.items():
print(f"{name}最喜欢的数字是:")
for digit in digits:
print(f"{digit}")
练习6-11
cities = {'Bei jing':{
'country':'China',
'population':'21 million',
'fact':'Tsing University',
},
'New york':{
'country':'America',
'population':'8 million',
'fact':'The biggst city in America',
},
'Shang hai':{
'country':'China',
'population':'25 million',
'fact':'Fudan University',
}
}
for city,informations in cities.items():
print(f"\n{city}")
for keys,values in informations.items():
print(f"{keys}:{values}")
第七章
练习7-1
car = input("What car do you want? ")
print(f"Let me see if I can find you a {car.title()}.")
练习7-2
number = input("How many people are eating? ")
number = int(number)
if number >= 8:
print("There adre no extra tables here.")
else:
print("There are extra tables.")
练习7-3
number = input("Enter a number: ")
number = int(number)
if number % 10 == 0:
print("It is an integer multiple of 10.")
else:
print("It is not an integer multiple of 10.")
练习7-4
prompt = "Enter the ingredients: "
ingredient = ""
while ingredient != 'quit':
ingredient = input(prompt)
if ingredient != 'quit':
print(f"We will add {ingredient}.")
prompt = "Enter the ingredients: "
ingredient = ""
while True:
ingredient = input(prompt)
if ingredient == 'quit':
break
else:
print(f"We will add {ingredient}.")
练习7-5
while True:
age = input("What is your age? ")
age = int(age)
if age < 3:
print("Your price is free.")
elif age >= 3 and age <=12:
print("Your price is 10 dollor.")
else:
print("Your price is 15 dollor.")
练习7-6 修改7-5
active = True
while active:
age = input("What is your age? ")
if age == 'quit':
active = False
else:
age = int(age)
if age < 3:
print("Your price is free.")
elif age >= 3 and age <=12:
print("Your price is 10 dollor.")
else:
print("Your price is 15 dollor.")
练习7-7 练习7-5就是一个没完没了的循环。
练习7-8
sandwich_order = ['Onion sandwich','Cucumber sandwich','Cream sandwich']
finished_sandwich = []
while sandwich_order:
order = sandwich_order.pop()
print(f"I made your {order}.")
finished_sandwich.append(order)
for sandwich in finished_sandwich:
print(sandwich)
练习7-9
print("Pastrami sold out.")
sandwich_order = ['Pastrami','Onion sandwich','Pastrami','Pastrami','Cucumber sandwich','Cream sandwich']
while 'pastrami'.title() in sandwich_order:
sandwich_order.remove('Pastrami')
finished_sandwich = []
while sandwich_order:
order = sandwich_order.pop()
print(f"I made your {order}.")
finished_sandwich.append(order)
for sandwich in finished_sandwich:
print(sandwich)
练习7-10
responses = {}
while True:
name = input("\nWhat is your name? ")
response = input("If you could visit one place in the world, where would you go? ")
responses[name] = response
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
break
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to visit {response}.")
第八章
练习8-1
def display_message():
print("定义函数,形参与实参。")
display_message()
练习8-2
def favorite_book(title):
print(f"One of my favorite books is {title.title()}.")
favorite_book('Alice in Wonderland')
练习8-3
def make_shirt(size,words):
print(f"The shirt's size is {size},here are words on it:{words}.")
make_shirt('xxxl','hello world')
def make_shirt(size,words):
print(f"The shirt's size is {size},here are words on it:{words}.")
make_shirt(size = 'xxxl',words = 'hello world')
练习8-4
def make_shirt(size = '大号',words = 'I love Python'):
print(f"The shirt's size is {size},here are words on it:{words}.")
make_shirt()
make_shirt('中号')
make_shirt('小号','I love C')
练习8-5
def describe_city(name,country = 'China'):
print(f"{name.title()} in {country.title()}.")
describe_city('bei jing')
describe_city('shang hai')
describe_city('new york','america')
练习8-6
def city_country(city,country):
print(f"{city.title()},{country.title()}")
city_country('bei jing','China')
city_country('Santiago', 'Chile')
city_country('san francisco','america')
练习8-7
def make_album(singer,album_name,number = None):
"""描述音乐专辑"""
albums = {'singer':singer,'album_name':album_name}
if number:
albums['number'] = number
return albums
album = make_album('毛不易','幼鸟指南',11)
print(album)
album = make_album('伍佰','泪桥')
print(album)
album = make_album('孙燕姿','风筝')
print(album)
练习8-8
def make_album(singer,album_name,number = None):
"""描述音乐专辑"""
albums = {'singer':singer,'album_name':album_name}
if number:
albums['number'] = number
return albums
while True:
singer = input("输入歌手名字: ")
album_name = input("输入专辑名: ")
number = input("输入专辑中歌曲数量(选填): ")
album = make_album(singer,album_name,number)
print(album)
repeat = input("是否要继续?(yes or no)")
if repeat == 'no':
break
练习8-9
def show_messages(messages):
for message in messages:
print(message.title())
messages = ['phone number','tsinghua university','peking university']
show_messages(messages)
练习8-10
def show_messages(unsend_messages):
while unsend_messages:
message = unsend_messages.pop()
print(message.title())
send_messages.append(message)
send_messages = []
messages = ['phone number','tsinghua university','peking university']
show_messages(messages)
print(messages)
print(send_messages)
练习8-11
def show_messages(unsend_messages):
while unsend_messages:
message = unsend_messages.pop()
print(message.title())
send_messages.append(message)
send_messages = []
unsend_messages = ['phone number','tsinghua university','peking university']
show_messages(unsend_messages[:])
print(unsend_messages)
print(send_messages)
练习8-12
def order(*un_add):
print("These will be add: ")
for meterial in un_add:
print(f"-{meterial}")
order('cucumber')
order('onion','beef')
order('tomato','eggplant','cabbage')
练习8-13
def build_profile(first, last, **user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切。"""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('xian', 'yang',
location='qingdao',
school='tsinghua university')
print(user_profile)
练习8-14
def build_profile(manufacturer,model,**kwargs):
"""描述车辆信息"""
kwargs['manufacturer'] = manufacturer
kwargs['model'] = model
return kwargs
car_info = build_profile('subaru', 'outback', color='blue', tow_package=True)
print(car_info)
练习8-15
from printing_models import build_profile
build_profile('subaru', 'outback', color='blue', tow_package=True)
练习8-16
import printing_models
printing_models.build_profile('subaru', 'outback', color='blue', tow_package=True)
from printing_models import build_profile
build_profile('subaru', 'outback', color='blue', tow_package=True)
from printing_models import build_profile as bp
bp('subaru', 'outback', color='blue', tow_package=True)
import printing_models as pm
pm.build_profile('subaru', 'outback', color='blue', tow_package=True)
from printing_models import *
build_profile('subaru', 'outback', color='blue', tow_package=True)
第九章
练习9-1
class Restaurant:
"""描述餐馆信息"""
def __init__(self,restaurant_name,cuisine_type):
"""初始化属性餐馆名和菜式"""
self.name = restaurant_name
self.type = cuisine_type
def describe_restaurant(self):
"""描述餐馆"""
print(f"The restaurant's name is {self.name}.")
print(f"The restaurant's cuisine type is {self.type}.")
def open_restaurant(self):
"""描述餐馆正在营业"""
print("The restaurant is opening.")
restaurant = Restaurant('新月饭店','老北京菜')
restaurant.describe_restaurant()
restaurant.open_restaurant()
练习9-2