python——函数
来源:互联网 发布:php 面向对象 太烂 编辑:程序博客网 时间:2024/06/05 14:41
函数
python也分形参实参
函数文档(突然发现tab是好用的)
def myfirstfun(name):'xxxx'#xxxxxprint(name)>>> myfirstfun(x) SyntaxError: invalid character in identifier>>> myfirstfun('x')x>>> myfirstfun.__doc__'xxxx'>>> help(myfirstfun)Help on function myfirstfun in module __main__:myfirstfun(name) xxxx>>> print.__doc__"print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n\nPrints the values to a stream, or to sys.stdout by default.\nOptional keyword arguments:\nfile: a file-like object (stream); defaults to the current sys.stdout.\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.\nflush: whether to forcibly flush the stream.">>> help(print)Help on built-in function print in module builtins:print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
>>>
关键字参数
>>> tell('misszhou','让编程编织梦想')misszhou让编程编织梦想>>> tell(wors='words',name='misszhou')Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> tell(wors='words',name='misszhou')TypeError: tell() got an unexpected keyword argument 'wors'>>> tell(words='words',name='misszhou')misszhouwords
默认参数
>>> def saysome(name='name',word='word'):print(name+word)>>> saysome<function saysome at 0x000000A74A7969D8>>>> saysome()nameword
收集参数(这玩意别的语言没有,类C语言有可变参数啊)print的实现
>>> def test(*par):print('len',len(par))print(par[0])>>> test(1,2,3,4)len 41>>> def test(*par,exp=8)SyntaxError: invalid syntax>>> def test(*par,exp=8):print('len:',len(par),exp)print('第二个参数为',par[1])>>> test(1,2,3,4)len: 4 8
第二个参数为 2
函数与过程
python可以返回多个值(通过列表打包呗)
>>> def back():return 1,'misszhou'>>> back()(1, 'misszhou')
python也分全局变量/局部变量
一段神奇的代码
def discount(price,rate): fin_price=price*rate # print('这里试图打印全局变量old_price:',old_price) old_price=50 print('1修改后oldprice的值',old_price) return fin_priceold_price=float(input('请输入原价:'))rate=float(input('请输入折扣;'))new_price=discount(old_price,rate)print('2修改后oldprice的值',old_price)print('折扣后价格:',new_price)请输入原价:100请输入折扣;0.91修改后oldprice的值 502修改后oldprice的值 100.0折扣后价格: 90.0
为什么呢?在函数里面的那个是新创建的局部变量!!不是原来的那个全局变量
我要是想在函数里面修改全局变量,也可以嵌套定义
内嵌函数和闭包
global关键字(这玩意和php一样啊=w=)
>>> count=5>>> def myfun()SyntaxError: invalid syntax>>> def myfun():count=10print(count)>>> def myfun()SyntaxError: invalid syntax>>> myfun()10>>> print(count)5>>> def myfun():global countcount=10print(10) SyntaxError: invalid character in identifier>>> def myfun():global countcount=10print(10)>>> def myfun():global countcount=10print(count)>>> def myfun()SyntaxError: invalid syntax>>> myfun()10>>> print(count)10
函数嵌套
>>> def fun1():print('fun1')def fun2():print('fun2')fun2()>>> fun1()fun1fun2>>> fun2()Traceback (most recent call last): File "<pyshell#68>", line 1, in <module> fun2()NameError: name 'fun2' is not defined>>> fun1().fun2()fun1fun2Traceback (most recent call last): File "<pyshell#69>", line 1, in <module> fun1().fun2()AttributeError: 'NoneType' object has no attribute 'fun2'闭包(这玩意js有啊)>>> def funx(x):def funy(y):return x*yreturn funy>>> i=funx(8)>>> i<function funx.<locals>.funy at 0x0000004A51346A60>>>> type(i)<class 'function'>>>> i(5)40>>> funx(4)(4)16>>> funy(8)Traceback (most recent call last): File "<pyshell#80>", line 1, in <module> funy(8)NameError: name 'funy' is not defined>>> def fun1():x=5def fun2():x*=xreturn xreturn fun2()>>> fun1()Traceback (most recent call last): File "<pyshell#88>", line 1, in <module> fun1() File "<pyshell#87>", line 6, in fun1 return fun2() File "<pyshell#87>", line 4, in fun2 x*=xUnboundLocalError: local variable 'x' referenced before assignment>>> def fun1():x[0]=5def fun2():x[0]*=x[0]return x[0]return fun2()>>> fun1()Traceback (most recent call last): File "<pyshell#91>", line 1, in <module> fun1() File "<pyshell#90>", line 2, in fun1 x[0]=5NameError: name 'x' is not defined>>> def fun1():x=[5]def fun2():x[0]*=x[0]return x[0]return fun2()>>> fun1()25>>> def fun1():x=5def fun2():nonlocal xx*=xreturn xreturn fun2()>>> fun1()25
lambda表达式
参数:返回值
>>> x=lambda x,y:x+y>>> print(x)<function <lambda> at 0x0000004A51346EA0>>>> x(3,4)7
这玩意在js里面不也有么……
lambda表达式的作用
省下定义函数的作用、不需要考虑函数名、省得函数阅读跳到开头定义部分
filter()过滤器
help(filter)Help on class filter in module builtins:class filter(object) | filter(function or None, iterable) --> filter object | | Return an iterator yielding those items of iterable for which function(item) | is true. If function is None, return the items that are true. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __next__(self, /) | Implement next(self). | | __reduce__(...)<pre name="code" class="python">>>> def odd(x):return x%2>>> temp=range(10)>>> show=filter(odd,temp)>>> list(show)[1, 3, 5, 7, 9]
| Return state information for pickling.filter(None,[1,0,False,True])<filter object at 0x0000004A5135B240>>>> list(filter(None,[1,0,False,True]))
[1, True]
默认把一切非正的过滤掉
自定义:
>>> def odd(x):return x%2>>> temp=range(10)>>> show=filter(odd,temp)>>> list(show)[1, 3, 5, 7, 9]
学以致用精简一下
>>> list(filter(lambda x:x%2,range(10)))
map()
映射
list(map(lambda x:x%2,range(10)))[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
递归
可以人为规定递归层数
import syssys.setrecursionlimit(10000)
输出阶乘
def func(num): if(num==1): return 1 return num*func(num-1)num=int(input())print(func(num))
递归的斐波那契
def fun(n): if(n==3): return 2 elif(n==2): return 1 return fun(n-1)+fun(n-2)print(fun(12))
汉诺塔
def hano(n,x,y,z): if(n==1): print(x,"-->",z) return hano(n-1,x,z,y) print(x,"-->",z) hano(n-1,y,x,z)n=int(input())hano(n,'x','y','z')
0 0
- python——函数
- Python——函数
- Python—定义函数
- Python函数—基础
- Python函数—参数
- Python——strip()函数,title()函数
- python—数学函数/随机数函数/三角函数
- Python内建函数—isinstance()函数
- 关于python——函数
- python基础知识——函数
- Python——makefile函数
- Python——函数基础
- python学习——函数
- Python——5函数
- python基础——函数
- Python入门——函数
- Python——调用函数
- Python——fifter函数
- Android MediaRecorder 后台视频录制
- HDU1711-KMP算法
- ActiveRecord中实现软删除
- pch文件配置
- Python 基础归纳整理
- python——函数
- Give the common ancestor of all the deepest nodes of a tree
- 最近公共祖先
- android开发 使用RecycleView加载数据
- 使用vlc实现视频TS流的推送
- Exception:Failed to start component [StandardEngine[Catalina... NoClassDefFoundError:org/apache/log4
- java 通过URL请求获取结果(http协议)
- useful url
- php浮点数的精度问题深究