函式的巢狀

2022-06-30 16:42:12 字數 983 閱讀 1813

函式的巢狀定義

def f1(): # 函式定義完畢,通過f1()呼叫函式,函式體開始執行

# def f2(): # 先找到f3(),並不會立刻就去找呼叫,在同級裡一步一步往下走,先到print("from f2")

# print('from f2') # 再到呼叫,最後執行f3()函式體

def f3():

print("lucas")

print('from f2') # 巢狀函式先執行同級的,定義--呼叫。

f3()

f1()

把圓的面積和周長巢狀在circle裡

from math import pi

def circle(radius,action='area'): #radius=10

def area():

return pi * (radius ** 2)

def perimeter():

return 2 * pi * radius

if action == 'area':

return area()

elif action == 'perimeter':

return perimeter()

print(circle(10))

print(circle(10,action='perimeter'))

函式的巢狀呼叫

def max2(x,y):

if x > y:

return x

else:

return y

def max4(a,b,c,d):

res = max2(a,b)

res1 = max2(res,c)

res2 = max2(res1,d)

return res2

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

函式的巢狀

例1 def index print from index def func index print from func func 定義乙個index函式 定義乙個func函式 呼叫func函式,然後跳轉到那邊執行語句,先執行index 語句,列印from index,然後往下執行,列印from f...

函式的巢狀

a 1 def outer a 2 def inner a 3 def inner2 nonlocal a nonlocal只能用於區域性變數,找最近一層的區域性變數 a 1 inner2 print inner a a inner print a a outer print a def func ...

Python中函式巢狀以及函式巢狀的繼承

a 10 b 0 c 5 try print a的值是 d,b的值是 d a,b f c.open a.txt print f d a b print d除以 d的值為 d a,b,d except zerodivisionerror,attributeerror as msg print 程式出錯...