With the help of lambda function, we can create one line function definition.
借助lambda函數,我們可以創建一個行函數定義。
Note: Function must have return type and parameter
注意:函數必須具有返回類型和參數
Example:
例:
Convert temperature from Celsius to Fahrenheit
將溫度從攝氏溫度轉換為華氏溫度
1) Approach 1: Using normal way
1)方法1:使用常規方法
# function definition to convert from c to F
def ctof(c):
f=9/5*c+32
return f
# input
c=int(input("Enter Temp(C): "))
# function call
f=ctof(c)
# print
print("Temp(F) :",f)
Output
輸出量
Enter Temp(C): 10
Temp(F) : 50.0
2) Approach 2: Using lambda
2)方法2:使用lambda
# lambda function
ctof = lambda c:9/5*c+32
# input
c=int(input("Enter Temp(C):"))
# function call
f=ctof(c)
# print
print("Temp(F) :",f)
Output
輸出量
Enter Temp(C): 10
Temp(F) : 50.0
翻譯自: https://www.includehelp.com/python/lambda-function-with-example.aspx