Python Recursion Function , Lambda Function

 Python Recursion Function , Lambda Function



 Arbitrary Argument

*args( Non Keyword Arguments)

 If you dont know how many arguments that has to be passed in to function then 

we can add '*' before the parameter name in function definition if number of arguments  are unknown then we can use arbitrary argument just by using before the argument name in function definition

For Example:

def arbfunction(*name):

    print("My name is",name)

arbfunction("manisha",'m','more')

 O/P:

My name is ('manisha', 'm', 'more')

In above example name is an srbitrary argument which is used with *. The arbfunction() allows to use many argument with it.

 Another Example on *args

def friends(*name):

    for i in name:

        print("Hello my friend",i)

friends("Rekha","Hema","Jaya")

 O/P:

Hello my friend Rekha

Hello my friend Hema

Hello my friend Jaya

 Another Example shows sum of variables by using *args.

def operations(*variables):

    sum=0 

    print(" The variables are:",variables)

    print("Sum is:")

    for i in variables:

        sum=sum+i

        print(sum)

operations(10,20,30,40)

 O/P:

The variables are: (10, 20, 30, 40)

Sum is:

10

30

60

100

 

Default Argument:

Default argument means compiler  will use the argument which is declared in function definition if no any argument value is passed. The default value is assigned by assignment operator ‘=’ in function definition.

For example

# Default argument

def myname(fname,mname='m',lname='more'):

  print(fname,mname,lname)

myname("manisha")

 O/P:

manisha m more

 Recursion Function in Python:

 Recursion Function means defined function can call itself.  Recursion is a simple programming concept which means function calls itself. It has disadvantage that it take more memory and time in its multiple calls.

 For Example,

def factorial(n):

    if n==1:

        return 1 

    else:

        return(n*factorial(n-1))

print("Factorial of given number is")

factorial(5)

O/P:

 Factorial of given number is

120

 Anonymous Function/ Lambda Function

A function which is defined without name is called anonymous function

normal user defined functions are defined with def keyword where anonymous function  is defined with lambda keyword.

 Syntax:

        lambda arguments:expression

Lambda functions have one or many arguments but have only one expression

 For Example,

 x= lambda num: num+100 

print("The sum is",x(200))

 O/P:

The sum is 300

 sum=lambda x,y:x+y

print("The sum is")

sum(20,40)

 O/P:

The sum is
60

Another Example to demonstrate Lambda function in Python 

a=int(input("Enter number"))

b=int(input("Enter number"))

#b=int(input("Enter number"))

sum=lambda a,b: a+b 

print("The sum is",sum(a,b))

 O/P:

Enter number20

Enter number20

The sum is 40

 

 

 

 

 

 

 

टिप्पणी पोस्ट करा

0 टिप्पण्या