1、定义函数
下面是一个打印问候语的简单函数,名为greet_user():
def greet_user():
"""显示简单的问候语"""
print("Hello!")
greet_user()
第二行处的文本称为文档字符串的注释,描述了函数是做什么的。
2、向函数传递信息
def greet_user(username):
"""显示简单的问候语"""
print(f"Hello,{username.title()}")
greet_user('jesse')
3、传递实参
位置实参:
调用函数是,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。因此,最简单的关联方式是基于实参的顺序。这种关联方式称为位置实参。
示例:
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')
关键字实参:
关键字实参是传递给函数的名称值对。关键字实参无需考虑函数调用中的实参顺序,还清楚的指出了函数调用中各个值的用途。
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')
describe_pet(pet_name = 'harry',animal_type = 'hamster')
两个函数的结果是等效的。
使用关键字实参时,务必准确的指定函数定义中的形参名。
4、默认值
编写函数时,可以给每一个形参指定默认值。再调用函数中给形参提供了实参时,python将使用指定的实参值;否则,将使用形参的默认值。
def describe_pet(pet_name,animal_type = 'dog'):
"""显示宠物信息"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name = 'harry')
注意:使用默认参数时,必须先在形参列表中列出没有默认值的形参,在列出有默认值的实参。这让Python依然能够正确的解读位置实参。
5、等效的函数调用
鉴于可混合使用位置实参、关键字实参和默认值,通常有多种等效的函数调用方式。
示例:
def describe_pet(pet_name,animal_type = 'dog'):
"""显示宠物信息"""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
#一条名为Willie的小狗
describe_pet(pet_name = 'Willie')
describe_pet('Willie')
#一只名为Harry的仓鼠
describe_pet('harry','hamster')
describe_pet(pet_name = 'harry',animal_type = 'hamster')
describe_pet(animal_type = 'hamster',pet_name = 'Harry')
6、返回值
函数并非总是直接显示输出,他还可以处理一些数据,返回一个或一组值。函数返回的值成为返回值。在函数中,可以使用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('john','hooker','lee')
print(musician)
返回字典
示例:
def build_person(first_name,last_name):
"""返回一个字典,其中包含有关一个人的信息"""
person = {'first':first_name,'last':last_name}
return person
musician = build_person('jimi','hendrix')
print(musician)
示例扩展:
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',27)
print(musician)
结合使用函数和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}!")
7、传递列表
向函数传递列表,其中包含的可能是名字、数或更复杂的对象(如字典)。将列表传递给函数后,函数就能直接访问其内容。
def greet_suers(names):
"""像列表中的每位用户发出简单的问候"""
for name in names:
msg = f"Hello,{name.title()}!"
print(msg)
usernames = ['hannah','ty','margot']
greet_suers(usernames)
在函数中修改列表
将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的,这能够处理大量的数据。
def print_models(unprinted_designs,completed_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移动到列表completed_modeks中。
"""
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)
8、传递任意数量的实参
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 oeooers','extra cheese')
*topping中的的星号让Python创建一个名为topping的空元组,并将收到的所有值都封装到这个元组中。
结合使用位置实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
def make_pizza(size,*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 oeooers','extra cheese')
使用任意数量的关键字实参
def bulid_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = bulid_profile('albert','eistein',
location = 'princeton',
field = 'phyiscs')
print(user_profile)
build_profile()的定义要求提供名和姓,同时允许根据需要提供任意数量的名称值对。形参**user_info中的两个星号让Python创建一个空字典,并将收到的所有名称值对都放到这个字典中。
9、将函数存储在模块中
导入整个模块
导入特定函数
使用as给函数指定别名
需要在其导入的时候指定
使用as给模块指定别名
导入模块中的所有函数