函数
# 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