六、函数

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

 

posted @   鹤比纷恆红  阅读(11)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示