函数的定义
一个简单的打印问候语的函数:
def greet_user():
"""函数体内的执行代码"""
print("hello!")
可以稍作修改,将用户名作为函数参数。
def greet_user(user_name):
"""函数体内的执行代码"""
print(f"hello,{user_name.title()}!")
greet_user('zhang san')#调用函数greet_user(user_name)
结果:

根据位置传递实参
调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参,最简单的方式即按位置关联。
如:
def describe_pet(animal_type,prt_name):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {prt_name}.")
describe_pet('hamster','harry')#hamster:仓鼠
结果:

关键字传参
关键字传参是传递给函数的名称值对。不需要考虑顺序,直接将名称和值关联起来。
如:
def describe_pet(animal_type,pet_name):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name}.")
describe_pet(pet_name = 'harry',animal_type = 'hamster')#hamster:仓鼠
结果:

默认值
在编写函数时,可给每个形参指定默认值,在调用函数中给形参提供了实参时,Python将使用指定实参值,否则,使用形参的默认值。
如:
代码:
def describe_pet(pet_name,animal_type = 'dog'):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name}.")
describe_pet(pet_name = 'hale')
describe_pet('hale')#两种等价
结果:

注
使用默认值时,必须先在形参列表中列出没有默认值的形参。在列出有默认值的实参。
由于可混合使用位置形参、关键字实参和默认值,通常有多种等效的函数调用方式。
返回值
函数并非总是直接显示输出,它可以处理一些数据,并返回一个或一组值,称为返回值。在函数中,可使用return语句将值返回到调用函数的代码行。
如:
代码:
函数定义后面一定加冒号
def get_formatted_name(first_name,last_name):#**函数定义后面一定加冒号**
full_name = f"{first_name}{last_name}"
return full_name.title()
print(get_formatted_name('tang','liu'))
结果:

返回值为字典
函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构。
如:
代码:
参数不需要用引号括起来,只有字符串需要。
def build_person(first_name,last_name,age = None):
person = {'first':first_name,'last':last_name,'age':age}
return person
person1 = build_person('zhang','san','36')
print(person1)
结果:

传参数为列表
向函数传递列表很有用,其中包含的可能是名字、数或更复杂的对象(如字典)。将列表传递给函数后,函数就能直接访问其内容。
如:
代码:
def greet_users(names):
for name in names:
print(f"Hello,{name.title()}!")
usernames = ['tang','zhang','he']
greet_users(usernames)
结果:

传递任意参数的实参
有时候,我们不知道需要接受多少个实参,Python可以调用语句接受任意数量的实参。
如:
代码:
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
结果:

注
形参名*toppings 中的星号让Python创建一个名为toppings 的空元组,并将收
到的所有值都封装到这个元组中。
结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参
放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一
个形参中。
如:
代码:
def make_pizza(size,*toppings):
"""打印顾客点的所有配料"""
print(f"披萨的尺寸为:{size}。")
print(f"需要添加的配料:{toppings}")
make_pizza('16','mushrooms','green peppers','extra cheese')
将第一个参数传给第一个形参,剩下的全传给任意数量参数*toppings
结果:


1593

被折叠的 条评论
为什么被折叠?



