记忆关键点:看目录即可记住
一、定义函数
def greet_user():
"""显示简单的问候语"""
print("hello!")
greet_user()
def greet_user():
"""显示简单的问候语"""
print("hello!")
greet_user()
def greet_user(username):
"""显示简单的问候语"""
print("hello!",username)
greet_user("bob")
注意实参,形参,函数开头用define,冒号的使用
二、传递实参
1、位置实参
要求实参的位置与形参相同
def show_mypets(name,varition):
print(f"my pet's name is {name},it is a {varition}")
show_mypets("xinxin","my_wife")
实参按对应顺序传递给形参后,在函数体内执行
def show_mypets(name,varition):
print(f"my pet's name is {name},it is a {varition}")
show_mypets("xinxin","my_wife")
show_mypets("dd",'dog')#多次调用函数
2、关键字实参
无需考虑实参顺序,清楚地指明了函数调用中各个值得用途
def show_mypets(name,varition):
print(f"my pet's name is {name},it is a {varition}")
show_mypets("xinxin","my_wife")
show_mypets(varition='dog',name="dd")
3、默认值
实参或者形参有默认值了,那么只需要给没有默认值得形参进行实参传递
def show_mypets(name="ggg",varition):
print(f"my pet's name is {name},it is a {varition}")
show_mypets(varition='dog')#默认为位置实参,发生错误
def show_mypets(name,varition="dog"):
print(f"my pet's name is {name},it is a {varition}")
show_mypets(name="dsds")
def show_mypets(name,varition="dog"):
print(f"my pet's name is {name},it is a {varition}")
show_mypets(name="dsds",varition="cat")#覆盖形参中得原来的赋值
4、等效的函数调用
就是综合位置实参和关键字实参的应用
def show_mypets(name,varition="dog"):
print(f"my pet's name is {name},it is a {varition}")
show_mypets(name="dsds",varition="cat")#关键字实参
show_mypets("dsds",varition="cat")#位置实参
show_mypets(varition="cat",name="dsds")#关键字实参
show_mypets(name="dsds")#位置实参
show_mypets("dsds")#位置实参
show_mypets("dsds","dog")#位置实参
三、返回值
1、返回简单的值
def full_name(first_name,last_name):
full_name=f"{first_name}{last_name}"
return full_name
message=full_name("lai","xiangtiai")
print(message)
2、让实参变成可选的
def full_name(first_name,last_name,middle_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()
message1=full_name("lai","li")
print(message1)
message2=full_name("lai",'hhh',"li")
print(message2)
3、返回字典
函数可以返回任何类型的值,包括列表字典等较为复杂的数据结构
def my_name(first_name,last_name):#返回一个人的信息的字典
name={"first":first_name,"last":last_name}
return name
myname=my_name("bob","son")
print(myname)
def my_name_age(first_name,last_name,age):#返回一个人的信息的字典
name={"first":first_name,"last":last_name}
if age:
name["age"]=age#追加到后面
return name
myname_age=my_name_age("bob","son",27)
print(myname_age)
4、结合使用函数和while循环
使用用户名和姓给用户无限循环地打招呼
def my_name(first_name,last_name):#返回一个人的信息的字典
full_name=f"{first_name} {last_name}"
return full_name
while True:
print("tell me your name?")
f_name=input("first name:")
l_name=input("last name:")
full_name=my_name(f_name,l_name)
print(f"hello,{full_name}")
用break设置退出条件
def my_name(first_name,last_name):#返回一个人的信息的字典
full_name=f"{first_name} {last_name}"
return full_name
while True:
print("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
full_name=my_name(f_name,l_name)
print(f"hello,{full_name}")
5、传递列表
def greet_users(names):
for name in names:
print(f"hello,{name.title()}")
names=["zhang",'bob','david']#给列表中的每个人打招呼
greet_users(names)
在函数中修改列表
#首先创建一个列表,其中包含一些要打印的数据
unprinted_designs=['phone case','robot','data']#未打印的设计
completed_models=[]#完成的设计
#模拟打印所有设计
#打印设计后,移到列表completed_models中
while unprinted_designs:
current_design=unprinted_designs.pop()#每次从列表中最后一个设计打印
print(f"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(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','data']#未打印的设计
completed_models=[]#完成的设计
print_models(unprinted_designs,comple
有函数的版本程序更容易拓展和维护,将复杂的任务分解成一系列步骤
禁止函数修改列表
传递列表的副本,让原列表保留
def print_models(unprinted_designs,completed_models):
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','data']#未打印的设计
completed_models=[]#完成的设计
print_models(unprinted_designs[:],completed_models)#unprinted_designs[:]复制列表
show_completed_models(completed_models)
print(unprinted_designs)
6、任意传递数量的实参
def make_pizza(*toppings):
"""打印顾客所点的所有配料"""
print(toppings)
make_pizza("gousi")
make_pizza('sssxs')
make_pizza('ss','sb','sd','sl')
kk=["jo",'dd']
make_pizza(kk)
ll={'ss','xas'}#括号里面是啥就传递啥,打印出来也就是括号里的内容,
#且都是单引号,如果只有一个字符串,打印出来还有个逗号在尾部
make_pizza(ll)
def make_pizza(*toppings):
"""打印顾客所点的所有配料"""
for jj in toppings:
print(jj)
make_pizza('ss','sb','sd','sl')
这里的*toppping中的星号让python创建一个名为topping的元组,该元组包含函数收到的所有值。上面代码里就包含了四个值。无论函数收到多少个实参,这种语法都管用。
结合使用位置实参+任意数量的实参
位置实参必须放前面,一一对应,任意数量的实参会被打包起来对应一个形参
def make_pizza(size,flavor,*toppings):
"""概述要制作的披萨"""
print(f"making a {flavor} {size}_inch "
f"pizza with the following topping:")
for topping in toppings:
print(f"-{topping}")
make_pizza(24,'sweet','sb','sd','sl')
使用任意数量的关键字实参
def build_profile(first,last,**user_info):#两个星号是创建名为user_info
#的字典,该字典包含函数收到的所有键值对
"""创建一个字典,里面包含我们想知道的用户的一切"""
user_info["first_name"]=first#键值对
user_info["lat_name"]=last
return user_info
user_pofile=build_profile('bob','einstein',
location="china",father="notme")
#location和father两个键值对,前面两个是位置实参,**user_info是代表所有的
#*user_info,这样将两个键值对放入字典里,思考为什么是在前面?因为先入字典
print(user_pofile)
任意数量的实参+位置实参+关键字实参组合成实参
7、将函数存储在模块中
导入整个模块
test,py为我们要编辑的主文件,function文件为放函数的文件,注意:两文件必须要在统一文件最小子目录下,否则无法调用
import function#test.py文件代码
function.make_pizza(24,"sweet","hao","kkk","bu","le")#注意调用的写法
def make_pizza(size,flavor,*toppings):#function.py文件代码
"""概述要制作的披萨"""
print(f"making a {flavor} {size}_inch "
f"pizza with the following topping:")
for topping in toppings:
print(f"-{topping}")
导入特定的函数
#function.py文件代码
def make_pizza(size,flavor,*toppings):
"""概述要制作的披萨"""
print(f"making a {flavor} {size}_inch "
f"pizza with the following topping:")
for topping in toppings:
print(f"-{topping}")
def yourname(first_name,last_name):
full_name=f"{first_name}{last_name}"
print(full_name)
def yourwife(when,where,name):
print(f"your wife——{name} call you that"
f" she will kiss you at {where} in {when}")
from function import make_pizza #test.py文件代码
from function import make_pizza,yourname,yourwife#传入多个函数
make_pizza("25","salty","gousi")
yourwife(2022,"your dream",'jiangyuanxin')
yourname("lxt","hao")
使用as给函数指定别名
from function import make_pizza as m_p#用as ...取别名
#原来的名称就用不了了
m_p(25,"salty","gousi")
使用as给模块指定别名
import function as func
from function import make_pizza as m_p#这里只能用原名
m_p(25,"salty","gousi")
func.make_pizza(205,"salty","gous2i")#这里只能用别名
导入模块中的所有函数
使用*符可让python导入模块中的所有函数
from function import *
yourwife(22,12,22)#平时还是要用function.yourwife比较好,因为可能函数名重复
yourname(1,1)
make_pizza(2,5,8,9,7,5)
8、函数编写指南
- 函数名是描述性名称,只使用小写字母和下划线
- 每个函数都有描述其功能的注释,写在函数定义后面,采用文档字符串
- 形参指定默认值时,两边不要用空格
def function(wo=kk,ni)
- PEP8建议代码行的长度不超过79个字符,如果长了,缩进并分行
def make_pizza(
size,flavor,
*toppings):
- 程序或者模块包含多个函数,使用两个空行将相邻的函数分开
def yourname(first_name,last_name):
full_name=f"{first_name}{last_name}"
print(full_name)
def yourwife(when,where,name):
print(f"your wife——{name} call you that"
f" she will kiss you at {where} in {when}")
- 所有的import语句放在文件开头,除了注释放开头的情况