1、定义函数:关键字def用来告诉python你要定义一个函数。函数后面所有的缩进构成了函数体。要调用函数,可依次指定函数名以及用括号括起的必要信息。
def greet_user():#函数定义,向Python指出函数名,还可能在括号内指出函数为完成其任务需要什么样的信息
#最后定义以冒号结尾
#显示简单的问候语
print("hello!")
greet_user()
1.1 向函数传递信息
def great_user(username):
print("Hello, "+username.title() + "!")
great_user('jesse')
1.2 实参和形参
在上面的函数great_user()的定义中,变量username是一个形参——函数完成其工作所需的一项信息。在大马great_user('jesse')中,值'jesse'是一个实参。实参是调用函数时传递给函数的信息。我们调用函数时,要让函数使用的信息放在括号内。
2、传递实参
2.1 位置实参:调用函数时,Python必须将函数调用的每一个实参都关联到函数定义中的一个形参。为此最简单的关联方式是基于实参的顺序。这种关联方式被称为位置实参。(利用位置实参来调用函数时,如果实参的位置不正确,结果可能出乎意料)
def describe_pet(animal_type,pet_name):
#显示宠物信息
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "`s name is " + pet_name.title() + ".")
describe_pet('hamster','harry')
2.2 关键字实参:关键字实参是传递给函数的名称-值对。直接在实参中将名称和值关联起来了。因此向函数传递实参时不会混淆。关键字实参让你无需考虑函数调用中的实参顺序,还清楚地指出了函数调用中各个值的用途。
def describe_pet(animal_type,pet_name):
#显示宠物信息
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "`s name is " + pet_name.title() + ".")
describe_pet(animal_type = 'hamster',pet_name = 'harry')
2.3 默认值:编写函数时,可给每个形参指定默认值。在调用函数中给形参提供了实参时,Python将使用指定的实参值:否则,将使用形参的默认值。(注意实参的位置Python依然将这个实参视为位置实参,因此如果函数调用只包含宠物的名字,这个实参将关联到函数定义中的第一个形参。这就是需要将pet_name放在形参列表开头的原因所在)
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(pet_name = 'willie')
2.4 等效的函数调用
使用哪种调用方式无关紧要,只要函数调用能生成你希望的输出就行。
def describe_pet(pet_name,animal_type = 'dog'):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "`s name is " + pet_name.title() + ".")
#一条名为willie的小狗
describe_pet('willie')
describe_pet(pet_name = 'willie')
#一只名为Harry的仓鼠
describe_pet('harry','hamster')
describe_pet(pet_name = 'harry',animal_type = 'hamster')
describe_pet(animal_type = 'hamster',pet_name = 'harry')
3 返回值:调用返回值的函数时,需要提供一个变量,用于存储返回的值
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)
3.1 返回字典:函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构
def build_person(first_name,last_name):#这个函数接受简单的文本信息,将其放在一个更合适的数据结构中
#返回一个字典,包含一个人的信息
person = {'first':first_name,'last':last_name}#函数接受名和姓,并将这些值封装到字典中
return person
musician = build_person('jimi','hendrix')
print(musician)
4 传递列表:向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象。将列表传递给函数后,函数就能直接访问其内容
def greet_users(names):
for name in names:
msg = "Hello," + name.title() + "!"
print(msg)
usernames = ['hannah','ty','margot']
greet_users(usernames)
5、传递任意数量的实参:预先不知道函数需要接受多少个实参
def make_pizza(*toppings):#形参名*toppings中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','green peppers','extra cheese')
#函数体内的print语句通过生成输出证明Python能够处理使用一个值调用函数的情形,也能处理使用三个值来调用函数的情形
#它以类似的方式处理不同的调用。注意:Python将实参封装到一个元组中,即便函数只收到一个值也如此