函数的嵌套
1.函数的嵌套定义
- 一旦在函数内部定义一个函数,那么函数体内的函数,无法在函数外部使用
def f1():
def f2():
print('from f2')
f2()
f2()
# # NameError: name 'f2' is not defined
def f1():
def f2():
print('from f2')
f2()
f1()
# from f2
- 通过给一个函数传参即可求得某个圆的面积或者圆的周长
import cmath
def circle(r,choice):
def area():
return cmath.pi*r**2
def perimeter():
return 2*cmath.pi*r
if choice == 'area':
return area()
else:
return perimeter()
res = circle(3,'perimeter')
print(res) # 18.84955592153876
res = circle(3,'area')
print(res)# 28.274333882308138
2.函数的嵌套调用
def max2(x,y):
if x > y:
return x
else:
return y
res = max2(1,2)
# print(res)
def max4(x,y,z,a):
res = max2(x,y)
res1 = max2(res,z)
res2 = max2(res1,a)
return res2
res = max4(5,4,31,3)
print(res) # 31