Task09:函数与Lambda表达式
程序员文章站
2024-03-15 23:18:24
...
思维导图
代码
1.函数
# 函数的调用
def printme(str):
print(str)
printme('我要调用用户自定义函数')
printme('再次调用同一函数')
temp = printme('hello')
print(temp)
# 没有return,返回none
def add(a, b):
print(a + b)
add(1, 2)
add([1, 2, 3], [4, 5, 6])
# 对于不同的数据类型,+代表的意思是不同的
# 函数参数
def printinfo(name, age=8):
print('Name:{0},Age:{1}'.format(name, age))
printinfo('小马')
printinfo('小马', 10)
# 默认参数的默认值,第一位置是位置参数,第二位置为默认参数
def printinfo(name, age):
print('Name:{0},Age:{1}'.format(name, age))
printinfo(age=8, name='小马')
# 可变参数
def printinfo(arg1, *args):
print(arg1)
for var in args:
print(var)
printinfo(10)
printinfo(70, 60, 50)
# 关键字参数-字典
def printinfo(arg1, *args, **kwargs):
print(arg1)
print(args)
print(kwargs)
printinfo(70, 60, 50)
printinfo(70, 60, 50, a=1, b=2)
# 命名关键字参数
def printinfo(arg1, *, nkw, **kwargs):
print(arg1)
print(nkw)
print(kwargs)
printinfo(70, nkw=10, a=1, b=2)
# 命名的参数名不能不出现
def back():
return 1, 3.14
print(back(), type(back()))
# return的是tuple类型
# 求打折的例子
def discounts(price, rate):
final_price = price * rate
return final_price
old_price = float(input('请输入原价'))
rate = float(input('请输入折扣率'))
new_price = discounts(old_price, rate)
print('打折后的价格为:%0.2f' % new_price)
# 当内部作用域想修改为外部作用域的变量时,就要用到global
num = 1
def fun1():
global num
print(num)
num = 123
print(num)
fun1()
print(num)
# 内嵌函数
def outer():
print('outer函数在这被调用')
def inner():
print('inner函数在这里被调用')
outer(inner()) # 该行没有执行,该函数只能在outer函数内部被调用
outer()
def funX(x):
def funY(y):
return x * y
return funY
i = funX(8)
print(type(i))
print(i(5))
# 如果在一个内部函数里对外层非全局作用域的变量进行引用,那个内部函数就被认为是闭包,通过闭包可以访问外层非全局作用域的变量
# 闭包的返回值通常是函数
def make_counter(init):
counter = [init]
def inc(): counter[0] += 1
def dec(): counter[0] -= 1
def get(): return counter[0]
def reset(): counter[0] = init
return inc, dec, get, reset
inc, dec, get, reset = make_counter(0)
inc()
inc()
inc()
print(get())
dec()
print(get())
reset()
print(get())
# 修改闭包作用域中的变量则需要用nonlocal关键字
def outer():
num = 10
def inner():
nonlocal num
num = 100
print(num)
inner()
print(num)
outer()
# 循环
n = 5
for k in range(1, 5):
n = n * k
print(n)
#阶乘的两种算法
# 递归
def factoria(n):
if n == 1:
return 1
return n * factoria(n - 1)
print(factoria(5))
#斐波那契数列f(n)=f(n-1)+f(n-2), f(0)=0,f(1)=1
i=0
j=1
lst=list([i,j])#k可以用来控制次数
for k in range(2,11):
k=i+j
lst.append(k)
i=j
j=k
print(lst)
#斐波那契求法2
def recur_fibo(n):
if n<=1:
return n
return recur_fibo(n-1)+recur_fibo(n-2)
lst=list()
for k in range(11):
lst.append(recur_fibo(k))
print(lst)
2.lambda
#匿名函数
def sqr(x):
return x**2
print(sqr)
y=[sqr(x) for x in range(10)]
print(y)
lbd_sqr=lambda x:x**2
print(lbd_sqr)
y=[lbd_sqr(x) for x in range(10)]
print(y)
summary=lambda arg1,arg2:arg1+arg2
print(summary(10,20))
func=lambda *args:sum(args)
print(func(1,2,3,4,5))
#函数式编程和非函数式编程
def f(x):
for i in range(0,len(x)):
x[i]+=10
return x
x=[1,2,3]
f(x)
print(x)
#函数式编程
def f(x):
y=[]
for item in x:
y.append(item+10)
return y
x=[1,2,3]
f(x)
print(x)
odd=lambda x:x%2==1
templist=filter(odd,[1,2,3,4,5,6,7,8,9])
print(list(templist))
m1=map(lambda x:x**2,[1,2,3,4,5])
print(list(m1))
m2=map(lambda x,y:x+y,[1,3,5,7,9],[2,4,6,8,10])
print(list(m2))
习题
汉诺塔问题:
def hanoi(n: int, A: str, B: str, C: str):
if n == 1:
print(f"move from {A} to {C}")
else:
hanoi(n - 1, A, C, B)
print(f"move from {A} to {C}")
hanoi(n - 1, B, A, C)
hanoi(3, "A", "B", "C")
下一篇: Python面向对象编程(1)
推荐阅读