一、函数的简介
1.1、函数定义
python中函数的定义方法:
def test(x):
"The function definitions"
x+=1
return x
#def:定义函数的关键字
#test:函数名
#():内可定义形参
#"":文档描述(非必要,但是强烈建议为你的函数添加描述信息)
#x+=1:泛指代码块或程序处理逻辑
#return:定义返回值
#调用运行:可以带参数也可以不带
函数名()
1.2、函数的好处
1)代码重用
2)保持一致性,易维护
3)可扩展性
1.3、函数与过程
过程:简单特殊没有返回值的函数
def test01():
msg='hello The little green frog'
print(msg)
def test02():
msg='hello WuDaLang'
print(msg)
return msg
t1=test01()
t2=test02()
print('from test01 return is [%s]' %t1) #from test01 return is [None]
print('from test02 return is [%s]' %t2) #from test02 return is [hello WuDaLang]
返回结果:
def test01():
pass
def test02():
return 0
def test03():
return 0,10,'hello'
t1=test01()
t2=test02()
t3=test03()
print('from test01 return is [%s]: ' %type(t1),t1) #from test01 return is [<class 'NoneType'>]: None
print('from test02 return is [%s]: ' %type(t2),t2) #[<class 'int'>]: 0
print('from test03 return is [%s]: ' %type(t3),t3) #from test03 return is [<class 'tuple'>]: (0, 10, 'hello')
1.4、函数的参数
1.4.1、形参与实参
形参即变量名,实参即变量值,函数调用时,将值绑定到变量名上,函数调用结束,解除绑定
1.4.2、位置参数
按照从左到右的顺序定义的参数
- 位置形参:必选参数
- 位置实参:按照位置给形参传值
1.4.3、关键字参数
无需按照位置为形参传值 注意的问题:
- 关键字实参必须在位置实参右面
- 对同一个形参不能重复传值
1.4.4、默认参数
可以传值也可以不传值,经常需要变得参数定义成位置形参,变化较小的参数定义成默认参数(形参)
注意的问题:
- 只在定义时赋值一次
- 默认参数的定义应该在位置形参右面
- 默认参数通常应该定义成不可变类型
1.4.5、可变长参数
可变长指的是实参值的个数不固定,*args,**kwargs
def foo(x, y, *args):
print(x, y)
print(args)
foo(1, 2, 3, 4, 5)
#1 2
#(3, 4, 5)
-------------------------
def foo(x, y, *args):
print(x, y)
print(args)
foo(1, 2, *[3, 4, 5])
#1 2
#(3, 4, 5)
-------------------------
def foo(x, y, z):
print(x, y, z)
foo(*[1, 2, 3]) #1 2 3
-------------------------
def foo(x, y, **kwargs):
print(x, y)
print(kwargs)
foo(1, y=2, a=1, b=2, c=3)
#1 2
#{'a': 1, 'c': 3, 'b': 2}
-------------------------
def foo(x, y, **kwargs):
print(x, y)
print(kwargs)
foo(1, y=2, **{'a': 1, 'b': 2, 'c': 3})
#1 2
#{'a': 1, 'b': 2, 'c': 3}
-------------------------
def foo(x, y, z):
print(x, y, z)
foo(**{'z': 1, 'x': 2, 'y': 3})
#2 3 1
1.5、全局变量与局部变量
在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量。
全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序。
当全局变量与局部变量同名时:
在定义局部变量的子程序内,局部变量起作用;在其它地方全局变量起作用。
#当子程序没有定义局部变量时,会查找全局变量
name='Lawrence'
def change_name():
print('我的名字',name)
change_name() #我的名字 Lawrence
#局部变量存在时
name='Lawrence'
def change_name():
name='jack'
print('我的名字',name)
change_name() #我的名字 jack
print(name) #Lawrence
#使用global关键字
name='Lawrence'
def change_name():
global name
name='jack'
print('我的名字',name)
change_name() #我的名字 jack
print(name) #jack
优先读取局部变量,能读取全局变量,无法对全局变量重新赋值 NAME=“fff”,但是对于可变类型,可以对内部元素进行操作,如果函数中有global关键字,变量本质上就是全局的那个变量,可读取可赋值 NAME=“fff”
1.6、函数的作用域
name='lawrence'
def foo():
name='jack'
def bar():
name='vivian'
#print(name)
def tt():
print(name)
return tt
return bar
foo()()() #vivian
1.7、前向引用-函数即变量
def foo():
print('from foo')
bar()
foo() #报错NameError: name 'bar' is not defined
-------------------------------------------------
def bar():
print('from bar')
def foo():
print('from foo')
bar()
foo() #正常运行
-------------------------------------------------
def foo():
print('from foo')
bar()
def bar():
print('from bar')
foo() #正常运行
-------------------------------------------------
def foo():
print('from foo')
bar()
foo() #报错NameError: name 'bar' is not defined
def bar():
print('from bar')
1.8、递归函数
递归特性:
1. 必须有一个明确的结束条件
2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少
3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)
1)示例1
def calc(n):
print(n)
if int(n / 2) == 0:
return n
res=calc(int(n / 2))
return res
calc(10) #10 5 2 1
2)示例2
import time
person_list=['alex','wupeiqi','linhaifeng','zsc']
def ask_way(person_list):
print('-'*60)
if len(person_list) == 0:
return '根本没人知道'
person=person_list.pop(0)
if person == 'linhaifeng':
return '%s说:我知道,老男孩就在沙河汇德商厦,下地铁就是' %person
print('hi 美男[%s],敢问路在何方' % person)
print('%s回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问%s...' % (person, person_list))
time.sleep(2)
res=ask_way(person_list)
print('%s问的结果是: %res' %(person,res))
return res
res=ask_way(person_list)
print(res)
1.9、匿名函数
def calc(x):
return x+1
res=calc(10)
print(res) #11
print(calc) #<function calc at 0x00000271544D7F28>,函数的内存地址
print(lambda x:x+1) #<function <lambda> at 0x0000027154AEE158>
func=lambda x:x+1
print(func(10)) #11
-----------------------------------------------------------------------
name='lawrence'
def change_name(x):
return name+'_super'
res=change_name(name)
print(res) #lawrence_super
func=lambda x:x+'_sb'
res=func(name)
print('匿名函数的运行结果',res) #匿名函数的运行结果 lawrence_sb
1.10、map函数
处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样
def map_test(func,array):
ret=[]
for i in array:
res=func(i)
ret.append(res)
return ret
num_l=[1,2,10,5,3,7]
print(map_test(lambda x:x+1,num_l)) #[2, 3, 11, 6, 4, 8]
-------------------------------------------------------------------------------
#map函数
num_l=[1,2,10,5,3,7]
res=map(lambda x:x+1,num_l)
print('内置函数map,处理结果',res) #内置函数map,处理结果 <map object at 0x0000020141E8C160>
print(list(res)) #[2, 3, 11, 6, 4, 8]
-------------------------------------------------------------------------------
msg='lawrence'
print(list(map(lambda x:x.upper(),msg))) #['L', 'A', 'W', 'R', 'E', 'N', 'C', 'E']
1.11、filter函数
filter遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来
movie_people=['aaa_sb','bbb_sb','ccc','ddd_sb']
def filter_test(func,array):
ret=[]
for p in array:
if not func(p):
ret.append(p)
return ret
res=filter_test(lambda n:n.endswith('sb'),movie_people)
print(res) #['ccc']
-------------------------------------------------------
#filter函数
movie_people=['aaa_sb','bbb_sb','ccc','ddd_sb']
print(filter(lambda n:not n.endswith('sb'),movie_people)) #<filter object at 0x000001ED71DF6CC0>
------------------------------------------------------
movie_people=['aaa_sb','bbb_sb','ccc','ddd_sb']
res=filter(lambda n:not n.endswith('sb'),movie_people)
print(list(res))
------------------------------------------------------
print(list(filter(lambda n:not n.endswith('sb'),movie_people)))
示例:
people=[
{'name':'A','age':1000},
{'name':'B','age':10000},
{'name':'C','age':9000},
{'name':'D','age':18},
]
print(list(filter(lambda p:p['age']<=18,people))) #[{'age': 18, 'name': 'D'}]
1.12、reduce函数
处理一个序列,然后把序列进行合并操作
num_l=[1,2,3,100]
def reduce_test(func,array,init=None):
if init is None:
res=array.pop(0)
else:
res=init
for num in array:
res=func(res,num)
return res
print(reduce_test(lambda x,y:x*y,num_l,100)) #60000
-----------------------------------------------------
#reduce函数
from functools import reduce #导入函数
num_l=[1,2,3,100]
print(reduce(lambda x,y:x+y,num_l,1)) #107
print(reduce(lambda x,y:x+y,num_l)) #106
示例:
from functools import reduce
print(reduce(lambda x,y:x+y,range(100),100)) #100+1+2+...+99=5050
print(reduce(lambda x,y:x+y,range(1,101))) #1+2+....+100=5050
1.13、内置函数
文档:https://docs.python.org/3/library/functions.html?highlight=built#ascii
print(abs(-1)) #1
print(abs(1)) #1
print(all([1,2,'1'])) #true
print(all([1,2,'1',''])) #false
print(all('')) #true ==>If the iterable is empty, return True.
print(bin(3)) #0b11
#空,None,0的布尔值为False,其余都为True
print(bool(''))
print(bool(None))
print(bool(0))
name='你好'
print(bytes(name,encoding='utf-8')) #b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(bytes(name,encoding='utf-8').decode('utf-8')) #你好
print(bytes(name,encoding='gbk')) #b'\xc4\xe3\xba\xc3'
print(bytes(name,encoding='gbk').decode('gbk')) #你好
# print(bytes(name,encoding='ascii')) #报错ascii不能编码中文
print(chr(97)) #a
print(dir(dict)) #打印dict的方法
print(divmod(10,3)) #(3, 1) ==>Return the tuple ((x-x%y)/y, x%y)
dic={'name':'alex'}
dic_str=str(dic) #转换为字符串
print(dic_str)
#可hash的数据类型即不可变数据类型,不可hash的数据类型即可变数据类型
print(hash('12sdfdsaf3123123sdfasdfasdfasdfasdfasdfasdfasdfasfasfdasdf'))
print(hash('12sdfdsaf31231asdfasdfsadfsadfasdfasdf23'))
name='alex'
print(hash(name)) #1628103345716101507
print(hash(name)) #1628103345716101507
print(help(all)) #打印函数的方法
print(bin(10))#10进制->2进制
print(hex(12))#10进制->16进制
print(oct(12))#10进制->8进制
print(isinstance(1,int)) #True
print(isinstance('abc',str)) #True
print(isinstance([],list)) #True
print(isinstance({},dict)) #True
print(isinstance({1,2},set)) #True
name='哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈粥少陈'
# print(globals()) #打印全局变量
print(__file__) #G:/python/内置函数.py
def test():
age='11111111111111'
# print(globals())
print(locals()) #{'age': '11111111111111'} 打印局部变量
test()
#------------------------------------------------------------------------
l=[1,3,100,-1,2]
print(max(l))
print(min(l))
print(list(zip(('a','n','c'),(1,2,3)))) #[('a', 1), ('n', 2), ('c', 3)]
print(list(zip(('a','n','c'),(1,2,3,4)))) #[('a', 1), ('n', 2), ('c', 3)]
print(list(zip(('a','n','c','d'),(1,2,3)))) #[('a', 1), ('n', 2), ('c', 3)]
p={'name':'lawrence','age':18,'gender':'male'}
print(list(zip(p.keys(),p.values()))) #[('gender', 'male'), ('name', 'lawrence'), ('age', 18)]
print(list(p.keys())) #['name', 'gender', 'age']
print(list(p.values())) #['lawrence', 'male', 18]
print(list(zip(['a','b'],'12345'))) #[('a', '1'), ('b', '2')]
age_dic={'A_age':18,'B_age':20,'D_age':100,'E_age':30}
print(max(age_dic.values())) #100
#
#默认比较的是字典的key
print(max(age_dic)) #E_age
people=[
{'name':'alex','age':1000},
{'name':'wupei','age':10000},
{'name':'yuanhao','age':9000},
{'name':'linhaifeng','age':18},
]
# max(people,key=lambda dic:dic['age'])
print(max(people,key=lambda dic:dic['age'])) #{'age': 10000, 'name': 'wupei'}
print(chr(97)) #a
print(ord('a')) #97
print(pow(3,3)) #3**3
print(pow(3,3,2)) #3**3%2
l=[1,2,3,4]
print(list(reversed(l))) #[4, 3, 2, 1]
print(l) #[1, 2, 3, 4]
print(round(3.5)) #4
print(set('hello')) #{'h', 'e', 'o', 'l'}
#分片
l='hello'
s1=slice(3,5)
s2=slice(1,4,2)
print(l[3:5]) #lo
print(l[s1]) #lo
print(l[s2]) #el
print(s2.start) #1
print(s2.stop) #4
print(s2.step) #2
# print(sorted(l1)) #排序本质就是在比较大小,不同类型之间不可以比较大小
people=[
{'name':'alex','age':1000},
{'name':'wupei','age':10000},
{'name':'yuanhao','age':9000},
{'name':'linhaifeng','age':18},
]
print(sorted(people,key=lambda dic:dic['age']))
#[{'name': 'linhaifeng', 'age': 18}, {'name': 'alex', 'age': 1000}, {'name': 'yuanhao', 'age': 9000}, {'name': 'wupei', 'age': 10000}]
name_dic={
'abyuanhao': 11900,
'alex':1200,
'wupei':300,
}
print(sorted(name_dic)) #['abyuanhao', 'alex', 'wupei']
print(sorted(name_dic,key=lambda key:name_dic[key])) #['wupei', 'alex', 'abyuanhao']
print(sorted(zip(name_dic.values(),name_dic.keys()))) #[(300, 'wupei'), (1200, 'alex'), (11900, 'abyuanhao')]
print(type(str({'a':1}))) #<class 'str'>
dic_str=str({'a':1})
print(type(eval(dic_str))) #<class 'dict'>
l=[1,2,3,4]
print(sum(l))
print(sum(range(5)))
print(type(1)) #<class 'int'>
def test():
msg='abjfdkajslf'
print(locals()) #{'msg': 'abjfdkajslf'}
print(vars()) #Without arguments, equivalent to locals().With an argument, equivalent to object.__dict__.
test()
print(vars(int))
#import------>sys----->__import__()
import test
test.say_hi()
# import 'test'#报错
module_name='test'
m=__import__(module_name)
m.say_hi()