第七章、函数基础之函数嵌套09

第七章、函数基础之函数嵌套

一、函数的嵌套定义

函数内部定义的函数,无法在函数调用内部定义的函数

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

二、函数的嵌套的调用

def max2(x, y):
    if x > y:
        return x
    else:
        return y


def max4(a, b, c, d):
    res1 = max2(a, b)
    res2 = max2(res1, c)
    res3 = max2(res2, d)
    return res3


print(max4(1, 2, 3, 4))

三、练习

from math import pi


def circle(radius, action='area'):
    def area():
        return pi * (radius**2)

    def perimeter():
        return 2*pi*radius
    if action == 'area':
        return area()
    else:
        return perimeter()


print(f"circle(10): {circle(10)}")
print(f"circle(10,action='perimeter'): {circle(10,action='perimeter')}")

circle(10): 314.1592653589793 circle(10,action='perimeter'): 62.83185307179586

猜你喜欢

转载自www.cnblogs.com/demiao/p/11335325.html