8-2
def favorite_book(title):
print("One of my favorite books is " + title + ".")
book = input()
favorite_book(book)
输出结果:
Python Crash Course
One of my favorite books is Python Crash Course.
8-5
def describe_city(city,country = "China"):
print(city + " is in " + country + ".")
describe_city("Beijing")
describe_city("Guangzhou")
describe_city("London","England")
输出结果:
Beijing is in China.
Guangzhou is in China.
London is in England.
8-6
def city_country(city,country):
return city + ", " + country
print(city_country("Beijing","China"))
print(city_country("New York","US"))
print(city_country("London","England"))
输出结果:
Beijing, China
New York, US
London, England
8-8
def make_album(singer,name,number = 0):
album = {}
album[singer] = singer
album[name] = name
if number != 0:
album[number] = number
return album
while True:
singer = input("Singer: ")
name = input("Name: ")
number = input("How many songs in this album: ")
album = make_album(singer,name,int(number))
print(album)
flag = input("continue?(yes/no)")
if flag == "no":
break
输出结果:
Singer: Zhou jielun
Name: wohenmang
How many songs in this album: 10
{'Zhou jielun': 'Zhou jielun', 'wohenmang': 'wohenmang', 10: 10}
continue?(yes/no)yes
Singer: Jason
Name: The Best Moment
How many songs in this album: 15
{'Jason': 'Jason', 'The Best Moment': 'The Best Moment', 15: 15}
continue?(yes/no)no
8-11
def show_magicians(magicians):
for magician in magicians:
print(magician)
def make_great(magicians):
length = len(magicians)
i = 0
while(i < length):
magicians[i] = "the Great " + magicians[i]
i += 1
return magicians
magicians = ["Liu Qian","Deng Nanzi","Di Renjie"]
Great_magicians = make_great(magicians[:])
show_magicians(magicians)
show_magicians(Great_magicians)
输出结果:
Liu Qian
Deng Nanzi
Di Renjie
the Great Liu Qian
the Great Deng Nanzi
the Great Di Renjie
8-14
def make_car(make,size,**user_info):
car = {}
car[make] = make
car[size] = size
for key,value in user_info.items():
car[key] = value
return car
car = make_car('subaru','outback')
print(car)
car = make_car('subaru','outback',color = 'blue')
print(car)
car = make_car('subaru','outback',color = 'blue',tow_package = True)
print(car)
输出结果:
{'subaru': 'subaru', 'outback': 'outback'}
{'subaru': 'subaru', 'outback': 'outback', 'color': 'blue'}
{'subaru': 'subaru', 'outback': 'outback', 'color': 'blue', 'tow_package': True}