- 函数内第一行通常书写注释,表明该函数的意义
- 注释后空一行,开始写代码块
- 函数定义结束后,开始写代码块
- 函数调用后空一行,在执行别的代码
6.1、定义函数
使用关键字def
来定义一个函数,然后跟上一个函数名并加上括号()
,最后以冒号结尾。
def greet_user():
print("hello!")
greet_user()
6.1.1、向函数传递信息
在函数名后面的括号中添加上索要传递的信息
def greet_user(username):
print("hello, " + username.title() + "!")
greet_user('jesse')
6.1.2、实参和形参
在函数定义中,函数名后括号里的username是形参,调用函数时,传递的jesse是一个实参,实参是调用函数传递给函数的信息。
6.2、传递实参
当函数中有多个实参时,向函数传递实参的方式有很多:
- 位置实参
- 关键字实参
- 列表和字典
给形参指定默认值时,等号两边不要有空格。
6.2.1、位置实参
调用函数时,每个实参都按顺序对应到函数定义的每个形参。
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "`s name is " + pet_name + ".")
describe_pet('hamster', 'harry')
6.2.2、关键字实参
传递给函数的名称-值对,直接在实参中将名称和值联系起来,关键字实参无需考虑函数调用中的实参顺序
def describe_pet(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "`s name is " + pet_name + ".")
describe_pet(animal_type="hamster", pet_name="harry")
6.2.3、默认值
编写函数时,可给每个形参指定默认值。在调用函数提供了实参的时候,使用提供的实参值;否则,使用默认值。可在函数调用中省略相应的实参。
def describe_pet(pet_name, animal_type='dog'):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "`s name is " + pet_name.title() + ".")
describe_pet("willie")
6.2.4、等效的函数调用
应为存在多种函数实参传递方式,所以对于同一个函数的相同结果,可以有多重实参传递情况。
所以在编写代码时,要灵活处理,同时也要尽量避免实参调用错误。
6.3、返回值
在函数中,可使用return语将值返回到调用函数的代码行。
6.3.1、返回简单值
def get_formatted_name(first_name, last_name):
full_name = first_name + " " + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
6.3.2、让实参变成可选
实际场景中,有些形参属于额外信息,可以填或者不填,因此使用默认值,来让实参变成可选的
def get_formatted_name(first_name, last_name, middle_name=''):
# generate full name
full_name = first_name + " " + middle_name + " " + last_name
return full_name.title()
musician = get_formatted_name("john", "lee", "hooker")
print(musician)
6.3.3、返回字典
函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。
def build_person(first_name, last_name):
# return dictionary which inclouds the basic information of person
person = {'first_name': first_name, 'last_name': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
6.3.4、结合使用函数和while循环
def get_formatted_name(first_name, last_name):
# generate full name
full_name = 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("\nHello, " + formatted_name + "!")
6.4、传递列表
向函数传递列表很有用,这种列表包含的可能是名字,数字或者更复杂的对象(如字典)。将列表传递给函数后,函数就能直接访问其内容。
def greet_users(names):
# greet every user in the list
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
6.4.1、在函数中修改列表
将列表传递给函数之后,函数就可以对列表进行修改,任何修改都是永久性的
def print_models(unprinted_designs, completed_models):
# print models
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing model: " + current_design)
completed_models.append(current_design)
def show_completed_models(completed_models):
# show all the models printed
print("\nThe following models have been printed:")
for model in completed_models:
print(model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
6.4.2、禁止函数修改列表
要是函数不能修改原有列表,可以在调用时使用name[:]
将列表的副本传递给函数
# 调用函数时,使用副本传递
func_name(list_name[:])
print_models(unprcompleted_models, completed_models)
6.5、传递任意数量的实参
预先不知道函数需要接受多少个实参,python允许函数从调用语句中收集任意数量的实参
可以使用*var_name
来接受任意数量的实参
def make_pizza(*toppings):
# print all the toppings of pizza
for topping in toppings:
print(topping)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
6.5.1、结合位置使用实参和任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意实参的形参放在最后。Python西安配置位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
def make_pizza(size, *toppings):
# introduce the pizza being made
print("\nMake a " + str(size) + '-inch pizza with the following toppings: ')
for topping in toppings:
print("- " + topping)
make_pizza(16, "pepperoni")
make_pizza(12, 'mushrooms', 'green peppers')
6.5.2、使用任意数量的关键字实参
有时候,需要接受任意数量的实参,但是预先不知道传递给函数的会是什么信息,可将函数编写成能够接受任意数量的键-值对。
如下:**user_info
的两个星号让Python创建一个名为user_info的空字典,并将收到是的所有名称-值对都封装到这个字典中。
def build_profile(first, last, **user_info):
# generate a dictionary which inclouds the info we know
profile = {'first_name': first, 'last_name': last}
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
6.6、将函数存储在模块中
函数的优点之一,就是他们可将代码与主程序分离,通过给函数制定描述性名称,可让主程序容易理解得多。还可以更进一步,将函数存储在被称为模块的独立文件中,在通过import
关键字导入,在主程序中使用它们。
6.6.1、导入整个模块
要让函数可导入,首先要创建模块。模块是扩展名为.py
的文件,包含要导入到程序中的代码。
# pizza.py
def make_pizza(size, *toppings):
# describe the pizza will be made
print("\nMake a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
# making_pizzas.py
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
6.6.2、导入特定函数
还可以导入模块中的特定函数
# from module_name import function_0, function_1, function_2
# eg.
from pizza import make_pizza
6.6.3、使用as给函数指定别名
导入的函数名可能与程序中现有的名称冲突,或名称太长,可以制定简短的独一无二的别名。
from pizza import make_pizza as mp
mp(16, 'peppeironi')
6.6.4、使用as给模块指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
6.6.5、导入模块中的所有函数
使用*运算符可让Python导入模块中的所有函数, 让Python将模块中的所有函数都复制到这个程序文件中,由于导入了每个函数,因此可以直接通过名称来调用每个函数,而无需使用句点表示法。
但是要慎用这种方法,因为不同模块中可能有同名函数,可能导致错误。
from pizza import *
make_pizza(16, 'pepperoni')
网友评论