python學習筆記 - lambda表達式 . 函數. 作為參數傳參


#=============== lambda作為參數 ====================
#函數或lambda表達式作為參數傳參
def calculate(x, y, func):
    return func(x, y)

#加法
def add(x, y):
    return x + y

#減法
def sub(x, y):
    return x - y

a,b = 5,8
add_ret = calculate(a, b, add)  #加法
sub_ret = calculate(a, b, sub)  #減法
mul_ret = calculate(a, b, lambda a,b : a*b)  #乘法
dev_ret = calculate(a, b, lambda a,b : a/b)  #除法

print('加法運算: {}+{}={}'.format(a, b, add_ret))
print('減法運算: {}-{}={}'.format(a, b, sub_ret))
print('乘法運算: {}*{}={}'.format(a, b, mul_ret))
print('除法運算: {}/{}={}'.format(a, b, dev_ret))

打印結果:
加法運算: 5+8=13
減法運算: 5-8=-3
乘法運算: 5*8=40
除法運算: 5/8=0.625

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM