zoukankan      html  css  js  c++  java
  • 函数嵌套

    函数嵌套

    一、函数的嵌套定义

    函数内部定义的函数,无法在函数外部使用内部定义的函数。

    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
    

    现在有一个需求,通过给一个函数传参即可求得某个圆的面积或者圆的周长。也就是说把一堆工具丢进工具箱内,之后想要获得某个工具,直接从工具箱中获取就行了。

    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

    二、函数的嵌套调用

    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

    在当下的阶段,必将由程序员来主导,甚至比以往更甚。
  • 相关阅读:
    luogu P2852 [USACO06DEC]Milk Patterns G
    FZOJ 4267 树上统计
    CF1303G Sum of Prefix Sums
    luogu P5311 [Ynoi2011]成都七中
    luogu P5306 [COCI2019] Transport
    SP34096 DIVCNTK
    luogu P5325 【模板】Min_25筛
    luogu P1742 最小圆覆盖
    求两直线交点坐标
    1098: 复合函数求值(函数专题)
  • 原文地址:https://www.cnblogs.com/randysun/p/12240276.html
Copyright © 2011-2022 走看看