Function basis - function nesting

A function of nested definitions Dian

Internal function defined functions can not be used inside a function defined in an external function.

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
There is a demand for a function to pass through the area A reference to a circumference of a circle or circle:
Liezi:

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


Two nested definitions function Dian

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))

4

Guess you like

Origin www.cnblogs.com/suren-apan/p/11374783.html