Ch 02 Functions 02
Ch 02 Functions 02
1
25-06-2024
NOTE : “void functions” may display something Python follows a particular style of
on the screen or have some other effect, but they indentation to define the code. Since, Python
don’t have a return value. If we try to assign the functions don’t have any explicit beginning or
result of such a function to a variable, we get a end, like curly braces to indicate the start and
special value called “None”. stop for the function, they have to rely on this
NOTE : A Python function can be called directly indentation.
from the “Python shell”.
NOTE : User – Defined functions (UDFs) in Python PROGRAM – 2 :
are called or invoked by using only the function >>> def func1( ) :
name. print ( “I am Learning Functions in Python.”)
Significance of Indentation (Spaces) in Python:
Indentation rules to declare Python When we write “print( )” function right below the
functions are applicable to other elements of “def func1( )”, it will show an “Indentation Error :
Python as well like declaring conditions, loops or expected an indented block”.
variable. 7 8
2
25-06-2024
PROGRAM – 7 : Write a Python PROGRAM to ADD NOTE: In the above program , we have used a
and SUBTRACT two values and to return them. single return statement to return the two values at
the same time.
# Program to illustrate return statement returning
# multiple values. PROGRAM – 8 : Write a Python PROGRAM to
perform all the four basic operations and to return
them.
def add_diff (x , y) :
# Program to calculate Addition , Subtraction,
add = x + y
# Multiplication & Division and return those values.
diff = x – y
def calc(a , b) :
return add , diff
add = a + b
a , b = add_diff (200 , 100)
sub = a – b
print(“The sum of two numbers is : ”, a)
multi = a * b
print(“The diiferences of two numbers is : ”, b)
15 div = a / b 16
return add , sub , multi , div NOTE: A function may or may not return a value. In
nutshell, while creating functions, we can use two
result = calc ( 500 , 40) keywords:
print (“ The results obtained are : ”) 1. ‘def’ (mandatory)
for i in result : 2. ‘return’ (optional)
print ( i )
PROGRAM – 9 : Write a Python program to
implement calculator functions using the concept
OUTPUT :
of modules. (Alternative method of program – 8).
The results obtained are :
540
We will first create a module named ‘calculate.py’
460 as per the code given below. Then we shall call this
20000 module through Python shell prompt.
12.5 17 18
3
25-06-2024
PROGRAM – 9 : OUTPUT :
# Program to implement “calculate” module >>> import calculate #invoking ‘calculate’ module
>>> calculate.add(5 , 20)
def add(a , b): 25
return a+b >>> calculate.diff(5 , 20)
def diff(a , b) : –15
return a – b >>> calculate.mult(5 , 20)
def mult(a , b) : 100
return a * b >>> calculate.div(5 , 20)
def div(a , b) : 0.25
return a / b >>> calculate.rem(5 , 20)
def rem(a , b) : 0
return a // b 19 20
4
25-06-2024
However, the user is free to change the second Here, ‘x’ & ‘y’ are formal arguments whereas 20 &
argument from its default value : For Ex. : 30 are actual arguments.
>>> f1(2 , a=2) # f1(2,2) would also work. On the basis of above example, four types of
If there is a function with many parameters and we “Actual Arguments” are allowed in Python :
want to specify only some of them in function call, (a.) Positional Arguments.
then value for such parameters can be provided by (b.) Default Arguments
using their name, instead of the position (order). (c.) Keyword Arguments
This is called “Keyword Argument”.
(d.) Variable Length Arguments
Types of Arguments :
Consider the following example :
(a.) Positional Arguments :
def f1( x , y ) :
Positional arguments are arguments passed
------------------ to a function in correct positional order.
------------------ FOR EX. :
f1(20,30) 25 26
5
25-06-2024
While using keyword arguments, the following points (8.) We cannot have a parameter on the left with default
should be kept in mind : argument value without assigning default values to
(1.) An argument list must have any positional parameters lying on its right side.
arguments followed by any keyword arguments.
(2.) Keywords in argument list should be from the list of (d.) Variable Length Arguments :
parameters name only. As the name suggests, in certain situations, we
(3.) No parameter should receive value more than once. can pass variable number of arguments to a function.
(4.) Parameter names corresponding to positional Such type of arguments are called variable length
arguments cannot be used as keywords in the same arguments.
calls. Variable length arguments are declared with * (asterisk)
(5.) The default value assigned to the parameter should symbol in Python as follows :
be a constant only. >>> def fun1( *n ) :
(6.) Only those parameters which are at the end of the We can call this function by passing any number of
list can be given default value. arguments, including zero number. Internally, all these
(7.) The default value is evaluated only once at the point values are represented in the form of a tuple.
35 36
of function definition.
6
25-06-2024
7
25-06-2024
NOTE : NOTE :
(1.) We can use the same names in different scopes. (2.) Changing a global name used in a function
For Ex. : definition changes the function.
>>> a = 2 For Ex. :
>>> def f2(x , y): >>> a = 2
a=x+y >>> def f( x ) :
b=x–y return x + a # this function is , effectively, f(x)=x+2
NOTE : It can also make our program easier for non – Python
(3.) Unlike some other languages, Python function programmers to read.
arguments are not modified by default. For Ex. :
For Ex. : def hello( ):
>>> x = 4 print (“Hello , World”)
def main( ) :
>>> f (x)
print (“ This is the main( ) function.”)
5
hello( )
>>> x
Function Call :
4
>>> main( )
Using main() as a function :
Including a main() function is not mandatory in Python. It
OUTPUT :
can structure our Python programs in a logical way that
puts the most important components of the program into This is the main( ) function.
one function. 45
Hello , World 46
NOTE : RECURSION :
It is remembered that a function does not execute until it Recursion is one of the most powerful tools in a
is invoked, whether it is main( ) or any other user – programming language. Recursion is the property of a
defined function. function to call itself again and again and such types of
Flow of execution of program containing Function Call : function is called “Recursive Function”.
Execution always begins at the first statement of the
program. Statements are executed one at a time, starting Disadvantages of using Recursion :
from the top to bottom. Function definition does not alter (1.) It consumes more storage space because the
the flow of execution of a program, as the statements recursive calls along with local variables are stored on
inside the function is not executed until the function is the stack.
called. (2.) The computer may run out of memory if the
On a function call, instead of going to the next statement recursive calls are not checked.
of the program, the control jumps to the body of the (3.) It is less efficient in terms of speed and execution
function, executes all statements of the function, time.
starting from the top to the bottom and then comes back
to the point where it left off. 47 48
8
25-06-2024
PROGRAM : 1 a=2
Write a Python program using recursive function to print ( power ( a , 4 ))
implement the power( ) function.
49 OUTPUT : 16 50
9
25-06-2024
# Program for Binary Search in a List/Array using List = [ 5, 11, 22, 36, 99, 101 ]
# Recursion print (bin_search (list, 0, 5, 36))
def bin_search(list, low, high, val) :
print (bin_search (list, 0, 5, 100))
if high < low :
return None
else: OUTPUT :
midval = low + (( high – low ) // 2) 3
# Compare the search item with middle most value None
if list[midval] > val:
return bin_search( list, low, midval–1, val)
elif list[midval] < val :
return bin_search( list, midval+1, high, val)
else :
return midval 57 58
59
10