当前位置:   article > 正文

《Python编程:从入门到实践》第八章练习题_python8-16习题

python8-16习题

《Python编程:从入门到实践》第八章练习题

8-1 消息

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

代码:

def display_message():
    print("In this chapter, I study functions.")


display_message()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

8-3 T恤

编写一个名为 make_shirt() 的函数,它接受一个尺码及要印到T恤上的字样。这个函数应打印一个句子,概要地说明T恤的尺码和字样。

使用位置实参调用该函数来制作一件T恤,再使用关键字实参来调用这个函数。

代码:

def make_shirt(size, word):
    print("Brief information of this shirt:")
    print("\tSize: " + size)
    print("\tWord: " + word)


make_shirt('large', "MAGA")

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

8-4 大号T恤

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

代码:

def make_shirt(size, word='I love Python'):
    print("\nBrief information of this shirt:")
    print("\tSize: " + size)
    print("\tWord: " + word)


make_shirt('large')
make_shirt('middle')
make_shirt('small', 'MAGA')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

8-5 城市

编写一个名为 describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。

这个函数应打印一个简单的句子,如Reykjavik is in Iceland 。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。

代码:

def describe_city(city_name, country='china'):
    print(city_name.title() + " is in " + country.title())


describe_city('shanghai', 'china')
describe_city('new york', 'america')
describe_city('tokyo', 'japan')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

8-6 城市名

编写一个名为city_country() 的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面这样的字符串:

“Santiago, Chile”

至少使用三个城市-国家对调用这个函数,并打印它返回的值。

代码:

def city_country(city_name, country):
    return '"' + city_name.title() + ', ' + country.title() + '"'


print(city_country('shanghai', 'china'))
print(city_country('new york', 'america'))
print(city_country('tokyo', 'japan'))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

8-7 专辑

编写一个名为 make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。

给函数 make_album() 添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。

代码:

def make_album(singer_name, album_name, number=''):
    album = {'singer_name': singer_name, 'album_name': album_name}
    if number:
        album['number'] = number
    return album


albums = []
albums.append(make_album('周杰伦', '八度空间', number=10))
albums.append(make_album('陈奕迅', 'Rice & Shine'))
# print(albums)
for album in albums:
    print(album)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

8-8 用户的专辑

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

代码:

def make_album(s_name, a_name, n=0):
    a = {'singer_name': s_name, 'album_name': a_name}
    if n:
        a['number'] = n
    return a


albums = []
prompt = "\nPlease tell me your favorite albums:"
prompt += "\n(Enter 'quit' to end the program)"

while True:
    print(prompt)

    singer_name = input("Singer name: ")
    if singer_name == 'quit':
        break

    album_name = input("Album name: ")
    if album_name == 'quit':
        break

    sign = input("\nDo you know how many songs in this album (yes/no): ")
    if sign == 'yes':
        number = input("Number of songs: ")
        number = int(number)
        album = make_album(singer_name, album_name, number)
        albums.append(album)
    else:
        print("Do not worry! It does not matter")
        album = make_album(singer_name, album_name)
        albums.append(album)

    print("\nLet's check the album:")
    print(album)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

8-9 魔术师

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

代码:

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


magicians = ['simon', 'jesse', 'lucy']
show_magicians(magicians)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

8-10 了不起的魔术师

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

代码:

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


def make_great(magicians, great_magicians):
    while magicians:
        current_magician = magicians.pop()
        great_magicians.append('the Great ' + current_magician.title())


magicians = ['simon', 'jesse', 'lucy']
great_magicians = []

make_great(magicians, great_magicians)
# print(magicians)
# print(great_magicians)
show_magicians(magicians)
show_magicians(great_magicians)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

8-11 不变的魔术师

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

代码:

def show_magicians(magicians):
    for magician in magicians:
        print("\t" + magician)


def make_great(magicians, great_magicians):
    while magicians:
        current_magician = magicians.pop()
        great_magicians.append('the Great ' + current_magician.title())


magicians = ['simon', 'jesse', 'lucy']
great_magicians = []

make_great(magicians[:], great_magicians)
# print(magicians)
# print(great_magicians)
print("Original magicians:")
show_magicians(magicians)
print("\nGreat magicians:")
show_magicians(great_magicians)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

8-12 三明治

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

代码:

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


make_sandwich('mushrooms', 'green peppers', 'cheese')
make_sandwich('eggs')
make_sandwich('bacon', 'apples')

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

8-13 用户简介

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

代码:

def build_profile(first, last, **user_info):
    profile = {'first_name': first, 'last_name': last}

    for key, value in user_info.items():
        profile[key] = value

    return profile


my_profile = build_profile('San', 'Zhang', height='170cm', weight='64kg', locaton='Chengdu')
print(my_profile)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

8-14 汽车

编写一个函数,将一辆汽车的信息存储在字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用该函数:提供必不可少的信息,以及两个名称值对,如颜色和选装配件。这个函数必须能够像下面这样进行调用:

car = make_car('subaru', 'outback', color='blue', 'tow_package=True')
  • 1

打印返回的字典,确认正确地处理了所有的信息。

代码:

def make_car(manufacturer, model, **car_info):
    car_profile = {'manufacturer': manufacturer, 'model': model}

    for key, value in car_info.items():
        car_profile[key] = value

    return car_profile


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

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

8-15 打印模型

将示例print_models.py中的函数放在另一个名为printing_functions.py的文件中;在print_models.py的开头编写一条import 语句, 并修改这个文件以使用导入的函数。

代码:

import printing_funcitons

magicians = ['simon', 'jesse', 'lucy']
great_magicians = []

printing_funcitons.make_great(magicians, great_magicians)
printing_funcitons.show_magicians(magicians)
printing_funcitons.show_magicians(great_magicians)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

8-16 导入

选择一个你编写的且只包含一个函数的程序, 并将这个函数放在另一个文件中。
在主程序文件中, 使用下述各种方法导入这个函数, 再调用它:

import module_name
from module_name import function_name
from module_name import function_name as fn
import module_name as mn
from module_name import *
  • 1
  • 2
  • 3
  • 4
  • 5

代码:

# 1
import make_car
car = make_car.make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)

# 2
'''
from make_car import make_car
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
'''

# 3
'''
from make_car import make_car as mc
car = mc('subaru', 'outback', color='blue', tow_package=True)
print(car)
'''

# 4
'''
import make_car as mc
car = mc.make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
'''

# 5
'''
from make_car import *
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
'''
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

8-17 函数编写指南

选择你在本章中编写的三个程序,确保它们遵循了本节介绍的函数编写指南。

略。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/992887
推荐阅读
相关标签
  

闽ICP备14008679号