|
《Python编程:从入门到实践(第3版)》读书笔记7:函数
[复制链接]
本帖最后由 逝逝逝 于 2025-3-14 17:14 编辑
第八章 函数
在 Python 中,函数(Function)是一段可重复使用的代码块,用于执行特定任务并提高代码的模块化和可维护性。
基本语法
定义函数
- def 函数名(参数1, 参数2=默认值, *args, **kwargs):
- """文档字符串(可选)"""
- 代码块
- return 返回值
示例
- def greet(name):
- """向指定名字的用户问好"""
- print(f"Hello, {name}!")
-
- greet("Alice")
参数类型
(1) 位置参数(Positional Arguments)
按顺序传递参数:
- def add(a, b):
- return a + b
-
- print(add(3, 5))
(2) 默认参数(Default Arguments)
为参数指定默认值
- def power(base, exponent=2):
- return base ** exponent
-
- print(power(3))
- print(power(3, 4))
(3) 可变参数(*args)
接收任意数量的位置参数(以元组形式存储):
- def sum_all(*numbers):
- return sum(numbers)
-
- print(sum_all(1, 2, 3))
(4) 关键字参数(**kwargs)
接收任意数量的关键字参数(以字典形式存储):
- def print_info(**details):
- for key, value in details.items():
- print(f"{key}: {value}")
-
- print_info(name="Alice", age=30)
-
-
-
返回值
return语句结束函数执行并返回结果。
可返回多个值(实际返回一个元组):
- def min_max(numbers):
- return min(numbers), max(numbers)
-
- result = min_max([3, 1, 4])
- print(result)
4. 作用域(Scope)
局部变量:函数内定义的变量,仅在函数内有效。
全局变量:函数外定义的变量,需用 `global` 关键字修改:
- count = 0
-
- def increment():
- global count
- count += 1
-
- increment()
- print(count)
函数编写指南:
给函数指定描述性名称,且只能用小写字母和下划线。
单一职责原则:一个函数只做一件事。
文档字符串:用 `"""注释"""` 说明函数功能。
给形参指定默认值时,等含两边不要有空格,函数调用中的关键字实参也应该遵守这种约定。
如果形参很多,导致函数定义的长度超过了79个字符,可在函数定义中输入左括号后按回车健,并在下一行连按两次制表符键,从而将形参和只缩进一层的函数体区分开来
- def function_name(
- parameter_0,parameter_1,parameter_2,
- parameter_3,parameter_4,parameter_5):
- function body...
-
-
所有的import语句都应放在文件开头。唯一的例外时,你要在文件开头使用注释来描述整个程序。
练习 8.1 消息
编写一个名为display_message()的函数,让它打印一个句子,指出本章的主题是什么。
调用这个函数,确认显示的消息正确无误。
- def display_message():
- '''指出文章的主题是什么'''
- print('The theme of the article is ...')
- display_message()
运行结果
- The theme of the article is ...
练习 8.2 喜欢的书
- def favorite_book(title):
- print(f'My favorite book is {title}')
- favorite_book("the Old Man and the Sea.")
练习 8.3 T 恤
编写一个名为make_shirt()的函数,它接受一个尺码以及要印到T恤上的字样。这个函数应该打印一个句子,简要地说明T恤的尺码和字样。
先使用位置实参调用这个函数来制作一件 T 恤,再使用关键字实参来调用这个函数。
- def make_shirt(size,characters):
- print(f'The size is {size},and the character is {characters}')
- make_shirt('L','EEWORLD')
运行结果
- The size is L,and the character is EEWORLD
练习 8.4 大号 T 恤
修改make_shirt()函数,使其在默认情况下制作一件印有“I love Python”字样的大号T恤。
调用这个函数分别制作一件印有默认字样的大号T恤,一件印有默认字样的中号T恤,以及一件印有其他字样的T恤(尺码无关紧要)。
- def make_shirt(size = 'L',characters = 'I love EEWORLD!'):
- print(f'The size is {size},and the character is {characters}')
- make_shirt()
- make_shirt('M')
- make_shirt(characters = 'BEST EEWORLD')
练习 8.5 城市
编写一个名为describe_city()的函数,它接受一座城市的名字以及该城市所属的国家。
这个函数应该打印一个像下面这样简单的句子。
Reykjavik is in Iceland.
给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,其中至少有一座城市不属于默认的国家。
- def describe_city(name,country = 'China'):
- print(f'{name} is in {country}.')
- describe_city('Shanghai')
- describe_city('Beijing')
- describe_city('New York','America')
运行结果
- Shanghai is in China.
- Beijing is in China.
- New York is in America.
练习 8.6 城市名
编写一个名为city_country()的函数,它接受城市的名称及其所属的国家。这个函数应返回一个格式类似于下面的字符串:
"Santiago, Chile"
至少使用三个城市——国家对调用这个函数,并打印它返回的值。
- def city_country(city,country):
- msg = f'{city},{country}'
- return msg
- msg_1 = city_country('Beijing','China')
- msg_2 = city_country('Shanghai','China')
- msg_3 = city_country('Hangzhou','China')
- print(msg_1)
- print(msg_2)
- print(msg_3)
运行结果
- Beijing,China
- Shanghai,China
- Hangzhou,China
练习 8.7 专辑
编写一个名为make_album()的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手名和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。
给make_album()函数添加一个默认值为None的可选形参,以便存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。
- def make_album(singer,title,num_songs = None):
- album_dict = {
- 'artist': singer.title(),
- 'title': title.title()
- }
- if num_songs:
- album_dict['num_songs'] = num_songs
- return album_dict
- album = make_album('metallica', 'ride the lightning')
- print(album)
- album = make_album('beethoven', 'ninth symphony')
- print(album)
- album = make_album('willie nelson', 'red-headed stranger')
- print(album)
- album = make_album('iron maiden', 'piece of mind', 8)
- print(album)
-
运行结果
- {'artist': 'Metallica', 'title': 'Ride The Lightning'}
- {'artist': 'Beethoven', 'title': 'Ninth Symphony'}
- {'artist': 'Willie Nelson', 'title': 'Red-Headed Stranger'}
- {'artist': 'Iron Maiden', 'title': 'Piece Of Mind', 'num_songs': 8}
练习 8.8 用户的专辑
在为练习8.7编写的程序中,编写一个while循环,让用户输入歌手名和专辑名。获取这些信息后,使用它们来调用make_album()函数并将创建的字典打印出来。在这个while循环中,务必提供退出途径。
- def make_album(artist, title):
- album_dict = {
- 'artist': artist.title(),
- 'title': title.title(),
- }
- return album_dict
- title_prompt = "\nWhat album are you thinking of? "
- artist_prompt = "Who's the artist? "
- print("Enter 'quit' at any time to stop.")
- while True:
- title = input(title_prompt)
- if title == 'quit':
- break
- artist = input(artist_prompt)
- if artist == 'quit':
- break
- album = make_album(artist, title)
- print(album)
- print("\nThanks for responding!")
练习 8.9 消息
创建一个列表,其中包含一系列简短的文本消息。将这个列表传递给一个名为show_messages()的函数,这个函数会打印列表中的每条文本消息。
- def show_messaage(msgs):
- for msg in msgs:
- print(msg)
- cities = ['Beijing','Shanghai','Nanjing']
- show_messaage(cities)
-
运行结果
练习 8.10 发送消息
在为练习8.9编写的程序中,编写一个名为send_messages()的函数,将每条消息都打印出来并移到一个名为sent_messages的列表中。调用send_messages()函数,再将两个列表都打印出来,确认把消息移到了正确的列表中。
- def show_messaage(msgs):
- for msg in msgs:
- print(msg)
- def send_messages(msgs, sent_messages):
- print("\nSending all messages:")
- while msgs:
- current_message = msgs.pop()
- print(current_message)
- sent_messages.append(current_message)
- cities = ['Beijing','Shanghai','Nanjing']
- show_messaage(cities)
- sent_messages = []
- send_messages(cities, sent_messages)
- print("\nFinal lists:")
- print(cities)
- print(sent_messages)
运行结果
- Beijing
- Shanghai
- Nanjing
-
- Sending all messages:
- Nanjing
- Shanghai
- Beijing
-
- Final lists:
- []
- ['Nanjing', 'Shanghai', 'Beijing']
练习 8.11 消息归档
修改为练习8.10编写的程序,在调用函数send_messages()时,向它传递消息列表的副本。调用send_messages()函数后,将两个列表都打印出来,确认原始列表保留了所有的消息。
- def show_messaage(msgs):
- for msg in msgs:
- print(msg)
- def send_messages(msgs, sent_messages):
- print("\nSending all messages:")
- while msgs:
- current_message = msgs.pop()
- print(current_message)
- sent_messages.append(current_message)
- cities = ['Beijing','Shanghai','Nanjing']
- show_messaage(cities)
- sent_messages = []
- send_messages(cities[:], sent_messages)
- print("\nFinal lists:")
- print(cities)
- print(sent_messages)
运行结果
- Beijing
- Shanghai
- Nanjing
-
- Sending all messages:
- Nanjing
- Shanghai
- Beijing
-
- Final lists:
- ['Beijing', 'Shanghai', 'Nanjing']
- ['Nanjing', 'Shanghai', 'Beijing']
练习 8.12 三明治
编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。
- ef make_sandwich(*items):
- print("\nI'll make you a great sandwich:")
- for item in items:
- print(f" ...adding {item} to your sandwich.")
- print("Your sandwich is ready!")
- make_sandwich('roast beef', 'cheddar cheese', 'lettuce', 'honey dijon')
- make_sandwich('turkey', 'apple slices', 'honey mustard')
- make_sandwich('peanut butter', 'strawberry jam')
运行结果
- I'll make you a great sandwich:
- ...adding roast beef to your sandwich.
- ...adding cheddar cheese to your sandwich.
- ...adding lettuce to your sandwich.
- ...adding honey dijon to your sandwich.
- Your sandwich is ready!
-
- I'll make you a great sandwich:
- ...adding turkey to your sandwich.
- ...adding apple slices to your sandwich.
- ...adding honey mustard to your sandwich.
- Your sandwich is ready!
-
- I'll make you a great sandwich:
- ...adding peanut butter to your sandwich.
- ...adding strawberry jam to your sandwich.
- Your sandwich is ready!
练习 8.14 汽车
编写一个函数,将一辆汽车的信息存储在字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。在调用这个函数时,提供必不可少的信息,以及两个名值对,如颜色和选装配件。这个函数必须能够像下面这样调用:
car = make_car('subaru', 'outback', color='blue', tow_package=True)
打印返回的字典,确认正确地处理了所有的信息。
- def make_car(manufacturer, model, **options):
- car_dict = {
- 'manufacturer': manufacturer.title(),
- 'model': model.title(),
- }
- for option, value in options.items():
- car_dict[option] = value
- return car_dict
- my_outback = make_car('subaru', 'outback', color='blue', tow_package=True)
- print(my_outback)
- my_old_accord = make_car('honda', 'accord', year=1991, color='white',headlights='popup')
- print(my_old_accord)
运行结果
- {'manufacturer': 'Subaru', 'model': 'Outback', 'color': 'blue', 'tow_package': True}
- {'manufacturer': 'Honda', 'model': 'Accord', 'year': 1991, 'color': 'white', 'headlights': 'popup'}
|
|