The Anonymous Functions
These functions are called anonymous because they are
not declared in the standard manner by using the def
keyword.
use the lambda keyword to create small anonymous
functions.
Lambda forms can take any number of arguments but
return just one value in the form of an expression. They
cannot contain commands or multiple expressions.
cannot be a direct call to print because lambda requires
an expression
Have their own local namespace and cannot access
variables other than those in their parameter list and those
in the global namespace.
Syntax
• The syntax of lambda functions contains only
a single statement
lambda [arg1,arg2,.....argn]:expression
Use: Lambda functions are generally used as an
argument to a higher order function, i.e., a
function that takes in other functions as
arguments
Example
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
Result −
• Value of total : 30 Value of total : 40
Function with Return values
• The statement return [expression] exits a function, optionally passing back
an expression to the caller.
• A return statement with no arguments is the same as return None.
• Ex: Function area returns the area of a circle with the given radius:
import math
def circlearea( radius ) :
# the return stmt can also be written as :
return math . pi * radius ** 2
def circlecircumference ( radius ) :
circum = 2 * math . pi * radius
return circum
carea=circlearea ( 5 )
ccircum= circlecircumference ( 5 )
print ( carea , ccircum)
Function with Return values
•Multiple return statements can be used in branch statments:
•As these return statements are in an alternative conditional, only one will be executed.
•When the return statement is executed, the function terminates without executing any
subsequent statements.
•A code that appears after a return statement, or any other place the flow of execution can
never reach, is called dead code.
Function with Return values
Every possible path through the program hits a return statement.
For example:
def a b s o l u t e a l u e ( x ) :
if x < 0:
return −x
elif x >0:
return x
print ( ab so l u t e V a l u e ( −5))
This program is not correct because if x happens to be 0, neither
condition is true, and the function ends without hitting a return
statement.
In this case, the return value is a special value called None:
>>> print ( a b s o l u t e V a l u e ( 0 ))
None
S e p t e m b e r 26 , 2 0 1 7