Creating and calling functions
Create function: def keyword
语法:
def functionname([parameterlist]):
['''comments''']
[functionbody]
#[parameterlist]:可选参数,用来向函数中传递参数,可以有多个参数使用逗号隔开
#['''comments''']:可选参数,用一对三引号括起来的多行注释,通常用来说明函数的功能和要传递的参数说明等等信息。
通过这个文档字符串可以自动生成在线文档或打印版的文档。通过:help(函数名)或函数名.__doc__显示。
#[functionbody]:可选参数,用来指定函数体的也就是功能代码
如果函数有返回值,就可以使用return进行返回
例1:
空函数:
def empty():
pass
例2:创建正则表达式分割函数
def filter(string):
'''
================
过滤============
================
'''
import re
pattern = r'[1a]'
plit = re.split(pattern,string)
print(plit)
filter("15032331123ayuikaieo")
filter?
Parameter passing
formal parameters and actual parameters
形式参数:在定义参数的时候放置的函数的参数为形式参数,例如: def demo(obj)中的obj
实际参数:调用函数时的函数的参数为实际参数
Pass-through and pass-by-reference
直传递:当实际参数为不可变对象时的参数传递,不改变形式参数的值
引用传递:当实际参数为可变对象时的参数传递,改变形式参数的值
例1:值传递
aa = "bac"
print(aa)
def ff(string):
string += string
print(string)
ff(aa)
print(aa)
调用函数前后aa的值不变
例2:引用传递
aa = "bac"
bb = list(aa)
print(bb)
def ff(string):
string += string
print(string)
ff(bb)
print(bb)
调用函数前后bb的值发生改变
Positional parameters
是必备参数,定义之后调用函数时必须给定定义的位置参数,位置参数多了或少了或位置不一致都会报错
例:
aa = ("xiaoming",2,5)
def nn(name,num1,num2):
print("name",num1+num2)
nn("xiaoming",2,5)
Keyword parameters: You can disrupt the order of parameters
例:
def nn(name,num1,num2):
print(name,num1+num2)
nn(num1=2,num2=5,name="xiaoming")
Set default values for parameters: When specifying default value parameters, they must be placed after all parameters
查看默认值:
print(nn.__defaults__)
例
def nn(num1,num2,name="xiaoming"):
print(name,num1+num2)
nn(2,5)
nn(2,5,"lisi")
当引用传递时,多次执行时默认值会随之改变,这是可以把默认值设置为None值
例1:默认值会随可变参数发生改变
def nn(name=[]):
print(name)
name.append(1)
nn()
nn()
例2:通过None值优化
def nn(name=None):
if name == None:
name=[]
print(name)
name.append(1)
nn()
nn()
variable parameter
*parameter:按位置进行传递可以接受任意多个实际参数,并把它们放到一个元组当中
例1:
def nn(*zimu):
for i in zimu:
print(i)
nn("a","b")
nn(1)
**arameter
例2:可以接受列表
list = ["a","b","c"]
def nn(*zimu):
print(zimu)
for i in zimu:
print(i)
nn(*list)
例3:参数为俩列表
def nn(*shuzi):
for sz in shuzi:
for i in sz:
num = i[0] + i[1]
print(num)
list1 = [[1,3],[3,9],[5,7]]
list2 = [[2,4],[6,8]]
nn(list1,list2)
**parameter: Passed by keyword, accepts multiple keyword parameters and puts them in a dictionary
例1:
def nl(**nianling):
print(nianling)
for key,value in nianling.items():
print("姓名:",key,"年龄:",value)
nl(xiaoming=18,lisi=22,wangwu=20)
例2:
def nl(**nianling):
for key,value in nianling.items():
print("姓名:",key,"年龄:",value)
dict1={'xiaoming':18,'lisi':22,'wangwu':20}
nl(**dict1)
return value
return
可以用return语句来指定函数返回值,指定的返回值可以是任意类型
可以返回多个值并使用逗号进行分割
如果没有返回值就会返回None值
无论return出现在函数的什么位置都会终止函数
如果不给函数指定返回值,也会返回一个None值
在调用函数时可以把返回值赋值给一个变量,如果返回值数量为一个,变量就保存这一个值;如果返回值数量为多个,变量则以元组形式把这些返回值进行保存
语法:return [value]
例:根据消费价格打折
def num(money):
money_old = sum(money)
if 500 < money_old <= 1000:
money_new='{:.2f}'.format(money_old*0.9)
elif 1000 < money_old <= 2000:
money_new = '{:.2f}'.format(money_old*0.8)
elif 2000 < money_old <= 3000:
money_new = '{:.2f}'.format(money_old*0.7)
elif 3000<money_old:
money_new = '{:.2f}'.format(money_old*0.6)
else:
money_new=money_old
return money_new,money_old
list=[]
while True:
mon = float(input("请输入价格(输入0表示输入完毕):"))
if mon == 0:
break
else:
list.append(mon)
mm = num(list)
print(mm)
variable scope
The scope of a variable: refers to the area in which the program code can access the variable. If it exceeds this area, an error will occur when accessing it again.
Local variables: refer to variables defined and used inside the function. NameErorr errors will be thrown outside the function.
例:
def name():
AA_1 = "名字" #定义局部变量
print(AA_1) #函数内部调用变量
name()
print(AA_1) #函数外部调用会报错
Global variables: variables that can be scoped inside and outside the function. Global variables cannot be changed within the function body. If they are changed, it is equivalent to defining a local variable within the function body.
例:
AA_1 = "名字A" #定义全局变量
def name():
print(AA_1)
name()
print(AA_1)
Define global variables within the function body using the global keyword
例:
def name():
global AA_1 #修饰为全局变量
AA_1 = "名字"
print(AA_1)
name()
print(AA_1)
anonymous function
Anonymous function: It is usually only used once in Python, so there is no need to name it. You can use lambda expressions to implement anonymous functions.
语法:输出一个lamdba对象
reslut = lamdba [arg1[,arg2,arg3,...,argn]]:expression
#arg:定义的参数会在后面表达式中被引用
#expression #在这个表达式中不能出现for或者while非表达式语句
例1
import math
r = 10
result = lambda r:math.pi*r*r
print(result(r))
例2:
bookinfo = [('不一样的卡梅拉(全套)',22.50,120),('零基础学Python',65.10,79.80),('摆渡人',23.40,36.00),('福尔摩斯探案全集8册',22.50,128)]
print('爬取到的商品信息:\n',bookinfo,'\n')
bookinfo.sort(key=lambda x:(x[1],x[1]/x[2])) # 按指定规则进行排序
#x:表示传入的列表中的元组
#(x[1],x[1]/x[2]))表示先通过元组中的第二项升序排序,如果相同在通过元组中的第二项除以第三项升序排序
print('排序后的商品信息:\n',bookinfo)