函数
2019-11-06 23:35
786 查看
函数
# def test(): #定义一个函数,关键字def # print("OK") # # test() #引用函数 # import time # # # def logger(n): # time_format = '%Y-%m-%d %X' # time_current = time.strftime(time_format) # # with open('日志记录','a') as f: # f.write('%s end action%s\n' %(time_current,n)) # # def action1(n): # print('starting action1...') # logger(n) # # def action2(n): # print('starting action2...') # logger(n) # # def action3(n): # print('starting action3...') # logger(n) # # action1(1) # action2(2) # action3(3) #形参 # def print_info(name,age,sex='man'): #sex定义默认参数 # print("name: %s" %name) # print("age: %d" %age) # print("sex: %s" %sex) # #必须参数 # # print_info('hao',11) # #关键字参数 # print_info(name='xiaoxue',age=22) #不定长参数 # *args ---一个元素,元组 # def add(*args): # sum = 0 # for i in args: # sum += i # print(sum) # add(1,2,3,4) # **kwargs---一个key,一个值,字典 # def f(**kwargs): # for i in kwargs: # print('%s:%s' %(i,kwargs[i])) # f(name='hao',age=18) #关键字参数最左,默认参数随后,没有命名在中间(*args),有命名放最后(**kwargs) # def f(sex=1,*args,**kwargs): return返回值 def f(*args): # sum = 0 # for i in args: # sum += i # # return sum #返回结果 # a = f(1,3) # print(a) #返回结果None #注意点:1.函数里如果没有return,会默认返回一个None #2.如果return多个对象,那么Python会帮我们做成一个对象元组 #作用域 # count = 10 # # def outer(): # # global count #修改全局变量要global关键字声明count为全局变量 # # print(count) # count = 4 # # print(count) # def inter(): # nonlocal count #修改嵌套变量,要nonlocal关键字声明 # count = 20 # print(count) # inter() # outer()
高阶函数
def f(n): return n**2 def foo(a,b,func): result = func(a) + func(b) print(result) foo(1,3,f) #输出结果:10 1. 函数名可以进行赋值 2. 函数名可以作为函数参数,还可以作为函数的返回值 def t(): def inner(): return 8 return inner ret = t() print(ret) #输出结果:<function t.<locals>.inner at 0x006AAA50>
递归:
# def fat(n): # ret = 1 # for i in range(1,n+1): # ret *= i # return ret # print(fat(5)) # #输出结果:120(5*4*3*2*1) ##递归 #1. 调用自身函数 #2. 有一个结束条件 #但凡是递归可以写,循环也能写 #递归效率比较低 # def fat(n): # if n ==1: # return 1 # return n * fat(n-1) # print(fat(5)) #斐波数列 # a = 0 # b = 1 # while b < 100: # print(b ,end=' ') # a, b = b, a + b
相关文章推荐
- 第十七周 项目一:体会函数参数传递
- 字符串删减函数
- DllMain函数参数简介
- strncmp很好的函数
- 函数调用分析 http://www.cnblogs.com/bangerlee/archive/2012/05/22/2508772.html
- 18.9: fn:substringAfter 函数
- c++中虚函数和多态性的问题
- C++ Primer【第五版】习题参考答案——第六章(函数)
- round()和trunc()函数的应用
- mysql存储过程基本函数
- isprint () 函数
- freopen重定向函数
- 友元函数实例
- SQL字符串处理函数大全
- opengl绘制几何体的函数
- 虚函数——虚表总结
- java函数参数后面加三个点——可变长度参数列表
- 立刻执行函数深入了解
- C语言:函数参数传递的三种方式
- PHP获取当前url路径的函数及服务器变量:QUERY_STRING、REQUEST_URI、SCRIPT...