python初识函数
一、函数的使用原则
函数的使用必须遵循:先定义后使用的原则
函数的定义,与变量的定义是相似的,如果没有事先定义函数而直接引用,就相当于在引用一个不存在的变量名
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 print(x) #NameError 2 x=1 3 4 func 5 6 def func(): 7 print('hello world')
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def func(): 2 print('hello world') 3 4 print(func) 5 func()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #定义阶段 2 def bar(): 3 print('from bar') 4 5 def foo(): 6 print('from foo') 7 bar() 8 9 #调用阶段 10 foo()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #定义阶段:只检测语法,不执行代码 2 def func(): 3 if 1>2 4 print('hahahahahahah') 5 6 7 def func(): #语法没问题,逻辑有问题,引用一个不存在的变量名 8 asdfasdfasdfasdfasdf
二、函数的返回值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #y=x**2 2 3 4 def func(x): 5 return x**2 6 y=func(10) # 10**2 7 8 print(y) 9 10 11 12 def foo(): 13 return None 14 15 res=foo() 16 print(res) 17 18 19 def foo(): 20 return {'a':1} 21 22 res=foo() 23 print(res['a']) 24 25 26 27 def foo(): 28 return {'a':1},1,'a',[1,2] 29 30 res=foo() 31 print(res) 32 33 34 def foo(): 35 return 1 36 print('=====>') 37 return 2 38 return 3 39 return 4 40 41 print(foo()) 42 43 44 ''' 45 返回值:可以返回任意类型 46 没有return:None 47 return value: value 48 return val1,val2,val3 :(val1,val2,val3) 49 50 51 return的效果:只能返回一次值,终止函数的执行 52 '''
三、函数参数的使用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #形参与实参: 2 # def foo(x,y): #x=1,y=2 3 # return x+y 4 # 5 # foo(1,2) 6 7 8 9 #===================================part1 10 #位置参数:按照从左到右的顺序依次定义的参数 11 12 13 def foo(x,y): 14 print(x) 15 print(y) 16 #按位置定义的形参,必须被传值,多一个不行,少一个也不行 17 18 # foo(1,2,3) 19 20 21 #按位置定义的实参,与形参一一对应 22 # foo(2,10) 23 24 25 26 #===================================part2 27 #关键字参数:实参在定义时,按照key=value形式定义 28 # def foo(x,y): 29 # print(x) 30 # print(y) 31 # 32 # # foo(y=10,x=1) 33 # foo(y=10,x=1) #关键字参数可以不用像位置实参一样与形参一一对应,指名道姓地传值 34 35 36 37 def foo(x,y): 38 print(x) 39 print(y) 40 41 42 # foo(1,10) 43 # foo(x=1,y=10) 44 # foo(1,y=10) 45 # foo(y=10,1) 46 # foo(x=10,1) 47 48 # foo(1,x=10,y=20) 49 50 51 # def foo(x,y,z): 52 # print(x) 53 # print(y) 54 # print(z) 55 # # foo(1,z=20,10) 56 # foo(1,y=2,z=10) 57 #注意的问题一:位置实参必须在关键字实参的前面 58 #注意的问题二:实参的形式既可以用位置实参又可以是关键字实参,但是一个形参不能重复传值 59 60 61 62 63 #===================================part3 64 #默认参数:在定义函数阶段,就已经为形参赋值,定义阶段有值,调用阶段可以不用传值 65 # def func(x,y=10): 66 # print(x) 67 # print(y) 68 69 70 # func(1,20) 71 # func(1) 72 73 74 75 # def func(y=10,x): 76 # print(x) 77 # print(y) 78 79 80 81 #位置实参 82 #关键字实参 83 84 #位置形参 85 #默认参数(形参) 86 87 88 #形参的应用:值经常变化的需要定义成位置形参, 89 # 值大多数情况下都一样,需要定义成默认参数 90 # def register(name,age,sex='male'): 91 # print(name,age,sex) 92 # 93 # register('alex',1000) 94 # register('wupeiqi',9000) 95 # register('yuanhao',10000) 96 # register('王铁蛋',10000,'female') 97 98 99 100 101 102 103 104 #默认参数需要注意的问题一:必须放在位置形参后面 105 #默认参数需要注意的问题二:默认参数通常要定义成不可变类型 106 #默认参数需要注意的问题三:默认参数只在定义阶段被赋值一次 107 # x=10 108 # def func(name,age=x): 109 # print(name) 110 # print(age) 111 # x=20 112 # 113 # func('egon') 114 115 116 117 118 119 # def func(name,age=10,sex='male',hobby=['play1','play2']): 120 # print(name) 121 # print(age) 122 # print(hobby) 123 # 124 # func('egon') 125 126 127 #===================================part4 128 #可变长参数:可变长指的是实参的个数不固定 129 #按位置定义的可变长度的实参:* 130 #按关键字定义的可变长度的实参:** 131 132 # 133 # def func(x,y,*args): #x=1,y=2,args=(3,4,5,6) 134 # print(x,y) 135 # print(args) 136 # 137 # func(1,2,3,4,5,6) 138 139 140 141 142 # def func(x,y,*args): #args=(3,4,5,6) 143 # print(x,y) 144 # print(args) 145 # 146 # func(1,2,*(3,4,5,6)) #foo(1,2,3,4,5,6) 147 148 149 # def func(x,y,z): 150 # print(x,y,z) 151 # 152 # # func(1,*(2,3)) #func(1,2,3) 153 # func(*(2,3)) #func(2,3) 154 155 156 157 # 158 # def func(x,y=2,z=1): 159 # print(x,y,z) 160 # 161 # 162 # func(*('a','b','c')) #func('a','b','c') 163 164 165 166 167 168 169 170 171 172 # def func(x,y,**kwargs): #x=1,y=2,kwargs={'a':1,'b':3,'z':3} 173 # print(x,y) 174 # print(kwargs) 175 # 176 # func(1,y=2,z=3,a=1,b=3) 177 178 179 180 181 182 # def func(x,y,**kwargs): #x=1,y=2,**kwargs=**{'a':1,'b':3,'z':3} 183 # print(x,y) 184 # print(kwargs) 185 # 186 # func(1,y=2,**{'a':1,'b':3,'z':3}) #func(1,y=2,z=3,b=3,a=1) 187 188 189 # def func(x,y=1,z=1): 190 # print(x,y,z) 191 # 192 # func(**{'y':2,'x':1,'z':3}) # 193 194 195 196 197 # def wrapper(*args,**kwargs): #可以接受任意形式,任意长度的参数 198 # print(args) 199 # print(kwargs) 200 # 201 # 202 # wrapper(1,2,3,3,3,3,3,x=1,y=2,z=3) 203 204 205 206 207 # 208 # def index(name,group): 209 # print('welcome %s to index page,group is: %s' %(name,group)) 210 # 211 # def wrapper(*args,**kwargs): #可以接受任意形式,任意长度的参数 212 # # print(args) #args=(1,2,3) 213 # # print(kwargs) #kwargs={'x':1,'y':2,'z':3} 214 # index(*args,**kwargs) #index(*(1,2,3),**{'x':1,'y':2,'z':3}) #index(1,2,3,z=3,y=2,x=1) 215 # 216 # wrapper(name='egon',group='group1') 217 218 219 220 221 222 223 224 225 #命名关键字参数:定义在*后的形参,这类形参,必须被传值,而且要求实参必须是以关键字的形式来传值 226 227 # def register(**kwargs): 228 # print(kwargs) 229 # if 'name' in kwargs: 230 # print(kwargs['name']) 231 # if 'age' in kwargs: 232 # print(kwargs['age']) 233 # 234 # 235 # # register(name='egon',age=18) 236 # register() 237 238 239 240 # def register(*args,name='egon',age): 241 # print(args) 242 # print(name) 243 # print(age) 244 # 245 # # register(name='egon',age=18) 246 # register(1,2,2,3,age=10) 247 248 249 250 # 251 # def register(name,age,*,group,**kwargs): 252 # print(name) 253 # print(age) 254 # print(kwargs) 255 # 256 # 257 # # register('egon',18) 258 # register('egon1',18,hobby='paly1',group='group1') 259 260 261 # def func(x,y=1,*args,z,**kwargs): 262 # print(x) 263 # print(y) 264 # print(args) 265 # print(z) 266 # print(kwargs) 267 # 268 # func(1,2,3,4,5,z=10,a=1,b=2) 269 270 271 272 # 273 # def func(x,*args,z=1,**kwargs): 274 # print(x) 275 # print(args) 276 # print(z) 277 # print(kwargs) 278 # 279 # func(1,2,3,4,5,a=1,b=2,c=3) 280 281 282 283 284 285 286 #形参:位置形参,默认参数,*args,命名关键字参数,**kwargs
四、函数嵌套
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #函数的嵌套调用 2 3 def max2(x,y): 4 if x > y: 5 return x 6 else: 7 return y 8 9 def max4(a,b,c,d): 10 res1=max2(a,b) #23 11 res2=max2(res1,c) #23 12 res3=max2(res2,d) #31 13 return res3 14 15 16 print(max4(11,23,-7,31)) 17 18 19 #函数的嵌套定义 20 def f1(): 21 def f2(): 22 def f3(): 23 print('from f3') 24 print('from f2') 25 f3() 26 print('from f1') 27 f2() 28 # print(f1) 29 f1() 30 31 ''' 32 from f1 33 from f2 34 from f3 35 36 '''
五、名称空间与作用域
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #名字空间:存放名字与值的绑定关系 2 3 #名称空间分为三种 4 5 #内置名称空间:python解释器自带的名字,python解释器启动就会生成 6 7 #全局名称空间:文件级别定义的名字都会存放与全局名称空间,执行python文件时会产生 8 9 # x=1 10 # def func(): 11 # pass 12 # 13 # class Foo: 14 # pass 15 # 16 # import os 17 # 18 # if 1 > 2 : 19 # y=3 20 21 #局部名称空间:定义在函数内部的名字,局部名称空间只有在调用函数时才会生效,函数调用结束则失效 22 # def func(x,y): #x=1,y=2 23 # z=3 24 25 # func(1,2) 26 27 28 #三者的加载顺序:内置名称空间->全局名称空间->局部名称空间 29 30 #取值:局部名称空间->全局名称空间->内置名称空间 31 32 33 # # max=10 34 # def func(): #x=1 35 # # max=20 36 # print(max) 37 # 38 # 39 # func() 40 41 42 43 # max=10 44 # 45 # def func(): #x=1 46 # max=20 47 # # print(max) 48 # func() 49 # 50 # 51 # print(max) 52 # 53 54 55 # # x=0 56 # def f1(): 57 # # x=1 58 # def f2(): 59 # # x=2 60 # def f3(): 61 # # x=3 62 # print(x) 63 # f3() 64 # f2() 65 # 66 # f1() 67 68 #作用域:作用范围 69 #全局作用域:内置名称空间与全局名称空间的名字属于全局范围, 70 # 在整个文件的任意位置都能被引用,全局有效 71 #局部作用域:局部名称空间的名字属于局部范围, 72 #只在函数内部可以被引用,局部有效 73 74 75 76 # x=1 77 # def foo(): 78 # def f2(): 79 # print(x) 80 # f2() 81 # def bar(): 82 # print(x) 83 # 84 # foo() 85 # bar() 86 87 88 # def f1(): 89 # x=1 90 # def f2(): #f2=value 91 # # x=2 92 # print(x) 93 # f2() 94 # f1() 95 96 97 x=1 98 def func(): 99 x=2 100 def f1():pass 101 # print(dir(globals()['__builtins__'])) #全局作用域name 102 # print(locals()) #局部作用域name 103 104 func() 105 106 print(globals() is locals()) 107 108 109 #局部作用域----->全局作用域
六、函数对象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #函数是第一类对象: 指的是函数可以被当做数据传递 2 3 def func(): 4 print('from func') 5 6 #可被引用 7 # f=func 8 9 #可以当做函数的参数 10 # def func(): 11 # print('from func') 12 # def foo(x): 13 # print(x) 14 # x() 15 # 16 # foo(func) 17 18 #可以当做函数的返回值 19 # def foo(): 20 # print('from foo') 21 # def bar(): 22 # return foo 23 # f=bar() 24 # print(f) 25 # print(foo) 26 27 # x=0 28 # def f1(): 29 # x=1 30 # def f2(): 31 # # x=2 32 # print(x) 33 # return f2 34 # f=f1() 35 # # print(f) 36 # f() 37 38 39 40 #可以当做容器类型的元素 41 # def select(): 42 # print('select function') 43 # 44 # func_dic={ 45 # 'select':select, 46 # } 47 # 48 # # print(func_dic['select']) 49 # func_dic['select']() 50 51 52 53 54 55 56 # 57 # def select(): 58 # print('select func') 59 # 60 # def delete(): 61 # print('delete func') 62 # 63 # def change(): 64 # print('change func') 65 # 66 # def add(): 67 # print('add func') 68 # 69 # 70 # while 1: 71 # cmd=input('>>: ').strip() 72 # if not cmd:continue 73 # if cmd == 'select': 74 # select() 75 # elif cmd == 'delete': 76 # delete() 77 # elif cmd == 'change': 78 # change() 79 # elif cmd == 'add': 80 # add() 81 # else: 82 # print('无效的命令') 83 84 85 86 87 88 89 90 def select(cmd_l): 91 filename=cmd_l[-1] 92 pattern=cmd_l[1] 93 94 with open(filename,'r',encoding='utf-8') as f: 95 for line in f: 96 if pattern in line: 97 print(line) 98 99 100 def delete(): 101 print('delete func') 102 103 def change(): 104 print('change func') 105 106 def add(): 107 print('add func') 108 109 def check(): 110 print('check func') 111 112 113 func_dic={ 114 'select':select, 115 'delete':delete, 116 'change':change, 117 'add':add, 118 'check':check, 119 } 120 121 122 while 1: 123 inp=input('>>: ').strip() 124 if not inp:continue 125 cmd_l=inp.split() 126 # print(cmd_l) 127 cmd=cmd_l[0] 128 if cmd in func_dic: 129 func_dic[cmd](cmd_l) 130 else: 131 print('无效的命令')