目录
8.1 定义
def greet_user():
"""Simple message"""
print('Hello')
greet_user()
def为函数定义关键字,后跟函数名及括号,括号内可为空
""" """:文档字符串的注释
1.传递信息
def greet_user(username):
"""Simple message"""
print('Hello, '+username.title())
greet_user('james')
可在函数名的括号内添加需要传递的信息
2.实参和形参
针对上面这个例程的定义中,变量username是形参,是函数完成工作所需的一项信息;而给定的james为实参,是调用函数时传递给函数的信息
8.2 传递实参
传递实参的方式有很多种,包括:要求顺序与形参相同的位置实参;关键字实参,由变量名和值组成;还可使用列表和字典。
1.位置实参
每个实参与形参顺序一一对应:
def describe_pet(animal_type,pet_name):
print("\n I have a "+animal_type+" .")
print("my pet's name is "+pet_name)
describe_pet('keji','pao')
#I have a keji
#my pet's name is pao
可以多次调用函数
def describe_pet(animal_type,pet_name):
print("\n I have a "+animal_type+" .")
print("my pet's name is "+pet_name)
describe_pet('dog','pao')
describe_pet('horse','niko')
2.关键字实参
def describe_pet(animal_type,pet_name):
print("\n I have a "+animal_type+" .")
print("my pet's name is "+pet_name)
describe_pet(animal_type='dog',pet_name='pao')
使用关键字实参不易混淆实参与形参,可以在函数引用中随意调换关键字实参的顺序
3.默认值
可以给形参指定默认值,只有当调用函数时使用了实参,才将指定实参值
def describe_pet(pet_name,animal_type='dog'):
print("\n I have a "+animal_type+" .")
print("my pet's name is "+pet_name)
describe_pet(pet_name='pao')
4.等效函数调用
以下函数调用方式均等效
def describe_pet(pet_name,animal_type='dog'):
print("\n I have a "+animal_type+" .")
print("my pet's name is "+pet_name)
describe_pet('pao')
describe_pet(pet_name='pao')
describe_pet('harry','cat')
describe_pet(pet_name='harry',animal_type='cat')
describe_pet(animal_type='cat',pet_name='harry')
5.避免实参错误
若只有型参数与实参数不符时,会产生实参不匹配错误
def describe_pet(pet_name,animal_type='dog'):
print("\n I have a "+animal_type+" .")
print("my pet's name is "+pet_name)
describe_pet()
Traceback (most recent call last):
File "D:\python_work\hello world2.py", line 5, in <module>
describe_pet()
TypeError: describe_pet() missing 1 required positional argument: 'pet_name'
8.3 返回值
函数返回的值即返回值,可使用return语句将值返回至调用函数的代码行
1.返回简单值
def get_name(first_name,last_name):
full_name=first_name+' '+last_name
return full_name
people=get_name('lebron','james')
print(people)
调用返回值的函数时,需要提供变量
2.可选实参值
使用默认值让实参变成可选的
def get_name(first_name,middle_name,last_name):
full_name=first_name+' '+middle_name+' '+ last_name
return full_name
people=get_name('lebron','raymone','james')
print(people)
上述代码可以提供一个人的全名,但并非所有人都有中间命
def get_name(first_name,last_name,middle_name=' '):
if middle_name: #非空为True
full_name=first_name+' '+middle_name+' '+ last_name
else:
full_name=first_name+' '+last_name
return full_name
people=get_name('lebron','raymone','james')
print(people)
people=get_name('lebron','james')
print(people)
中间名此时变成了可选的
3.返回字典
函数可返回任意类型的值,包括列表与字典
def build_person(first_name,last_name):
person={'first':first_name,'last':last_name}
return person
people=build_person('lebron','james')
print(people)
4.函数与while循环
def get_name(first_name,last_name):
full_name=first_name+' '+last_name
return full_name
while True:
f_name=input("first name: ")
l_name=input("last name: ")
people=get_name(f_name,l_name)
print(people)
8.4 传递列表
def greet_users(names):
for name in names:
msg="hello, "+name
print(msg)
usernames=['james','curry','kobe']
greet_users(usernames)
1.修改列表
未使用函数修改列表时
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing model: " + current_design)
completed_models.append(current_design)
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
使用函数后
def print_models(unprinted_designs,completed_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):
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs,completed_models )
show_completed_models(completed_models)
2.禁止修改列表
使用切片法,保留原列表
print_models(unprinted_designs[:],completed_models )
8.5 传递任意数量实参
def make_pizza(*toppings):
print(toppings)
make_pizza('tomato')
make_pizza('mushroom','cheese')
*使创建一个空元组。将接收到的值存入该元组中
1.结合使用位置与任意数量实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中
2.使用任意数量的关键字实参
def build_profile(first,last,**user_info):
profile={}
profile['first_name']=first
profile['last_name']=last
for key,value in user_info.items():
profile[key]=value
return profile
user_profile=build_profile('a','b',location='london',field='math')
print(user_profile)
**创建一空字典,将接收到的键-值对存入字典中。
8.6 将函数存储在模块中
可将函数存储在名为模块的文件中
1.导入模块
def make_pizza(size,*toppings):
print("making a "+str(size)+"-inch pizza with the following toppings:")
for topping in toppings:
print("- "+topping)
将以上函数导入
import pizza
pizza.make_pizza(16,'tomato')
pizza.make_pizza(18,'mushroom','cheese')
2.导入特定函数
from pizza import make_pizza
3.使用as给函数指定别名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
4.使用as给模块指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
5.导入模块中所有函数
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
作业
1.编写一个名为display_message() 的函数,它打印一个句子,指出你在本章学的是什么。调用这个函数,确认显示的消息正确无误。
def display_message():
print("In this chapter I learned about functions")
display_message()
2.编写一个名为favorite_book() 的函数,其中包含一个名为title 的形参。这个函数打印一条消息 。调用这个函数,并将一本图书的名称作为实参传递给它。
def favorite_book(title):
print("one of my favorite books is "+title)
favorite_book('older and sea')
3.编写一个名为make_shirt() 的函数,它接受一个尺码以及要印到T恤上的字样。这个函数应打印一个句子,概要地说明T恤的尺码和字样。使用位置实参调用这个函数来制作一件T恤;再使用关键字实参来调用这个函数。
def make_shirt(size,word):
print("this shirt size is "+size+" inch.and printed with the words:"+word)
make_shirt('6','just do it')
make_shirt(word='just do it',size='6')
4.修改函数make_shirt() ,使其在默认情况下制作一件印有字样“I love Python”的大号T恤。调用这个函数来制作如下T恤:一件印有默认字样的大号T恤、一件印有默认字样的中号T恤和一件印有其他字样的T恤(尺码无关紧要)。
def make_shirt(size,word='I love python'):
print("this shirt size is "+size+".and printed with the words:"+word)
make_shirt('big size')
make_shirt('middle size')
make_shirt(word='just do it',size='middle size')
5.编写一个名为describe_city() 的函数,它接受一座城市的名字以及该城市所属的国家。这个函数应打印一个简单的句子。给用于存储国家的形参指定默认值。为三座不同的城市调用这个函数,且其中至少有一座城市不属于默认国家。
def describe_city(name,country='china'):
print(name+" is in "+country)
describe_city('beijing')
describe_city('shanghai')
describe_city('longdon','U.K')
6.编写一个名为city_country() 的函数,它接受城市的名称及其所属的国家。
def city_country(name,country):
name_country=name+" , "+country
print(name_country)
city_country('santiago','chile')
7.编写一个名为make_album() 的函数,它创建一个描述音乐专辑的字典。这个函数应接受歌手的名字和专辑名,并返回一个包含这两项信息的字典。使用这个函数创建三个表示不同专辑的字典,并打印每个返回的值,以核实字典正确地存储了专辑的信息。给函数make_album() 添加一个可选形参,以便能够存储专辑包含的歌曲数。如果调用这个函数时指定了歌曲数,就将这个值添加到表示专辑的字典中。调用这个函数,并至少在一次调用中指定专辑包含的歌曲数。
def make_album(singer_name,album_name):
album={'singer_name':singer_name,'album_name':album_name}
print(album)
make_album('Jay Chou','Fantasy')
make_album('Jay Chou','Qi Li Xiang')
make_album('Jj Lin','jiangnan')
def make_album(singer_name,album_name,songs_number=''):
album_0={'singer_name':singer_name,'album_name':album_name,'songs_number':songs_number}
album_1={'singer_name':singer_name,'album_name':album_name}
if songs_number:
print(album_0)
else:
print(album_1)
make_album('Jay Chou','Fantasy','10')
make_album('Jay Chou','Qi Li Xiang','10')
make_album('Jj Lin','jiangnan')
8. 编写一个while 循环,让用户输入一个专辑的歌手和名称。获取这些信息后,使用它们来调用函
def make_album(singer_name,album_name,songs_number=''):
album_0={'singer_name':singer_name,'album_name':album_name,'songs_number':songs_number}
album_1={'singer_name':singer_name,'album_name':album_name}
if songs_number:
print(album_0)
else:
print(album_1)
active=True
while active:
singer_name=input('singer:')
if singer_name=='quit':
break
else:
album_name=input('album:')
make_album(singer_name,album_name)
9.创建一个包含魔术师名字的列表,并将其传递给一个名为show_magicians() 的函数,这个函数打印列表中每个魔术师的名字。
def show_magicians(names):
for name in names:
print(name)
magicians_name=['joly','cord','pete']
show_magicians(magicians_name)
10.编写一个名为make_great() 的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the Great”。调用函数show_magicians() ,确认魔术师列表确实变了。
magicians_name=['joly','cord','pete']
finished_name=[]
def make_great(magicians_name,finished_name):
while magicians_name:
unfinished_name=magicians_name.pop()
uf_name='the great '+unfinished_name
finished_name.append(uf_name)
def show_magicians(finished_name):
for name in finished_name:
print(name)
make_great(magicians_name,finished_name)
show_magicians(finished_name)
11.修改你为完成练习8-10而编写的程序,在调用函数make_great() 时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调用show_magicians() ,确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the Great”的魔术师名字。
magicians_name=['joly','cord','pete']
finished_name=[]
def make_great(magicians_name,finished_name):
while magicians_name:
unfinished_name=magicians_name.pop()
uf_name='the great '+unfinished_name
finished_name.append(uf_name)
def show_magicians(finished_name):
for name in finished_name:
print(name)
make_great(magicians_name[:],finished_name)
show_magicians(finished_name)
show_magicians(magicians_name)
12.编写一个函数,它接受顾客要在三明治中添加的一系列食材。这个函数只有一个形参(它收集函数调用中提供的所有食材),并打印一条消息,对顾客点的三明治进行概述。调用这个函数三次,每次都提供不同数量的实参。
def foods(*toppings):
for topping in toppings:
print(topping)
print("\n")
foods('tomato','mushroom','potato')
foods('tomato')
foods('tomato','ice')
13.复制前面的程序user_profile.py,在其中调用build_profile() 来创建有关你的简介;调用这个函数时,指定你的名和姓,以及三个描述你的键-值对。
def build_profile(name,**user_info):
profile = {}
profile['name'] = name
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('tyz',location='china', field='python',hobby='basketball')
print(user_profile)
14.编写一个函数,将一辆汽车的信息存储在一个字典中。这个函数总是接受制造商和型号,还接受任意数量的关键字实参。这样调用这个函数:提供必不可少的信息,以及两个名称—值对,如颜色和选装配件。
def make_car(band,model,**car_info):
car={}
car['band']=band
car['type']=model
for key,value in car_info.items():
car[key]=value
return car
car=make_car('sabaru','outback',color='black',age='3')
print(car)
16.选择一个你编写的且只包含一个函数的程序,并将这个函数放在另一个文件中。
源代码
def make_car(band,model,**car_info):
car={}
car['band']=band
car['type']=model
for key,value in car_info.items():
car[key]=value
print(car)
导入方式1:整体模块
import make
make.make_car('sabaru','outback',color='black',age='3')
导入方式2:模块中部分函数
from make import make_car
make_car('sabaru','outback',color='black',age='3')
导入方式3:利用as将函数指定别名
from make import make_car as mc
mc('sabaru','outback',color='black',age='3')
导入方式4:利用as将模块指定别名
import make as m
m.make_car('sabaru','outback',color='black',age='3')
导入方式5:利用*导入模块中所有函数
from make import *
make_car('sabaru','outback',color='black',age='3')