2026/1/8 函数2

1 阅读7分钟

今天看了罗振宇编著的《预测之书》,里面有一句话,我想要在这里分享给大家: “荣格认为,人的一生大致可以分成两个阶段:前半生的重心在于繁衍和延续生命;到了中年,第一阶段告一段落,我们的心灵会踏上“第二旅程”——开始重新关注自我,勇敢面对并整合自己的阴影,更深刻地理解潜意识,追问此生真正的灵魂召唤是什么。” 而于我,从步入2025年开始,我越来越发现,人的轨迹是个圆,不管中途你迷失了多久,做了多少次违心的决定,你终归会回到原点,那个最接近你内心最真实的点,从而获得平和。

言归正传,今天复习了函数的第二部分,笔记如下:

练习

  • T恤
def make_shirt(size,phrase):
	print(f"The size of your shirt is '{size}' and we will print '{phrase.title()}' in front of it.")

make_shirt('L','hello world')
# 》The size of your shirt is 'L' and we will print 'Hello World' in front of it.
def make_shirt(size,phrase):
	print(f"The size of your shirt is '{size}' and we will print '{phrase.title()}' in front of it.")

make_shirt(size='L',phrase='hello world')
# 》The size of your shirt is 'L' and we will print 'Hello World' in front of it.
  • 大号T恤
def make_shirt(size,phrase='I love Python'):
	print(f"The size of your shirt is '{size}' and we will print '{phrase.title()}' in front of it.")

make_shirt('L')
# 》The size of your shirt is 'L' and we will print 'I love Python' in front of it.
make_shirt(size='M',phrase='Hello World')
# 》T size of your shirt is 'M' and we will print 'Hello World' in front of it.
  • 城市
def describe_city(name,country='China'):
	print(f"{name.title()} is in {country.title()}.")
describe_city('shanghai')
describe_city('beijing')
describe_city(name='new york',country='the america')
# 》Shanghai is in China.
# 》Beijing is in China.
# 》New York is in The America.

5.返回值

  • 返回简单值:return
def get_formatted_name(first_name,last_name):
	"""返回标准格式的姓名"""
	full_name=f"{first_name} {last_name}"
	return full_name.title()
musician= get_formatted_name('jimi','hendrix')
print(musician)
  • 让实参变成可选的
def get_formatted_name(first_name,last_name,middle_name=''):
	"""返回标准格式的姓名"""
	if middle_name:
		full_name=f"{first_name} {middle_name} {last_name}"
	else:
		full_name=f"{first_name} {last_name}"
	return full_name.title()

musician=get_formatted_name('jimi','hendrix')
print(musician)
musician=get_formatted_name('john','hooker','lee')
print(musician)

# 》Jimi Hendrix
# 》John Lee Hooker
  • 返回字典 person.py
def build_person(first_name,last_name):
	"""返回一个字典,其中包含有关一个人的信息"""
	person={'first_name':first_name,'last_name':last_name}
	return person
musician=build_person('jimi','hendrix')
print(musician)
# 》{'first_name': 'jimi', 'last_name': 'hendrix'}
def build_person(first_name,last_name,age=None):
	"""返回一个字典,其中包含有关一个人的信息"""
	person={'first':first_name,'last':last_name}
	if age:
		person['age']=age
	return person
musician = build_person('jimi','hendrix',age=27)
print(musician)
# 》{'first': 'jimi', 'last': 'hendrix', 'age': 27}
  • 与while联合使用
def get_formatted_name(first_name,last_name):
	"""返回规范格式的姓名"""
	full_name=f"{first_name} {last_name}"
	return full_name.title()
while True:
	print("\nPlease tell me your name:")
	print("enter 'q' at any time to quit")
	f_name=input("First name: ")
	if f_name =='q':
		break
	l_name=input("Last name: ")
	if l_name == 'q':
		break
	formatted_name = get_formatted_name(f_name,l_name)
	print(f"\nHello,{formatted_name}!") 

练习

歌曲专辑
def make_album(singer,name,song=None):
	album={"Singer":singer,"Name":name}
	if song:
		album['Song'] = song
	return album
masician=make_album('Jay','fantexi',song=26)	
print(masician)
def make_album(singer,name):
	album={"Singer":singer,"Name":name}
    while True:
	    print("Please tell me the information of the album""Enter 'quit' if you want to exit")
	    si=input("singer")
	    if si =='quit':
		    break
		na=input("Name")
		if na == 'quit':
			break
masician=make_album('Jay','fantexi')
def make_album(singer,name):
    """定义专辑"""
    album={"Singer":singer,"Name":name}
    return album
while True:
    print("Please tell me the information of the album.""Enter 'quit' if you want to exit.")
    si = input("singer:")
    if si == 'quit':
        break
    na = input("Name:")
    if na == 'quit':
        break
    formatted_album=make_album(si,na)
    print(f"\nThe information of you album is following: ")
    print(formatted_album)

6. 传递列表

greet_users.py
def greet_users(names):
	"""向列表中的每个用户发出简单的问候"""
	for name in names:
		msg=f"Hello,{name.title()}!"
		print(msg)
		
usernames=['hannah','ty','margot']
greet_users(usernames)
  • 在函数中修改列表 printing_models.py
# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['phone case','robot pendant','dodecahedron']
completed_models=[]

# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表 completed_models中
while unprinted_designs:
	current_design = unprinted_designs.pop()
	print(f"Printing model: {current_design}")
	completed_models.append(current_design)

# 显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
	print(completed_model)
def print_models(unprinted_designs,completed_models):
	"""
	模拟打印每个设计,直到没有未打印的设计为止
	打印每个设计后,都将其移到列表completed_models中
	"""
	while unprinted_models:
		current_model = unprinted_designs.pop()
		print(f"Printing model:{current_model}")
		completed_models.append(current_model)

def show_completed_models(completed_models):
	"""显示打印好的所有模型"""
	print("\nThe following models have been printed:")
	for completed_model in completed_models:
		print(completed_model)

unprinted_designs = ['phone case','robot pendant','dodecahedron']
completed_models = []

print_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

# 》Printing model:dodecahedron
# 》Printing model:robot pendant
# 》Printing model:phone case

# 》The following models have been printed:
# 》dodecahedron
# 》robot pendant
# 》phone case

==推荐每个函数只负责一项具体工作==

  • 可以利用切片来创建副本,使得保留原先的列表内容,但是该方法会增加运行时间和内存压力,效率下降,所以正常情况下需要慎重使用。

练习

  • 消息
def show_messages(list_a):
	for mes in list_a:
		print(mes)
show_messages(['今天天气不错','明天将会是个阴天','后天大概率会下雨'])
  • 发送消息
def send_messages(list_a[:],sent_messages):
	"""打印列表"""
	while list_a[:]:
		mes = list_a[:].pop()
		print(mes)
		sent_messages.append(mes)

def show_list(list_a,sent_messages):
	"""打印两个列表"""
	print(f"需要打印的列表是 {list_a}")
	print(f"已打印的列表如下:{sent_messages})

list1 = ['今天天气不错','明天将会是个阴天','后天大概率会下雨']
sent_messages=[]		
send_messages(list1[:],sent_messages)
show_list(list1,sent_messages)
def send_messages(messages, sent_messages):
    """发送消息并将已发送的消息移动到sent_messages列表"""
    print("正在发送消息...")
    while messages:
        current_message = messages.pop()
        print(f"已发送: {current_message}")
        sent_messages.append(current_message)
    print("所有消息已发送完毕。\n")

def show_list_status(original_list, sent_list):
    """显示列表状态"""
    print("=" * 40)
    print("列表状态报告:")
    print(f"原始消息列表: {original_list}")
    print(f"已发送消息列表: {sent_list}")
    print(f"原始列表中剩余消息数: {len(original_list)}")
    print(f"已发送消息数: {len(sent_list)}")
    print("=" * 40)

# 原始消息列表
unsent_messages = ['今天天气不错', '明天将会是个阴天', '后天大概率会下雨']
sent_messages = []

# 显示初始状态
print("初始状态:")
show_list_status(unsent_messages[:], sent_messages)  # 使用副本显示

# 发送消息
send_messages(unsent_messages[:], sent_messages)  # 使用副本,不修改原列表

# 显示最终状态
print("发送后状态:")
show_list_status(unsent_messages, sent_messages)

7.传递任意数量的实参

  • 利用 “*” 想函数传达讲所有实参封装到一个元组中,即便只有一个实参值也如此 pizza.py
def make_pizza(*toppings):
	"""打印顾客点的所有配料"""
	print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

# 》('pepperoni',)
# 》('mushrooms', 'green peppers', 'extra cheese')
  • 搭配循环一起
def make_pizza(*toppings):
	"""概述要制作的比萨"""
	print("\nMaking a pizza with the following toppings:")
	for topping in toppings:
		print(f"- {topping}")

make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')

# 》Making a pizza with the following toppings:
# 》- pepperoni

# 》Making a pizza with the following toppings:
# 》- mushrooms
# 》- green peppers
# 》- extra cheese
  • 结合使用位置实参和任意数量的实参,==但任意数量实参的形参必须放在最后,函数会先匹配位置实参和关键字实参,再将余下的所有实参都集中到最后一个形参中。==
def making_pizza(size,*toppings):
	"""概述要制作的比萨"""
	print(f"\nMaking a {size}-inch pizza with the following toppings:")
	for topping in toppings:
		print(f"-{topping}")

making_pizza(12,'mushrooms','green peppers','extra cheese')
  • 使用任意数量的关键字实参,“**” 可以调用任意数量的键值对,创建一个字典。 user_profile.py
def build_profile(first,last,**user_info):
	"""创建一个字典,其中包含我们知道的有关用户的一切"""
	user_info['first_name'] = first
	user_info['last_name'] = last
	return user_info
user_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

# 》{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

练习

  • 三明治
def make_sandwichs(*toppings):
	print("The sandwich you order is following:")
	for topping in toppings:
		print(f"-{topping}")
make_sandwichs('egg','vegetable','beef')

# 》The sandwich you order is following:
-egg
-vegetable
-beef
def build_profile(first,last,**user_info):
	"""创建一个字典,其中包含我们知道的有关用户的一切"""
	user_info['first_name'] = first
	user_info['last_name'] = last
	return user_info
user_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

# 》{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}
  • 汽车
def make_car(maker,type1,**car_info):
    """创建车的型号"""
    car_info['Maker'] = maker
    car_info['Type'] = type1
    return car_info
car=make_car('subaru','outback',color='blue',tow_package=True)
print(car)

8.将函数存储在模块中

  • 导入整个模块: 模块是扩展名为.py的文件。 pizza.py
def make_pizza(size,*toppings):
	"""概述要制作的比萨"""
	print(f"\nMaking a {size}-inch pizza with the following toppings:")
	for topping in toppings:
		print(f"-{topping}")
 making_pizzas.py
     import pizza
     pizza.make_pizza(16,'pepperoni')
     pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')
  • 导入特定的函数,多个函数之间用逗号分隔 from module_name import function_name

  • 使用 as 给函数指定别名 from module_name import function_name as fn

from pizza import make_pizza as mp
mp(16,'pepperoni')
  • 使用as 给模块指定别名 import pizza as p

  • 导入模块中的所有函数 from pizza import * ==一般不建议使用,不够清晰