# 函数封装的练习题# 打印九九乘法表,矩形,十二生肖# 定义函数,打印九九乘法表defjiujiu(n =0):'''
当前函数的功能:打印九九乘法表
n = 0:n=0正向输出, n=1 反向输出
:return:
'''if n ==0:
re =range(1,10)else:
re =range(9,0,-1)for x in re:for y inrange(1,x+1):print(f'{x}*{y}={x*y}',end=" ")print()
jiujiu(1)# 封装打印矩形的函数defjuxing():for x inrange(1,100):print(f'a ',end="")if x %10==0:print()
juxing()
递归函数
'''
递归函数:
递归函数就是定义了一个函数,然后在函数内,自己调用了自己这个函数
递归函数内必须要有接受,不然就会一直调用下去,直到调用的层数越来越多,栈溢出
递归函数是一层层的进入再一层层的返回
递归函数的效率并不高,尽量不使用就不使用
一个函数如果调用后,没有结束,那么在栈空间就一直存在,直到这个函数运算结束才销毁
斐波那契数列
1 1 2 3 5 8 13
实现一个数的阶乘:
1*2*3*4*5*6*7
'''# 初步认识 递归函数 3 2 1 0defdigui(num):print(num)# 检测当前的值是否到了零if num >0:# 调用函数本身
digui(num-1)print(num)# 0 1 2 3
digui(3)'''
解析当前递归函数的执行过程:
digui(3) ==> 3
digui(3-1) ==> 2
digui(2-1) ==> 1
digui(1-1) ==> 0
digui(0) ==> 0
digui(1) ===> 1
digui(2) ==> 2
digui(3) ==> 3
'''# 实现递归函数——阶乘# 求一个数的阶乘的结果 7 1*2*3*4*5*6*7defjiecheng(n):if n ==1:return1else:return n*jiecheng(n-1)
res = jiecheng(7)print(res)# 实现递归函数——斐波那契数列defFibonacci(pos):# check for the terminating conditionif pos <=1:# Return the value for position 1, here it is 0return0if pos ==2:# return the value for position 2, here it is 1return1# perform some operation with the arguments# Calculate the (n-1)th number by calling the function itself
n_1 = Fibonacci(pos -1)# calculation the (n-2)th number by calling the function itself again
n_2 = Fibonacci(pos -2)# calculate the fibo number
n = n_1 + n_2
# return the fibo numberreturn n
# Here we asking the function to calculate 5th Fibonacci
nth_fibo = Fibonacci(5)print(nth_fibo)
回调函数
# 回调函数# 如果在一个函数中要求传递的参数是一个函数作为参数,并且在函数中使用了传递进来的函数,那么这个函数我们称为是一个回调函数# 定义一个函数,函数中的一个参数要求是另一个函数# 带有回调函数参数的函数deffunc(f):print(f,type(f))# 并且在函数中调用了传递进来的形参函数
f()# 回调函数deflove():print('123')
func(love)deffunc(x,y,z):'''
当前函数接受两个数值,并把这两个数值传递给第三个参数进行运算
x,y int
z function
:param x: int
:param y: int
:param z: int
:return: function
'''print(f([x,y]))print(sum([1,2]))