章节回顾:
  1. 如何编写函数,以及如何传递实参,让函数能够访问完成其工作所需的信息;
  2. 如何使用位置实参和关键字实参,以及如何接受任意数量的实参;
  3. 显示输出的函数和返回值的函数;
  4. 如何将函数同列表、字典、if 语句和while 循环结合起来使用。
  5. 如何将函数存储在被称为模块模 的独立文件中,让程序文件更简单、更易于理解;
  6. 学习了函数编写指南。

8-1 消息: 编写一个名为 display_message() 的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。
def display_message():print(1+1)
display_message()
2Process finished with exit code 0
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.title() + ".")
favorite_book("TOM and JEnny")
One of my favorite books is Tom And Jenny.Process finished with exit code 0
8-3 T恤: 编写一个名为 make_shirt() 的函数,它接受一个尺码以及要印到 T 恤上的字样。这个函数应打印一个句子,概要地说明 T 恤的尺码和字样。
使用位置实参调用这个函数来制作一件 T 恤;再使用关键字实参来调用这个函数。
def make_shirt(size, words):print("\nI would like to have a " + size + " T-shirt, which has words like " + words + '.')make_shirt('XL', 'Hello World')
make_shirt(words='I LOVE YOU', size='L')
I would like to have a XL T-shirt, which has words like Hello World.I would like to have a L T-shirt, which has words like I LOVE YOU.Process finished with exit code 0

8-4 大号T恤: 修改函数 make_shirt() ,使其在默认情况下制作一件印有字样 “I love Python” 的大号 T 恤。调用这个函数来制作如下 T 恤:一件印有默认字样的大号 T 恤、一件印有默认字样的中号 T 恤和一件印有其他字样的 T 恤(尺码无关紧要)。
def make_shirt(size='L', words='I love Python'):print("\nI would like to have a " + size + " T-shirt, which has words like " + words + '.')make_shirt()
make_shirt('M')
make_shirt(words='ABCDEFG')
I would like to have a L T-shirt, which has words like I love Python.I would like to have a M T-shirt, which has words like I love Python.I would like to have a L T-shirt, which has words like ABCDEFG.Process finished with exit code 0

8-5 城市: 编写一个名为 describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子,如 Reykjavik is in Iceland 。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。
def describe_city(CityName, Contry='China'):print(CityName + " is in " + Contry + ".")describe_city('Shanghai')
describe_city('London', 'England')
describe_city('Guangzhou')

Shanghai is in China.
London is in England.
Guangzhou is in China.Process finished with exit code 0
8-6 城市名: 编写一个名为 city_country() 的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面这样的字符串:
"Santiago, Chile" 

至少使用三个城市 - 国家对调用这个函数,并打印它返回的值。
def city_country(city, contry):full_infor = city + ', ' + contryreturn full_infor.title()infor = city_country('santiago', 'chile')
print(infor)
infor = city_country('shanghai', 'china')
print(infor)
infor = city_country('chognqing', 'china')
print(infor)
Santiago, Chile
Shanghai, China
Chognqing, ChinaProcess finished with exit code 0

8-7 专辑: 编写一个名为 make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使 用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。
def make_album(singer, album):dict_album = {'signer': singer,'album': album}return dict_albuminformation = make_album('zhuli', 'FULL world')
print(information)
information = make_album('sisi', 'a little bird')
print(information)
information = make_album('rose', 'Fly away')
print(information)
{'signer': 'zhuli', 'album': 'FULL world'}
{'signer': 'sisi', 'album': 'a little bird'}
{'signer': 'rose', 'album': 'Fly away'}Process finished with exit code 0

给函数 make_album() 添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。
def make_album(singer, album, song_number=''):dict_album = {'signer': singer,'album': album}if song_number:dict_album['song_number'] = song_numberreturn dict_albuminformation = make_album('zhuli', 'FULL world')
print(information)
information = make_album('sisi', 'a little bird', 5)
print(information)
information = make_album('rose', 'Fly away',song_number=7)
print(information)
{'signer': 'zhuli', 'album': 'FULL world'}
{'signer': 'sisi', 'album': 'a little bird', 'song_number': 5}
{'signer': 'rose', 'album': 'Fly away', 'song_number': 7}Process finished with exit code 0

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

def make_album(singer, album, song_number=''):dict_album = {'signer': singer,'album': album}if song_number:dict_album['song_number'] = song_numberreturn dict_albumwhile True:print("Welcome to join in the game~")print("(enter 'q' at any time to quit)")name = input("\nPlease enter a singer name: ")if name == 'q':breakalbum = input("Please enter " + name.title() + "`s album name: ")if album == 'q':breakoutput = make_album(name, album)print(output)
Welcome to join in the game~
(enter 'q' at any time to quit)Please enter a singer name: Tom
Please enter Tom`s album name: July
{'signer': 'Tom', 'album': 'July'}
Welcome to join in the game~
(enter 'q' at any time to quit)Please enter a singer name: qProcess finished with exit code 0
8-9 魔术师: 创建一个包含魔术师名字的列表,并将其传递给一个名为 show_magicians() 的函数,这个函数打印列表中每个魔术师的名字。
def show_magicians(names):for name in names:print(name.title())magicians = ['Tom', 'JHON', 'ROSE', 'TONY', 'Alice']
show_magicians(magicians)
Tom
Jhon
Rose
Tony
AliceProcess finished with exit code 0

8-10 了不起的魔术师: 在你为完成练习 8-9 而编写的程序中,编写一个名为 make_great() 的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样 “the Great” 。调用函数 show_magicians() ,确认魔术师列表确实变了。
def show_magicians(names):for name in names:print(name.title())def make_great(repeat_name):great_magicians = []while magicians:magician = magicians.pop()great_magician = magician + ' the Great'great_magicians.append(great_magician)for great_magician in great_magicians:magicians.append(great_magician)magicians = ['Tom', 'JHON', 'ROSE', 'TONY', 'Alice']
show_magicians(magicians)print('\n')
make_great(magicians)
show_magicians(magicians)
Tom
Jhon
Rose
Tony
AliceAlice The Great
Tony The Great
Rose The Great
Jhon The Great
Tom The GreatProcess finished with exit code 0

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

# 创建show_magicians 函数,并打印所有 魔术师的名字。
def show_magicians(magicians):for magician in magicians:print(magician.title())# 创建make_great函数def make_magician(magicians):# 将the great 加入每个魔术师的名字后面# 创建一个新的函数,放 zzz+ the greatgreat_magicians = []# 让每个名字变成 magician+ the greatwhile magicians:magician = magicians.pop()great_magician = magician + ' the Great'great_magicians.append(great_magician)# 将great_magicians 放入 magicians中for great_magician in great_magicians:magicians.append(great_magician)return magiciansmagicians = ['Tom', 'JHON', 'ROSE', 'TONY', 'Alice']
show_magicians(magicians)print("\nGreat magicians: ")
great_magicians = make_magician(magicians[:])
show_magicians(great_magicians)print("\nOriginal magicians: ")
show_magicians(magicians)
Tom
Jhon
Rose
Tony
AliceGreat magicians:
Alice The Great
Tony The Great
Rose The Great
Jhon The Great
Tom The GreatOriginal magicians:
Tom
Jhon
Rose
Tony
AliceProcess finished with exit code 0
8-12 三明治: 编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客 点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。
# 方法一:
def add_food(foods):"""打印一条消息"""print("\nYou would like to order " + foods + " sandwich.")add_food('orange')
add_food('apple')
add_food('banana')# 方法二:
def add_food(*toppings):"""打印一条消息"""print("\nMaking a sandwich with the following toppings: ")for topping in toppings:print("-" + topping)add_food('orange', 'banana', 'apple')

You would like to order orange sandwich.You would like to order apple sandwich.You would like to order banana sandwich.Making a sandwich with the following toppings:
-orange
-banana
-appleProcess finished with exit code 0

8-13 用户简介: 复制前面的程序 user_profile.py ,在其中调用 build_profile() 来创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键 - 值 对。
def build_profile(first, last, **user_info):profile = {'first_name': first, 'last_name': last}for k, v in user_info.items():profile[k] = vreturnuser_profile = build_profile('Jin', 'Ho', age='18', weight='45kg')
print(user_profile)

{'first_name': 'Jin', 'last name': 'Ho', 'age': '18', 'weight': '45kg'}Process finished with exit code 0

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

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

def make_car(company, size, **cars_info):car_profile = {'car_company': company, 'car_size': size}for k, v in cars_info.items():car_profile[k] = vreturn car_profilecar = make_car('subaru', 'outback', color='blue', tow_package='pink')
print(car)
{'car_company': 'subaru', 'car_size': 'outback', 'color': 'blue', 'tow_package': 'pink'}Process finished with exit code 0
8-15 打印模型: 将示例 print_models.py 中的函数放在另一个名为 printing_functions.py 的文件中;在 print_models.py 的开头编写一条 import 语句,并修改这个文件以使用导 入的函数。
8-16 导入: 选择一个你编写的且只包含一个函数的程序,并将这个函数放在另一个文件中。在主程序文件中,使用下述各种方法导入这个函数,再调用它:
import module_name
from module_name import fn
function_name
from module_name
import function_name as fn
import module_name as mn
from module_name import *

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

python编程:从入门到实践 第八章知识汇总 + 习题8-1~8-17相关推荐

  1. Python编程从入门到实践第五章部分习题

    Python编程从入门到实践第五章部分习题 5-8 5-9` names = ['admin','zhang','li','zhao','song'] for name in names:if nam ...

  2. python编程从入门到实践第八章_Python编程从入门到实践的第三天

    #-*- coding = utf-8 -*- #今天是12月24号了,天气阴,不是太好,这是我看Python编程从入门到实践的第三天,现在是上午,我是皮卡丘,这是我敲的第八章的代码 #第八章练习题1 ...

  3. Python编程:从入门到实践(基础知识)

    第一章 起步 计算机执行源程序的两种方式: 编译:一次性执行源代码,生成目标代码 解释:随时需要执行源代码 源代码:采用某种编程语言编写的计算机程序 目标代码:计算机可执行,101010 编程语言分为 ...

  4. Python编程-从入门到实践第15章课后习题详解

    第15章 使用Plotly模拟掷骰子--课后习题答案 练习15-6 #掷两个D8 from plotly.graph_objs import Bar,Layout from plotly import ...

  5. Python编程从入门到实践(第三、四章的列表和元祖)

    1.Python中列表用[]来表示,并用逗号分隔其中元素 2.访问列表元素,给出元素的索引值即可(索引从0开始) 3.修改,添加和删除元素 3.1修改时给出列表名和修改元素的索引,然后赋新值 3.2在 ...

  6. python编程从入门到实践第九章——类

    相关文章链接: python编程从入门到实践第二章--变量和简单数据类型 python编程从入门到实践第三章--列表简介 python编程从入门到实践第四章--操作列表 python编程从入门到实践第 ...

  7. Python编程从入门到实践(第二版)课后习题自写代码

    Python编程从入门到实践(第二版)课后习题自写代码 第八章 函数 最近自学的python,动手做了一下课后习题,错误也许会有,和大家一起探讨.多多指教! 8.3 返回值 动手试一试代码片 &quo ...

  8. python编程 从入门到实践怎么样-python编程从入门到实践这本书怎么样

    <Python编程-从入门到实践>作者: Eric Matthes,已翻译为中文,人民邮电出版社出版. python编程从入门到实践怎么样? 我们一起看看已经学习的同学对这本书的口碑和评价 ...

  9. python编程入门指南怎么样-python编程从入门到实践这本书怎么样

    <Python编程-从入门到实践>作者: Eric Matthes,已翻译为中文,人民邮电出版社出版. python编程从入门到实践怎么样? 我们一起看看已经学习的同学对这本书的口碑和评价 ...

最新文章

  1. ESP32检测调制激光信号程序优化
  2. 糍粑大叔的独游之旅-开篇语
  3. This function or variable may be unsafe
  4. nodejs写html文件路径,Nodejs读取文件时相对路径的正确写法(使用fs模块)
  5. P4201-[NOI2008]设计路线【结论,树形dp】
  6. 屌丝笔记本玩Windows Phone 8开发(在Windows Server 2012中安装WP8 SDK)
  7. win下修改anaconda的jupyter notebook默认打开路径
  8. BigDecimal.divide方法
  9. 一个可以免费下载数据集的网站
  10. Studio3T安装
  11. 最基础内网ip地址配置
  12. 苹果手机数据线正确鉴定方法
  13. (3)Pairing Functions Element Functions
  14. WebDriverPool浏览器驱动池 减少驱动频繁打开和关闭引起的资源损耗
  15. 论文研究范围从什么角度怎么写?
  16. 嵌入式工资为什么比纯软工资低那么多?
  17. C++库常用函数一览表
  18. vue 3.0 即将发布,敬请期待
  19. Python|为什么列表推导式会更快
  20. linux技术咨询,Linux技术咨询委员会已完成对UMN内核漏洞植入事件的调查

热门文章

  1. Eclipse配置SSM框架(非maven模式)
  2. c#线程中的属性isbackground
  3. 轻量级的PHP在线考试系统源码+实测可用
  4. 无理取闹,我Release要你pdb文件做啥
  5. 龙芯服务器稳定性,真实现状!国产龙芯水平究竟如何(续)
  6. Qt——绘制瀑布图/热度图
  7. Seata-AT如何保证分布式事务一致性
  8. Academic Phrasebank 2021《学术短语库 2021在线版 英译汉》
  9. c语言错误的常量表达式,C struct object Stack – 在常量表达式中不允许函数调用(错误)...
  10. C语言学习入门篇(1.1)