《Python程式設計》第八章部分課後練習題

Zetrue_Li發表於2018-03-29

#8-4 大號T恤:

程式碼:

#8-4 大號T恤

def  make_shirt(size='L', style='I love Python'):
	"""pass two argurments to make the specific T-shirt"""
	message = "This T-shirt's size is " + size + '\n'
	message += "This T-shirt's style is " + style + '\n'
	print(message)
	
make_shirt()
make_shirt('M')
make_shirt(style='I hate Python')

輸出:

This T-shirt's size is L
This T-shirt's style is I love Python

This T-shirt's size is M
This T-shirt's style is I love Python

This T-shirt's size is L
This T-shirt's style is I hate Python


#8-5 城市:

程式碼:

#8-5 城市

def describe_city(city, country='Iceland'):
	"""print the city belongs to which counrty"""
	message = city + ' is in ' + country + '.'
	print(message)
	
describe_city('Reykjavík')
describe_city('Kópavogur')
describe_city('New york')	

輸出:

Reykjavík is in Iceland.
Kópavogur is in Iceland.
New york is in Iceland.                             


#8-6 城市名:

程式碼:

#8-6 城市名

def city_country(*item):
	"""pass (city, country), then print the message of city_country"""
	for pair in item:
		message = pair[0] + ', ' + pair[-1]
		print(message)

city_country(('Ottawa', 'Canada'), ('Beijing', 'China'), ('Cairo', 'Egypt'), ('Moscow', 'Russia'))

輸出:

Ottawa, Canada
Beijing, China
Cairo, Egypt
Moscow, Russia                                                 


#8-7 專輯:

程式碼:

#8-7 專輯

def make_album(singer_name, album_name, songs_num=''):
	"""receive singer's name and album's name of a album, then return the dictionary"""
	album = {'singer_name': singer_name, 'album_name': album_name}
	if songs_num:
		album['songs_num'] = songs_num
	return album

print(make_album('Eason', 'A life'))
print(make_album('Jay', 'fantacy', 10))

輸出:

{'singer_name': 'Eason', 'album_name': 'A life'}
{'singer_name': 'Jay', 'album_name': 'fantacy', 'songs_num': 10}


#8-14 汽車:

程式碼:

#8-14 汽車

def make_car(manufacturer, model_type, **others):
	"""return all information of a Car"""
	car = {'manufacturer': manufacturer, 'model_type': model_type}
	for key, value in others.items():
		car[key] = value
	return car
	
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)

car = make_car('Toyta', 'AE86', color='red')
print(car)

輸出:

{'manufacturer': 'subaru', 'model_type': 'outback', 'color': 'blue', 'tow_package': True}
{'manufacturer': 'Toyta', 'model_type': 'AE86', 'color': 'red'}                                                            


相關文章