Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

CHAPTER - 3

WORKING WITH FUNCTIONS


• Function can be defined as a named group of instructions that accomplish a specific task when it is

invoked.

• Basically it is a block of code which runs only when it is called.

• The use of function is one of the means to achieve modularity and reusability.

• Once defined, a function can be called repeatedly from different places of the program without writing

all the codes of that function every time , or it can be called from inside another function, by simply

writing the name of the function and passing the required parameters,

• The programmer can define as many functions as desired while writing the code.

• Modularity is breaking down the larger program to smaller code segments so as to reduce the

complexity and make it more simpler


Function definition:
• Defining the name and task of the function using the keyword def.
• Syn of a general function:
def functionname(parameter/s variable): #Function Header
“””<function docstring>””” #Function Body
Statement/s
return statement
• def means a function definition is starting.
• Identifier following “def” is the name of the function
• Information can be passed into functions as arguments. Also called Parameter. Arguments are specified after the function name, inside
the parentheses. You can add as many arguments as you want, just separate them with a comma. If no arguments then give empty
parenthesis. They are the values given to function. From a function's perspective it is the value that is sent to the function when it is
called.
• There is a colon at the end of def line, meaning it requires a block.
• Function docstring in the body of function is optional, but still it is good to include them. . It is for defining the comment about the
task of the function. We can retrieve it using the attribute __doc__ Eg: print(functioname.__doc__)
• The statements indented below the function (i.e block below def line), defines the functionality (working) of the function. This block is
also called body of the function.
• The value given from the function at the place of function call is called return value . The return statement returns the computed
results as return value. A function can return any number of values. If no return, then we need not give this statement. Anyhow,
default return value by Python is None
Function call:

• Given whenever we want the task of that function to be executed.

• A function defined can be called (invoked) any number of times at any part of the program.

• Syn : Depends on presence or absence of arguments and return.

>>> functionname() # For fn with no argument

>>> functionname(argument value) # For fn with argument

>>> varname/s=functionname() # For fn with return only.

>>> varname/s=functionname(args) # For fn with return and arguments

Note: The varname/s in function with return in the above two lines, are the variables where we want to assign

the value/s returned from the function . In case of multiple return values, we need to unpack them providing

variable names for each value returned.


EXAMPLE FOR FUNCTION WITH NO ARGUMENT AND NO RETURN

Function Definition Function call Output

def fn(): fn() Hello


“""Body part begins"""
print("Hello")

fn ("Manik") TypeError - because the function is not


defined with any parameter, cannot send any
value.
EXAMPLE FOR FUNCTION WITH ARGUMENT AND NO RETURN

Function Definition Function call Output

def fn(s): fn(“Manik”) Hello Manik


print("Hello“, s)
fn (10) Hello 10

fn() TypeError - because the function is defined


with a parameter and we should invoke
with a parameter.
fn(10,”Manik”) TypeError - because the function is defined
with one parameter and we should invoke
with only one parameter.
EX AMPLE FOR FUNCTION WITH ARBITRARY ARGUMENTS, * ARGS AND NO RETURN

• If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the items
accordingly.

Function Definition Function call Output

def fn(*s): fn(“Manik”) Hello ('Manik',)


print("Hello“, s) fn (10) Hello (10,)
fn() Hello ()
fn(1,2,”test”) Hello (1, 2, 'test')
EXAMPLE FOR FUNCTION WITH A RETURN BUT NO ARGUMENT
Note:
• While function call, the returned value can be assigned to a variable or can be used in any
calculations or any relational expressions or can be directly printed.

Function Definition Function call Output

def fn1(): X=fn1() #assigned to variable value is 100


s=100 print (‘value is’, X)
return s
print('value is’, fn1()) #directly print value is 100

X=200 + fn1() # used in calculation value is 300


print (‘value is’ , X)
EXAMPLE FOR FUNCTION WITH MULTIPLE RETURN BUT NO ARGUMENT
Note:
• While function call, each returned value must be assigned to different variables (unpack tuple), or give the
function call to directly print the resultant values which are in the form of a tuple

Function Definition Function call Output

def fn1(): x,y=fn1() value is 100 and 40


s=100 print('value is',x,'and',y)
return s,40 print('values are’, fn1()) values are (100, 40)
X=200 + fn() TypeError because integer
and tuple (function result)
cant be concatenated
t=(5,) values are (5, 100, 40)
x=t+fn1()
print('values are',x)
EXAMPLE FOR FUNCTION WITH BOTH RETURN AND ARGUMENT

Function Definition Function Call

def fn1(s): print('Value after return is’, fn1(10))


print('value brought inside the function’, s) “”” can also be -
s=s+100 n=fn1(10)
return s print(“Value after return is”,n) “””
Output

value brought inside the function 10


Value after return is 110
STRUCTURE OF A PYTHON PROGRAM
• Generally all function definitions are given at the top followed by the statements which are not
part of any functions.
• These statements which fall outside the indent of function are often called top-level statements.
• Internally Python gives a special name to top-level statements as _main_
• Python interpreter starts the execution of a program from the top-level statements which are part
of the main program.
• print( __name__ ) - will display __main__
Example for defining a function and invoking it within main of python program

#fn definition
Output will be:
def fn(): Inside __main__

print("Hello") Hello

#top - level statements begins

print(‘Inside’, __name__)

fn() #function call

Note:
• The function calling another function is called the caller and the function being called is the called
function (or callee).
• In the above code __main__ is the caller of callee fn()
FLOW OF EXECUTION IN A FUNCTION CALL
The flow of execution refers to the order in which statements are executed during a program run.
• Program execution begins with first statement of __main__ segment.
• Comment lines if any are ignored.
• Python just executes the function header line to determine that it is proper function header and ignores all lines
in the function body initially. The statements inside function body are not executed until the function is invoked.
• In python,, a function can define another function inside it. But, since the inner function definition is inside a
function-body, the inner definition isn’t executed until the outer function is called.
• When a code-line contains a function-call, program control first jumps to the function header line and then to the
first line of the function-body and starts executing its statements creating an execution frame for that function.
• A function ends with a return statement or the last statement of the function body, whichever occurs earlier.
• If the called function returns a value (using return statement), then the program control will jump back to the
function call statement and completes it by replacing the function call statement with the return value.
• If the called function doesn’t return any value, then the program control jumps back to the line following the
function call statement.
ARGUMENTS AND PARAMETERS
• Arguments : -Values being passed through function call statement. Also called
actual parameters or actual arguments. They can be literals, variables (containing
value) or expressions.
– Eg :
fn(“Manik”)
fn(10)
n=10
fn(n) - Here “Manik”, 10 or variable “n” are known as actual parameter/argument.
• Parameters : - Values being received in function definition header. Also called
formal parameters or formal arguments. They must be some names or identifiers
only (i,e, variables) to hold incoming values. It cannot have an expression.
– Eg: def fn(s) - In this function header, identifier “s” refers to formal parameter.
– We cannot write definition as: - def fn(a+10) , as parameter cannot be expression
• If you are passing values of immutable types to the called functions, then the called
function cannot alter the values of passed arguments. But, if you are passing values
of mutable types then called function would be able to make changes in them.
• Function call mechanism is of two types: - Mutability and Immutability of
arguments/parameters to a function plays a important role here.
– Call by Value : The called function makes a separate copy of passed parameters and then works with them.
So original values remain unchanged in the __main__ program. Immutable types implement this.
– Call by Reference : The called function works with original arguments passed to it. So any changes made
with them inside the function will take place in original arguments itself. Mutable types implement this.
– Eg: -
Call by Value: Call by Reference:

def fn(a): def fn(a):


a=a+100 a[0]+=100
print('value inside the function’, a) print('value inside the function’, a)
a=10 a=[10]
fn(a) fn(a)
print("Value after function call", a) print("Value after function call", a)

O/p will be: O/p will be:


value inside the function 110 value inside the function [110]
Value after function call 10 Value after function call [110]
MUTABLE/IMMUTABLE PROPERTIES OF PASSED DATA OBJECTS
def fn(a):
print('value brought is',a)
t=[10,20] o/p will be:

a=t value brought is [10]


print('value inside the function',a) value inside the function [10, 20]
Value after function call [10]
a1=[10]
fn(a1)
print("Value after function call",a1)

Note:
• Changes in immutable types are not reflected in the caller function at all.
• Changes in any mutable type of parameter are reflected in caller function if its name is not assigned a
different variable or datatype.
PASSING PARAMETERS

Three types of formal argument/parameters:

1. Positional arguments (Required arguments).

2. Default arguments

3. Keyword (or named) arguments


1. POSITIONAL ARGUMENTS
The function call statement must match the number and order ( or position) of arguments as
defined in the function definition. This is called Positional argument matching.
This way of argument specification is also called Required arguments or mandatory arguments as
no value can be skipped from the function call nor we change the order
Eg:
def fn(a,b,c): #function header
:
Then possible function calls can be: -
1. fn( x, y, z ) # 3 values (all variables) passed.
2. fn( 2, x, y) # 3 values( literal + variables) passed
3. fn(2, 5, 7) # 3 values( all literals) passed
2. DEFAULT ARGUMENTS
• A parameter having default value in the function header is known as a default parameter. A
default value is a value that is pre-decided and assigned to the parameter when the function call
does not have its corresponding argument.
• We can assign default value/s to a function’s parameter/s, which will be used in case a matching
argument is not passed in the function call statement.
• A parameter having a default value in function header becomes optional in function call.
Function call may or may not have value for it.
• The default values for parameters are considered only if no value is provided for that
parameter in the function call statement.
• Non-default arguments cannot follow default argument. i. e in a function header, any parameter
cannot have a default value unless all parameters appearing on its right have their default values.
• Default arguments are useful in situations where some parameters always have the same value.
Also they provide greater flexibility to the programmers but still we cannot change the order of
arguments in the functioncall.
• They can be used to add new parameters to the existing functions and combine similar
functions into one.
EXAMPLE FOR DEFAULT ARGUMENT
# Function Header in the definition - with default value for parameter rate
def interest(prin, time, rate=0.10):
:
:
# Function call statements for the above function definition can be: -
interest(10000, 20) # Uses default value for rate parameter (as that parameter is missing).
interest(1000, 3, 0.75) # Ignores Default value of rate, instead takes rate as 0.75 as no missing parameter.
interest(1000) # Gives TypeError because - for one positional argument (i.e time) value is not passed.
interest (1000, 3, 0.8, 100) # TypeError because – number of parameters are more than definition.
Interest(3, 0.8) # takes prin as 3, time as 0.8 and rate default value 0.10
Note:
Imagine we want to set default value for prin then, we should have default value for time and rate also.
Otherwise it gives error for function header.
Eg:
def interest(prin=10000, time,rate): # is illegal – gives syntaxError
def interest(prin=10000, time=10,rate): # is illegal
def interest(prin=10000, time,rate=0.5): # is illegal
def interest(prin=10000, time=10,rate=0.5): # is legal –No error. In this case function call can be simply interest()
# Prg having a function defined to calculate simple interest
def interest(prin ,time=10, rate=0.10):
si=(prin*time*rate)/100
return si
print('Simple Interest with principle sent as argument’, interest(10000))
print('Simple Interest with principle and rate sent as argument’, interest(10000,2))
print('Simple Interest with all values sent for parameter’, interest(10000,2,0.75))

O/p will be:


Simple Interest with principle sent as argument 100.0
Simple Interest with principle and rate sent as argument 20.0
Simple Interest with all values sent for parameter 150.0
3. KEYWORD (NAMED) ARGUMENTS
• Keyword arguments are the named arguments with assigned values being passed in the function call
statement.

• It Provides complete control and flexibility over the values sent as arguments for the corresponding
parameters.

• We can write any argument in any order provided we name the arguments when calling the function.

• Example:

• Function call statements could be: -

 interest (prin=10000, time=2, rate=0.3)

 interest (time=2, prin=10000, rate=0.3)

 interest (time=2, rate=0.3 , prin=10000)

• All the above function calls are valid even if the order of arguments does not match with the order of
parameters defined in the function header.
USING MULTIPLE ARGUMENT TYPES TOGETHER
• We can combine multiple argument types in a function call following the rules stated below:

– An argument list must first contain positional argument followed by any keyword argument and then
default argument.

– Keyword argument should be taken from the required arguments preferably.

– Cannot specify a value for an argument more than once

• Eg: If the function call statements for the function interest() is given as: -

– interest(5000,time=4) # For prin it takes 5000 as positional argument, for time it takes 4 as keyword
argument and for rate it takes 0.10 as default argument.

• Instead if we give:

– interest(time=4, 5000) # Syntax Error - positional argument follows keyword argument.


RETURNING VALUES FROM FUNCTION

• There can be 2 types of function:

1. Function returning some value - known as non-void functions or fruitful functions

2. Function not returning any value – known as void functions


FUNCTION RETURNING SOME VALUES : -
• Value is returned using a return statement.
• The value to return can be a literal, a variable or an expression.
– Eg: return 10
return s
return N * * 3
• When such function is invoked the returned value is made available to the caller function/program, by internally substituting
the function call statement.
• Returned value should be assigned to a variable, or used in print statement or used in any relational/computational
expressions. Instead, if u simply give a standalone function call, we wont get any error. But, their return value is completely
wasted.
• A function can return multiple values . In this case we can either receive the returned values in form of a tuple variable or
we can directly unpack the received values of tuple by specifying the same number of variables on the left hand side of the
assignment in function-call statement.
• The return statement ends the function execution even if it is in the middle of the function. Example :-
def fn(a):
print(a)
return a
a=a+10
print (a)
>>>fn(100)

o/p will be: 100


FUNCTION NOT RETURNING ANY VALUES
• It may or may not have a return statement
• If a void function has a return statement, then it will not have any value or expression after the keyword
return. Hence, it takes the following form : return

Function call for above functions can be standalone statements: - Note:


greet() If we give:
greet1(“Kiran”) print(greet())
quote() o/p will be :
prinsum(10,20,30) helloz
None
• The void functions do not return any value, but they return a legal empty value of Python
i.e None.
• If need be, we can assign this function somewhere as per our needs.
• Eg:

def fn(a): def fn(a):


print(a) return a
return
print(fn(100))
print(fn(100))

o/p will be:


o/p will be:
100
None 100
# P r o g r a m t o i n p u t t wo n u m b e r s . P e r f o r m b a s i c m a t h e m a t i c a l c a l c u l a t i o n s u s i n g a
function that returns all those calculated values. Display the results unpacking the
return
# Function Definition begins
def calc(n1,n2): o/p will be:
sum=n1+n2
diff=n1-n2 Enter a number:5
mul=n1*n2
Enter another number:3
quo=n1/n2
Sum of 5 and 3 is 8
rem=n1%n2
return sum,diff,mul,quo,rem Difference of 5 and 3 is 2
#prg part Product of 5 and 3 is 15
a=int(input("Enter a number:")) quotient of 5 and 3 is 1.6666666666666667
b=int(input("Enter another number:"))
Remainder of 5 and 3 is 2
t,d,m,q,r=calc(a,b) #unpacking during function call
print("Sum of", a, "and", b, "is",t)
print("Difference of", a, "and", b, "is",d)
print("Product of", a, "and", b, "is",m)
print("quotient of", a, "and", b, "is",q)
print("Remainder of", a, "and", b, "is",r)
FUNCTION COMPOSITION IN PYTHON
• Function composition is the way of combining two or more functions in such a way that the output of one
function becomes the input of the second function and so on.
• For example, let there be two functions “F” and “G” and their composition can be represented as F(G(x))
where “x” is the argument and output of G(x) function will become the input of F() function.

# Example Program
o/p will be:
#Function to add 2 to a number
def add(x): Adding 2 to 5 and multiplying the result with 2: 14
return x + 2

# Function to multiply 2 to a number


def multiply(x):
return x * 2

# Printing the result of composition of add and multiply


print("Adding 2 to 5 and multiplying the result with 2: ",multiply(add(5)))
SCOPE OF VARIABLE
• Part(s) of program within which a name is legal and accessible is called scope of the name.
• A global variable is a variable defined in the __main__ section. Such variables are said to have global
scope.
• A local variable is a variable defined within a function. Such variables are said to have local scope.
• A local scope can be multilevel.There can be enclosing local scope having a nested local scope of an
inside block
• Eg:

def fn(a,b): # names a,b and t are local variables o/p is:
t=a+b
return t sum is 8
n1=5 #names n1, n2 and s are global variables
n2=3
s=fn(n1,n2)
print('sum is',s)
Contd….
Local Variable scope
Enclosing Variable scope
Enclosing scope contd…
Note –
The nested function cannot be called from outside that enclosing
function
Global scope
Built_in scope
LEGB rule that
determines the
scope of a variable
O/p
Usage of the keyword global

O/p
NAME RESOLUTION
def fn(a,b):
t=a+b
print('value brought are',n1,n2) #global variable used
return t
n1=5
n2=3
s=fn(n1,n2)
print('sum is',s)
Same variable name in local scope and global scope

def fn(): def fn():


a=10 global a
print('value inside function', a) a=10
print('value inside function', a)
a=100
a=100
print('value in prg before function call',a)
print('value in prg before function call',a)
fn()
fn()
print('value in prg after function call’,a) print('value in prg after function call’,a)
o/p will be: o/p will be:
value in prg before function call 100 value in prg before function call 100
value inside function 10 value inside function 10
value in prg after function call 100 value in prg after function call 10
ASSIGNMENT
1) Write a function that takes amount in dollar as parameter, converts the amount to rupees and
then returns that amount in rupees.

2) Write a program to have following functions:

i. A function that takes a number as argument and calculates cube for it. The function does not return a
value. If there is no value passed to the function in function call, the function should calculate cube of 2.

ii. A function that takes two char arguments and returns true if both arguments are equal otherwise false.

Test both these functions by giving appropriate function call statements.

3) Create following functions:

i. A function u1() to display 15 dashes as a underline.

ii. A function u2(character,count) to display specific character specific number of times in a straight
line,
Answers to assignment questions given earlier
Alternate way to write the previos prg
Chapter 2 Assignment answers -
Write a program that creates a tuple of all the integers between 1 to
100, that are multiples of 3 and 5. Display the tuple
Write a program to create a dictionary to input n number of times the name
and age of a person, where n is accepted from user (for number of people).
Store the details in a Dictionary and at the end decide and display who is the
eldest of them.
O/p should be like:
O/p should be like:
Enter how many people:3
Enter name:Madhu
Enter the age:18
Enter name:Kiran
Enter the age:56
Enter name:Sunil
Enter the age:54
Prg is in next slide
Values stored are:
Madhu -18
Kiran -56
Sunil -54
Eldest person is: Kiran with age 56

You might also like