第4周作业 #高级编程技术

第七章


7-1 汽车租赁

编写一个程序,询问用户要租赁什么样的汽车,并打印一条消息,如“Let me see if I can find you a Subaru”。

car = input("What kind of car do you want to lease?")
print("Let me see if I can find you a " + car)



7-2 餐馆订位

编写一个程序,询问用户有多少人用餐。如果超过8人,就打印一条消息,指出没有空桌;否则指出有空桌。

number = input("How many people will have a meal?")
number = int(number)
if number > 8:
    print("There is no available table!")
else:
    print("There is a available table.")



7-3 10的整数倍

让用户输入一个数字,并指出这个数字是否是10的整数倍。

number = input("Please enter a number:")
number = int(number)
if number % 10 == 0:
    print("The number is an integer multiple of 10.")
else:
    print("The number is not an integer multiple of 10.")



7-4 比萨配料

编写一个循环,提示用户输入一系列的比萨配料,并在用户输入’quit’ 时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添加这种配料。

message = input("Please enter a ingredient of pizza:")
while message != "quit":
    print("We will add this ingredient to the pizza.")
    message = input("Please enter a ingredient of pizza:")



7-5 电影票

有家电影院根据观众的年龄收取不同的票价:不到3岁的观众免费;3~12岁的观众为10美元;超过12岁的观众为15美元。请编写一个循环,在其中询问用户的年龄,并指出其票价。

age = input("Please enter your age:")
while age != "quit":
    age = int(age)
    if age < 3:
        print("free")
    elif 3 <= age <=12:
        print("$10")
    else:
        print("$15")
    age = input("Please enter your age:")



7-6 三个出口

以另一种方式完成练习7-4或练习7-5,在程序中采取如下所有做法。
- 在while 循环中使用条件测试来结束循环。
- 使用变量active 来控制循环结束的时机。
- 使用break 语句在用户输入’quit’ 时退出循环。

active = True
while active:
    message = input("Please enter a ingredient of pizza:")
    if message == "quit":
        active = False
    else:
        print("We will add this ingredient to the pizza.")
while True:
    message = input("Please enter a ingredient of pizza:")
    if message == "quit":
        break;
    else:
        print("We will add this ingredient to the pizza.")



7-7 无限循环

编写一个没完没了的循环,并运行它(要结束该循环,可按Ctrl +C,也可关闭显示输出的窗口)。

count = 1
while count:
    print(count)
    count += 1



7-8 熟食店

创建一个名为sandwich_orders 的列表,在其中包含各种三明治的名字;再创建一个名为finished_sandwiches 的空列表。遍历列表sandwich_orders ,对于其中的每种三明治,都打印一条消息,如I made your tuna sandwich ,并将其移到列表finished_sandwiches 。所有三明治都制作好后,打印一条消息,将这些三明治列出来。

sandwich_orders = ['Pepperoni sandwich', 'Hawaii sandwich', 'Mexican sandwich']
finished_sandwiches = []
while sandwich_orders:
    sandwich = sandwich_orders.pop()
    print("I made your " + sandwich)
    finished_sandwiches.append(sandwich)



7-9 五香烟熏牛肉卖完了

使用为完成练习7-8而创建的列表sandwich_orders ,并确保’pastrami’ 在其中至少出现了三次。在程序开头附近添加这样的代码:打印一条消息,指出熟食店的五香烟熏牛肉卖完了;再使用一个while 循环将列表sandwich_orders中的’pastrami’ 都删除。确认最终的列 表finished_sandwiches 中不包含’pastrami’ 。

sandwich_orders = [
    'Pepperoni sandwich',
    'pastrami',
    'Hawaii sandwich',
    'Mexican sandwich',
    'pastrami',
    'pastrami',
    ]
while 'pastrami' in sandwich_orders:
    sandwich_orders.remove('pastrami')
print("Pastrami are sold out.")
finished_sandwiches = []
while sandwich_orders:
    sandwich = sandwich_orders.pop()
    print("I made your " + sandwich)
    finished_sandwiches.append(sandwich)



7-10 梦想的度假胜地

编写一个程序,调查用户梦想的度假胜地。使用类似于“If you could visit one place in the world, where would you go?”的提示,并编写一个打印调查结果的代码块。

places = {}
while True:
    name = input("What is your name?")
    place = input("If you could visit one place in the world, where would you go?")
    places[name] = place
    repeat = input("Would you like to investigate another person? (yes/ no) ")
    if repeat == 'no':
        break;
print(places)



第八章


8-1 消息

编写一个名为display_message() 的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。

def display_message():
    print("The def statement defines a function or method.")
display_message()



8-2 喜欢的图书

编写一个名为favorite_book() 的函数,其中包含一个名为title 的形参。这个函数打印一条消息,如One of my favorite books is Alice in Wonderland 。调用这个函数,并将一本图书的名称作为实参传递给它。

def favorite_book(title):
    print("One of my favorite books is " + title)
favorite_book('Alice in Wonderland')



8-3 T恤

编写一个名为make_shirt() 的函数,它接受一个尺码以及要印到T恤上的字样。这个函数应打印一个句子,概要地说明T恤的尺码和字样。使用位置实参调用这个函数来制作一件T恤;再使用关键字实参来调用这个函数。

def make_shirt(size, words):
    print("The size: " + str(size))
    print("The words: " + words)
make_shirt(14, 'Practice Makes Perfect')



8-4 大号T恤

修改函数make_shirt() ,使其在默认情况下制作一件印有字样“I love Python”的大号T恤。调用这个函数来制作如下T恤:一件印有默认字样的大号T恤、一件印有默认字样的中号T恤和一件印有其他字样的T恤(尺码无关紧要)。

def make_shirt(size = 'L', words = 'I love Python'):
    print("\nThe size: " + size)
    print("The words: " + words)

make_shirt()
make_shirt('M')
make_shirt('XL', 'HAHA')



8-5 城市

编写一个名为describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,如Reykjavik is in Iceland 。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。

def describe_city(city = 'New York', country = 'America'):
    print(city + " is in " + country + '.')

describe_city()
describe_city('Los Angeles')
describe_city('Guangzhou', 'China')



8-6 城市名

编写一个名为city_country() 的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面这样的字符串:”Santiago, Chile” 至少使用三个城市-国家对调用这个函数,并打印它返回的值。

def city_country(city = 'New York', country = 'America'):
    return city + ', ' + country

print(city_country())
print(city_country('Los Angeles'))
print(city_country('Guangzhou', 'China'))



8-7 专辑

编写一个名为make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。给函数make_album()添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。

def make_album(singer_name, album_name, album_count = ''):
    if album_count:
        tmp = {'singer_name: ': singer_name,
            'album_name: ': album_name,
            'album_count: ': album_count,}
    else:
        tmp = {'singer_name: ': singer_name,
            'album_name: ': album_name,}
    return tmp
print(make_album('Avril Lavigne', 'The Best Damn Thing'))
print(make_album('Alice', 'Loving Python', 10))



8-8 用户的专辑

在为完成练习8-7编写的程序中,编写一个while循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函数make_album() 并将创建的字典打印出来。在这个while 循环中,务必要提供退出途径。

def make_album(singer_name, album_name, album_count = ''):
    if album_count:
        tmp = {'singer_name: ': singer_name,
            'album_name: ': album_name,
            'album_count: ': album_count,}
    else:
        tmp = {'singer_name: ': singer_name,
            'album_name: ': album_name,}
    return tmp

while True:
    print("(press Q any time to quit)")
    singer_name = input("Enter a singer name: ")
    if singer_name == 'Q':
        break;
    album_name = input("Enter a album name: ")
    if album_name == 'Q':
        break;
    count = input("Do you want to enter count of songs?(yes or no)")
    if count == 'Q':
        break;
    elif count == 'yes':
        album_count = input("Enter album count: ")
        print(make_album(singer_name, album_name, album_count))
    else:
        print(make_album(singer_name, album_name))



8-9 魔术师

创建一个包含魔术师名字的列表,并将其传递给一个名为show_magicians() 的函数,这个函数打印列表中每个魔术师的名字。

def show_magicians(magicians):
    for magician in magicians:
        print(magician)

magicians = ['Alice', 'Tew', 'Mary']
show_magicians(magicians)



8-10 了不起的魔术师

在你为完成练习8-9而编写的程序中,编写一个名为make_great()的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the Great”。调用函数show_magicians() ,确认魔术师列表确实变了。

def show_magicians(magicians):
    for magician in magicians:
        print(magician)

def make_great(magicians):
    for ele in range(len(magicians)):
        magicians[ele] = 'the Great ' + magicians[ele]

magicians = ['Alice', 'Tew', 'Mary']
show_magicians(magicians)
make_great(magicians)
show_magicians(magicians)

输出:

Alice
Tew
Mary
the Great Alice
the Great Tew
the Great Mary



8-11 不变的魔术师

修改你为完成练习8-10而编写的程序,在调用函数make_great() 时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调用show_magicians() ,确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the Great”的魔术师名字。

def show_magicians(magicians):
    for magician in magicians:
        print(magician)

def make_great(magicians):
    for ele in range(len(magicians)):
        magicians[ele] = 'the Great ' + magicians[ele]
    return magicians

magicians = ['Alice', 'Tew', 'Mary']
show_magicians(magicians)
magicians_new = make_great(magicians[:])
show_magicians(magicians)
show_magicians(magicians_new)

输出:

Alice
Tew
Mary
Alice
Tew
Mary
the Great Alice
the Great Tew
the Great Mary



8-12 三明治

编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。

def make_sandwich(*toppings):
    print("\nMaking a sandwich with the following toppings:")
    for topping in toppings:
        print("- " + topping)

make_sandwich('pepperoni')
make_sandwich('pepperoni', 'red peppers')
make_sandwich('mushrooms', 'green peppers', 'extra cheese')



8-13 用户简介

复制前面的程序user_profile.py,在其中调用build_profile()来创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键-值对。

def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('Zhongheng', 'Yang',
    location='SYSU', field='CS', GPA=4.0)
print(user_profile)



8-14 汽车

编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及两个名称—值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:
car = make_car(‘subaru’, ‘outback’, color=’blue’, tow_package=True)
打印返回的字典,确认正确地处理了所有的信息。

def make_car(manufacturer, model, **car_info):
    profile = {}
    profile['manufacturer'] = manufacturer
    profile['model'] = model
    for key, value in car_info.items():
        profile[key] = value
    return profile

car_profile = make_car('subaru', 'outback',
    color='blue', tow_package=True)
print(car_profile)



猜你喜欢

转载自blog.csdn.net/yyyyzxc1234/article/details/79702685
今日推荐