Class12_CS_Chapter7
Class12_CS_Chapter7
PYTHON FUNCTION
LEARNING
OBJECTIVES
Functions defined by
User-defined functions
the users themselves.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
def area(w,h):
return w * h
print (area (3,5))
Parameters Arguments
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
“Required Arguments” are the arguments passed to a
function in correct positional order.
Here, the number of arguments in the function call
should match exactly with the function definition.
You need at least one parameter to prevent syntax
errors to get the required output.
SYNTAX
def function_name(*args):
function_body
return_statement
EXAMPLE
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15)
EXAMPLES
def printnos (*nos): def adder(*num):
print for n in nos: sum = 0
return for n in num:
# now invoking the printnos()
sum = sum + n
function
print ("Printing two values") print("Sum:",sum)
printnos (1,2) adder(3,5)
print ('Printing three values') adder(4,5,6,7)
printnos (10,20,30) adder(1,2,3,5,6)
x = lambda a : a + 10
print(x(5))
x = lambda a, b : a * b
print(x(5, 6))
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
The return Statement
• The return statement causes your function to exit and
returns a value to its caller. The point of functions in
general is to take inputs and return something.
• The return statement is used when a function is ready
to return a value to its caller. So, only one return
statement is executed at run time even though the
function contains multiple return statements.
• Any number of 'return' statements are allowed in a
function definition but only one
return [expression list ]of them is executed at
run time.
This statement can contain expression which gets evaluated
and the value is returned. If there is no expression in the
statement or the return statement itself is not present inside
a function, then the function will return the None object.
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example
Overview of how recursive
function works
1. Recursive function is called by some external code.