首页 > 其他分享 >六、函数

六、函数

时间:2024-07-27 17:50:18浏览次数:7  
标签:last 函数 pet name print 实参 first

6.1 定义函数

def greet_user():
    """显示简单的问候语"""
    print('Hello!')
greet_user() # 调用函数

 6.1.1 向函数传递信息

def greet_user(username):
"“显示简单的问候语"”
	print(f"Hello,{username.title()}!")
greet_user('jesse')

 6. 2 实参和形参

6.2.1 位置实参

基于实参的顺序在函数调用时把每个实参关联到函数定义中的形参

def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
	print(f"{\nI have a (animal_type).")
	print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster','harry’)

6.2.2 关键字实参

def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
	print(f"{\nI have a (animal_type).")
	print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster',pet_name='harry’)

6.2.3 默认值

在调用函数时,给形参提供了实参,python就使用你指定的实参值。你没有给形参提供实参,就使用形参默认值
可给每个形参指定默认值。给animal_ype形参指定默认值dog

def describe_pet(animal_type,pet_name='dog’):
"""显示宠物的信息"""
	print(f"{\nI have a (animal_type).")
	print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='willie')
# 也可以这样describe_pet('willie')

 6.2.4 让实参变得可选

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)

6.2.5 返回字典

def build_person(first_name,last_name):
	"返回一个字典,其中包含有关一个人的信息"
	person ={'first':first_name,'last':last_name}
	return person
musician = build_person('jimi','hendrix)
print(musician)

# (‘first':'jimi','last':'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)              

6.3 传递列表

6.3.1 在函数中修改列表

def print_models(unprinted_designs,completed_models):
	while unprinted designs:
		current design unprinted designs.pop()
		print(f"Printing model:{current_design}")
		completed_models.append(current_design)
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)

 6.3.2 禁止函数修改列表

# 将列表的副本传递给函数
# function_name(list_name[:])
# 在上一例子中
print_models(unprinted designs[:],completed models)
# 原列表就不会变为空值

 6.4 传递任意数量的实参

形参名*toppings中的星号让Python创健一个名为toppings的空元组,并将收到的所有值都封装到这个元组中。

def make pizza(toppings):
# 打印顾客点的所有配料
	print(toppings)
	
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
# 上一句会报错,赋予实参过多
def make pizza(*toppings):
# 实参前加*便可赋予任意量

 6.4.1 结合使用位置实参和任意数量实参

def make_pizza(size,* toppings): # * toppings要写在后面
“打印顾客点的所有配料”
	print(f"\nMaking a (size)-inch pizza with the following toppings:
	for topping in toppings:
		print(f"-(topping)")
		
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms,'green peppers','extra cheese')

6.4.2 使用任意数量的关键字实参

形参*use_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称值对都放到这个字典中。在这个函数中,可以像访问其他字典那样访问user info中的名称值对。

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

 

标签:last,函数,pet,name,print,实参,first
From: https://www.cnblogs.com/pgl6/p/18327110

相关文章

  • ast获取指定python文件中携带指定装饰器函数的实现
    在实现自动化测试过程中,需要根据指定的装饰器来标记需要执行的用例或函数,下面根据使用ast库来实现读取指定文件中的数据结构后对其内容进行解析并拿到携带对应装饰器的函数。根据以下方法仅能解析func、class-func的数据结构,其余数据结构可能不兼容,需要根据实际情况进行完善调整......
  • 有参构造函数注入底层源码深入剖析**前戏
    有参构造函数注入底层源码深入剖析前戏方式一:创建两个类:publicclassTestDIBean{ publicStringsay(){ return"IamTestDIBean.say()"; }}packagecom.coding.spring.practies;publicclassTestDIBean1{ privateTestDIBeantestDIBean; publicTestDIBean......
  • useRoute 函数的详细介绍与使用示例
    title:useRoute函数的详细介绍与使用示例date:2024/7/27updated:2024/7/27author:cmdragonexcerpt:摘要:本文介绍了Nuxt.js中useRoute函数的详细用途与示例,展示了如何在组合式API中使用useRoute获取当前路由信息,包括动态参数、查询参数等,并提供了丰富的计算引用说明,如......
  • 《梦醒蝶飞:释放Excel函数与公式的力量》23.1 学生主导的项目案例
     第23章:学生项目展示 23.1学生主导的项目案例在《梦醒蝶飞:释放Excel函数与公式的力量》中,第23章将展示学生主导的项目案例。这些案例展示了学生如何运用所学的Excel函数与公式,解决实际问题,展示他们的创造力和分析能力。案例1:学校活动管理系统背景:某学校希望建立一个活动......
  • 《梦醒蝶飞:释放Excel函数与公式的力量》23.2 项目评估与反馈
     第23章:学生项目展示 23.2项目评估与反馈在学生项目展示中,项目评估与反馈是至关重要的一环。通过评估和反馈,可以识别项目中的优点和不足,帮助学生不断改进和提升。以下是项目评估与反馈的详细步骤和示例。项目评估的关键要素1.目标达成情况2.项目计划与执行3.数据准......
  • 《梦醒蝶飞:释放Excel函数与公式的力量》21.2 问题解决策略
     第21章:综合案例分析 21.2问题解决策略在综合案例分析中,解决问题的策略涉及多个步骤,从问题的识别、分析到实施解决方案和评估效果。通过系统的方法和多学科的知识,可以高效地解决复杂的问题。以下将介绍一个具体案例,并通过详细的步骤展示如何制定和实施问题解决策略。案例......
  • 函数调用结束后如何恢复调用前的现场
    函数调用结束后,恢复调用前的现场是一个涉及堆栈操作的重要过程。这个过程主要依赖于硬件栈(如x86架构中的栈)来保存和恢复函数的执行状态。以下是详细的恢复步骤:1.堆栈的作用在函数调用过程中,堆栈(Stack)被用来存储局部变量、函数参数以及函数的返回地址等信息。每个函数调用都......
  • 什么是函数重载以及它基于什么原则来区分不同的函数
    函数重载的定义函数重载(FunctionOverloading)是指在编程中允许同一个函数名定义多个具有不同参数类型或参数个数的函数,根据不同的参数类型或参数个数来确定调用哪个函数。这种机制提供了更灵活的函数调用方式,使得函数能够处理不同类型或数量的参数,而无需使用不同的函数名。函......
  • 绘制行星位置随时间的函数
    我一直在尝试模拟绕太阳运动的行星和小行星,我发现了这个链接:如何在已经绘制的椭圆上绘制行星轨道作为时间的函数?并且我决定研究并尝试其中的代码。但似乎我要么使用错误,要么代码错误,因为当我绘制火星、地球、木星、水星和金星的轨道时,它们似乎与美国宇航局的在线模拟......
  • Python 3 使用 super() 函数时出现“类型错误:__init__() 获得多个参数值”
    我正在使用继承的Python3编写一个OOP程序,当我尝试像这样初始化子类时遇到标题错误:classParent:def__init__(self,var1,var2):self.var1=var1self.var2=var2#moremethodsthattosomestuffclassChild(Parent):a=1#aan......