关键字def定义函数Python必须将函数调用中的每个实参度关联到函数定义中的一个形参调用函数多次时,Python按顺序将函数调用中的参数关联到函数定义中相应的形参位置参数的顺序很重要,使用关键字实参时务必准确指定函数定义中的形参名在调用函数中给形参提供了实参时,Python将使用指定的实参值,否则使用默认值使用默认值,在形参列表中必须现列出没有默认值的形参,再列出有默认值的实参return语句将值返回到调用函数的代码行python允许函数从调用语句中收集任意数量的实参若要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量的实参放在最后Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中】*toping 创建一个名为toping元祖**name 创建一个名为name字典import语句允许在当前运行的程序文件中使用模块中的代码关键字as将函数重命名为你提供的别名
课本例子
定义函数
===========================================================
def greet_user(username):#用关键字def定义函数
# """显示简单的问候语"""
# print("hello!")
"""向函数传递信息"""
print ("Hello, "+username.title()+"!")
greet_user('jesse')#调用该函数 username为形参,'jesse'为实参
"""位置实参"""
#位置实参的位置很重要
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')
"""调用函数多次"""
describe_pet('dog','willie')
"""关键字实参"""
describe_pet(animal_type='hamster',pet_name='harry')
"""默认值"""
#使用默认值时,在形参列表中必须先列出没有默认值的形参,在列出有默认值的实参
def describe_pet2(pet_name,animal_type='dog'):
"""显示宠物信息"""
print ("\nI have a " + animal_type + ".")
print ("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet2(pet_name='willie')
def greet_user(username):#用关键字def定义函数
# """显示简单的问候语"""
# print("hello!")
"""向函数传递信息"""
print ("Hello, "+username.title()+"!")
greet_user('jesse')#调用该函数 username为形参,'jesse'为实参
"""位置实参"""
#位置实参的位置很重要
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')
"""调用函数多次"""
describe_pet('dog','willie')
"""关键字实参"""
describe_pet(animal_type='hamster',pet_name='harry')
"""默认值"""
#使用默认值时,在形参列表中必须先列出没有默认值的形参,在列出有默认值的实参
def describe_pet2(pet_name,animal_type='dog'):
"""显示宠物信息"""
print ("\nI have a " + animal_type + ".")
print ("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet2(pet_name='willie')
"""等效的函数调用"""
#一条名为whiilie的小狗
describe_pet2('willie')
describe_pet2(pet_name='willie')
===========================================================
Hello, Jesse!
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
Hello, Jesse!
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
I have a hamster.
My hamster's name is Harry.
I have a dog.
My dog's name is Willie.
I have a dog.
My dog's name is Willie.
I have a dog.
My dog's name is Willie.
返回值
# # def get_formatted_name(first_name,last_name):#函数gget_formatted_name()的英译通过形参接受姓和名
# # """返回整洁的名字"""
# # full_name = first_name+' '+last_name
# # return full_name.title()#full_name的值首字母大写,并将结果返回到函数调用行
# #
# # musician = get_formatted_name('jimi','hendrix')#将函数返回值存储在musician变量中
# # print (musician)
#
# """将实参编程可选的"""
# def get_formatted_name(first_name,last_name,middle_name=''):
# #返回整洁的名字
# if middle_name:
# full_name = first_name +' '+middle_name+' '+last_name
# else:
# full_name = 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)
"""返回字典"""
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'}
结合使用函数和while循环
def get_formatted_name(first_name,last_name):
"""返回整洁的姓名"""
full_name = first_name+' ' +last_name
return full_name.title()
while True:#while循环让用户输入姓名:依次提示用户输入姓和名
print ("\nPlease tell me your name: ")
print ("(enter 'q' at any time to quit)")
f_name = input("Frist name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
fromatted_name = get_formatted_name(f_name,l_name)#调用函数,并将返回值传给形参
print ("\nHello, "+fromatted_name+"!")
===========================================================
F:\python37\python.exe G:/code/book_1/chapter8/greeter2.py
Please tell me your name:
(enter 'q' at any time to quit)
Frist name: ercie
Last name: maths
Hello, Ercie Maths!
Please tell me your name:
(enter 'q' at any time to quit)
Frist name: q
进程已结束,退出代码 0
传递列表
"""将一个名字列表传递给一个函数,这个函数问候列表中的每个人"""
def greet_users(names):#函数greet_users()接受一个名字列表,并将其存储在形参name中
"""向列表中的每位用户度发出简单的问候"""
for name in names:
msg ="Hello, "+name.title()+"!"
print(msg)
username = ['hannah','try','margot']#用户列表
greet_users(username)
===========================================================
Hello, Hannah!
Hello, Try!
Hello, Margot!
在函数中修改列表
"""一家为用户提交的设计制作3D打印模型的公司,需要打印的设计存储在一个列表中"""
"""打印后移到另一个列表中"""
#首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case','robat pendant','dodecahedron']
completede_models =[]
#模拟打印每个设计,直到没有未打印的设计为止
#打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
current_design = unprinted_designs.pop()#方法pop()弹出列表末尾元素
#模拟根据设计制作3D打印模型的过程
print("Printing model:"+current_design)
completede_models.append(current_design)#方法append()添加元素至列表末尾
#显示打印好的所有模型
print("\nThe following models have been printed: ")
for completede_model in completede_models:
print(completede_model)
===========================================================
Printing model:dodecahedron
Printing model:robat pendant
Printing model:iphone case
The following models have been printed:
dodecahedron
robat pendant
iphone case
"""重组pringting_models代码(编写两个函数)"""
def print_models(unprinted_designs,complete_models):
"""
模拟打印每个设计,直到没有未打印的设计为止
打印每个设计后,都将其移到列表completed_models中
"""
while unprinted_designs:#将设计逐个从未打印好的列表中去除,并加到打印好的模型列表中
current_design = unprinted_designs.pop()
#模拟根据设计制作3D打印模型的过程
print("Printing model: "+current_design)
complete_models.append(current_design)
def show_completed_models(complete_models):
"""显示打印好的所有模型"""
print("\nTHe following models have been printed: ")
for complete_model in complete_models:
print(complete_model)
unprinted_designs = ['iphone case','robat pendant','dodecahedron']
completede_models =[]#创建空列表存储打印好的模型
print_models(unprinted_designs,completede_models)#调用函数,并传递两个列表,模拟打印设计的过程
show_completed_models(completede_models)#调用函数,显示打印好的所有模型
"""解决禁止修改列表问题,切片表示法创建副本"""
# function_namew(list_name[:])
print_models(unprinted_designs[:],completede_models)
===========================================================
Printing model: dodecahedron
Printing model: robat pendant
Printing model: iphone case
THe following models have been printed:
dodecahedron
robat pendant
iphone case
传递任意数量的实参
def make_pizza(*toppings):#形参*toppings中的星号让python创建一个名为toppings的空元祖,并将收到的所有值都装到这个元祖中
# """打印顾客电的所有配料"""
# print(toppings)#python将实参封装到一个元祖中
"""用for循环代替print语句,对配料列表进行遍历,并对顾客点的披萨进行描述"""
#概述要制作的披萨
print("\nMaking a pizza with the following toppings: ")
for topping in toppings:
print("-"+topping)
make_pizza('pepperoni')
make_pizza('mushroom','green peppers')
===========================================================
Making a pizza with the following toppings:
-pepperoni
Making a pizza with the following toppings:
-mushroom
-green peppers
结合使用位置实参和任意数量实参
def make_pizza(size,*toppings):#表示披萨尺寸的形参放在接纳任意数量实参的形参前
"""概述要制作的披萨"""
"""python将收到的第一个值存储在形参siza中,并将其他的所有值都存贮在元祖yopping中"""
print("\nMaking a "+str(size)+
"-inch pizza with the following toppings:")
for topping in toppings:
print("-"+topping)
"""在调用函数中,首先指定表示披萨尺寸的实现,然后根据需求指定任意数量的配料"""
make_pizza(16,'pepperoni')
make_pizza(12,'mushroom','green pepperas')
===========================================================
F:\python37\python.exe G:/code/book_1/chapter8/pizza2.py
Making a 16-inch pizza with the following toppings:
-pepperoni
Making a 12-inch pizza with the following toppings:
-mushroom
-green pepperas
进程已结束,退出代码 0
使用任意数量的关键字实参
def build_profile(first,last,**user_info):#两个星号让python创建一个user_info的空字典
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile ={}#创建一个空字典,用于存储用户的简介
profile['first_name'] = first#将名和姓都加入到这个字典中
profile['last_name'] = last
for key,value in user_info.items():#遍历字典user_info的键值对
profile[key] = value#将每个键-值都加到字典profile中
return profile#将字典peofile返回给函数调用行
#调用build_profile函数
#无论额外提供多少个键值对,都能正确处理
user_profile = build_profile('albert','einstein',
location = 'princetion',
field = 'physics')
print(user_profile)
===========================================================
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princetion', 'field': 'physics'}
将函数存储在模块中
导入整个模块
#导入整个模块:编写一条import语句并将在其中指定模块名
#导入名为module_name.py的整个模块
import module_name
#使用该模块中的任何一个函数
module_name.function_name()
导入特定的函数
for module_name import function_name
#根据需求从模块中导入任意数量的函数
#通过逗号分隔函数名
from module_name import function_0,function_1
from pizza import make_pizza
make_pizza(12,'a')
make_piza(10,'a','b','c')
通过as给函数指定别名
#指定别名语法
from module_name import function_name as fn
from pizza import make_pizza as mp
mp(12,'a')
m[(10,'a','b','c')
课后练习
def display_message():
"""显示本章所学内容"""
print("本章所学内容为函数")
display_message()
--------------------------------
本章所学内容为函数
def favorite_book(title):
""""显示喜欢的书"""
print("One of my favorite book is "+ title+ " .")
favorite_book('Alice in Wonderland')
--------------------------------------------------------------------
One of my favorite book is Alice in Wonderland .
`
def make_shirt(shirt_size,print_model):
""""制作T恤"""
print("\n I need make a T-shirt,as follows:")
print("T-shirt size is "+ str(shirt_size)+".")
print("T-shirt mode is "+ print_model+".")
make_shirt('small','lw')#位置实参数
make_shirt(shirt_size='small',print_model='lw')#关键字实参
---------------------------------------------------------------------
I need make a T-shirt,as follows:
T-shirt size is small.
T-shirt mode is lw.—
def make_shirt(shirt_size='L',print_model='I love Python'):
"""制作T-shirt"""
print("\nI need make a T_shirt,as follows:")
print("T-shirt size is " + str(shirt_size) + ".")
print("T-shirt mode is " + print_model + ".")
make_shirt()
make_shirt('M')
make_shirt(shirt_size='...',print_model='Hello Py!')
------------------------------------------------------------------
I need make a T_shirt,as follows:
T-shirt size is L.
T-shirt mode is I love Python.
I need make a T_shirt,as follows:
T-shirt size is M.
T-shirt mode is I love Python.
I need make a T_shirt,as follows:
T-shirt size is ....
T-shirt mode is Hello Py!.
def describe_city(city_name,blong_nation='iceland'):
print("\n"+city_name.title()+ " is in "+blong_nation.title())
describe_city('reykJavik')
describe_city('youk')
describe_city('beijing','china')
---------------------------------------------------------------------------
Reykjavik is in Iceland
Youk is in Iceland
Beijing is in China
def city_country(city_name,blong_nation):
""""返回城市的姓名以及所属的国家"""
city = '"'+city_name.title()+","+blong_nation.title()+'"'
return city
while True:
city_name = input("city name:")
nation_name = input("nation name:")
infro = city_country(city_name,nation_name)
print(infro+"\n")
----------------------------------------------------------------------
city name:santigo
nation name:chile
"Santigo,Chile"
city name:beijing
nation name:china
"Beijing,China"
def make_album(songer_name,album_name,song_num= ' '):
""""返回一个字典,包含歌手名和专辑名"""
album = {'songer name':songer_name,'album name':album_name}
if song_num:
album['song_num'] = song_num
return album
infor = make_album("a","A")
print(infor)
infor = make_album("b","B","2")
print(infor)
infor = make_album("c","C","3")
print(infor)
--------------------------------------------------------------------
{'songer name': 'a', 'album name': 'A', 'song_num': ' '}
{'songer name': 'b', 'album name': 'B', 'song_num': '2'}
{'songer name': 'c', 'album name': 'C', 'song_num': '3'}
def make_album(songer_name,album_name,song_num= ' '):
""""返回一个字典,包含歌手名和专辑名"""
album = {'songer name':songer_name,'album name':album_name}
if song_num:
album['song_num'] = song_num
return album
while True:
"""输出歌手的名字和专辑名"""
print("you could enter 'q' to quit his program")
singername = input("Enter singername: ")
if singername == 'q':
break
albumname = input("Enter albumname: ")
if albumname == 'q':
break
a1 = make_album(singername, albumname)
print(a1)
---------------------------------------------------------------
you could enter 'q' to quit his program
Enter singername: w
Enter albumname: ww
{'songer name': 'w', 'album name': 'ww', 'song_num': ' '}
you could enter 'q' to quit his program
Enter singername: q
def show_magicians(names):
for name in names:
print("\nMagician's name: "+ name.title())
magicians_name = ['w','jiali']
show_magicians(magicians_name)
--------------------------------------------------------
Magician's name: W
Magician's name: Jiali
def make_great(magicians,show):
for magic in magicians:
magic = "the Great "+ magic+"."
show.append(magic)
def show_magicians(show):
while show:
print(show.pop())
magicians = ['alice', 'david', 'carolina']
show = []
make_great(magicians,show)
show_magicians(show)
-----------------------------------------------------
the Great carolina.
the Great david.
the Great alice.
def make_great(magician3,showmag):
while magician3:
magic="the Great "+magician3.pop()
showmag.append(magic)
def show_magicians(magician3,showmag):
for show in showmag:
print(show)
for magician in magician3:
print(magician)
showmag=[]
magician3=['John','Jack','Jackson']
make_great(magician3[:],showmag)
show_magicians(magician3,showmag)
--------------------------------------------------------------
the Great Jackson
the Great Jack
the Great John
John
Jack
Jackson
def add_material(*materials):
for material in materials:
print("Adding: ",material)
add_material('1')
print("-------------------------------")
add_material('2','3')
print("-------------------------------")
add_material('4','5','6')
--------------------------------------------------------------
Adding: 1
-------------------------------
Adding: 2
Adding: 3
-------------------------------
Adding: 4
Adding: 5
Adding: 6
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['last_namer'] = last
for key,vaule in user_info.items():
profile[key] = vaule
return profile
user_profile = build_profile('W','Jonr',
location = 'JiangXi',
field = 'cs',
weather = 'sun')
print(user_profile)
-------------------------------------------------------------------
{'first_name': 'W', 'last_namer': 'Jonr', 'location': 'JiangXi', 'field': 'cs', 'weather': 'sun'}
def make_cars(producer,size,**carinfos):
cars = {}
cars['producer'] = producer
cars['size'] = size
for key , value in carinfos.items():
cars[key] = value
return cars
car = make_cars('subaru','outback',color = 'blue',tow_package = True)
print(car)
------------------------------------------------------------------
{'producer': 'subaru', 'size': 'outback', 'color': 'blue', 'tow_package': True}
"""print_models.py"""
from printing_functions import make_car
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)
"""printing_models.py"""
def make_car(producer,size,**carinfos):
cars={}
cars['producer']=producer
cars['size']=size
for key,value in carinfos.items():
cars[key]=value
------------------------------------------------
{'producer': 'subaru', 'size': 'outback', 'color': 'blue', 'two_package': True}