函數內部定義的函數,沒法在函數外部使用內部定義的函數。函數
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