Python | Lambda function with Example

Python lambda function with example: Here, we are going to learn about lambda function and learn how to write one line code by using lambda?
Submitted by Pankaj Singh, on October 12, 2018

With the help of lambda function, we can create one line function definition.

Note: Function must have return type and parameter

Example:

Convert temperature from Celsius to Fahrenheit

1) Approach 1: Using normal way

# 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

# 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

Python Tutorial




Comments and Discussions!










Copyright © 2023 www.includehelp.com. All rights reserved.