Monday, 6 January 2020

lambda function


Lambda function:
#without using Lambda
def square(x):
    n=x*x
    return n
#reading the value from the keyboard, store into x
x=int(input("enter any value "))
#call the function
n=square(x)
print("square of %i value is=%i"%(x,n))
"""
enter any value 4
square of 4 value is=16
>>> """
#By using lambda function
a=lambda n:n*n
n=int(input("enter n value"))
print("square root of %i=%i"%(n,a(n)))
"""
output:
enter n value4
square root of 4=16
>>> """     
Lambda function:
We can define by using lambda keyword. A function without a name is called ‘anonymous function” or Lambdas function, so far function were written by using function name and keyword ‘def’. But Lambda function can be used by using the keyword ‘lambda’.

Syntax: lambda arguments:expression

Example: lambda n:n*n

Advantages: Code can be reduced so that code readability can be improved.
Find sum of two numbers by using lambda function:
#sum of two numbers using lambda function
#lambda arguments:expression
s=lambda a,b:a+b
a=int(input("enter any value"))
b=int(input("enter any value"))
print("Sum of two nos are",s(a,b))
"""
output:
enter any value2
enter any value3
Sum of two nos are 5
"""
Note: (1)Lambda function internally returns expression value and we are not required to write return statement explicitly.
(2)sometimes we can pass function as actual parameter to another function, in such case we use lambda functions.
Find biggest of given numbers:
Syntax: lambda arguments:expression
Largest of two nos: Normal function:
def big(a,b):
  if a>b:
    print(“a is big”)
 else:
    print(“b is big”)
Largest of two nos: By using lambda function:
n=lambda a,b:a if a>b else b
print("big is",n(10,20))
"""output:
big is 20""

Related video: https://youtu.be/8TVWQwEkcFg
Next: 
Previous: Tower of Hanoi

https://www.youtube.com/playlist?list=PL2mD2CO8TKlJdFbbtuhTXPQk2tNQx0pb1

No comments:

Post a Comment

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...