Functions in Python
Salil Verma (PGT IT)
Jawahar Navodaya Vidyalaya, Adilabad (T.S)
Hyderabad Region
Navodaya Vidyalaya Samiti
Contents
1 Function 2
1.1 Syntax for Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Example:Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Anatomy of Python function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Python Function types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Arguments and Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.6 Passing parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.6.1 Positional/Required Arguments . . . . . . . . . . . . . . . . . . . . . . . 4
1.6.2 Default Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6.3 Keyword (Named) Arguments . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6.4 Rules for using multiple argument types together . . . . . . . . . . . . . 5
1.7 Returning values from functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7.1 Functions returning some values(non-void functions) . . . . . . . . . . . 5
1.7.2 Functions not returning any value(void functions) . . . . . . . . . . . . . 6
1.8 Returning multiple values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.9 Scope of variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.9.1 Global Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.9.2 Local Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.10 LEGB Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.11 Passing an immutable/mutable data types to a function . . . . . . . . . . . . . . 8
1.11.1 Passing an immutable type value(integer) to a function . . . . . . . . . . 8
1.11.2 Passing a mutable type value(List) to a function . . . . . . . . . . . . . . 9
1.11.3 Passing a mutable type value(List) to a function - Adding/Deleting items
to it . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.11.4 Passing a mutable type value(List) to a function - Assigning parameter
to a new value/variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.11.5 Summary of mutable/immutable type’s behaviour with functions . . . . 10
1
2 Using Python Libraries 11
2.1 Importing Modules in a Python program . . . . . . . . . . . . . . . . . . . . . . 11
2.2 Using Python standard library’s functions and modules . . . . . . . . . . . . . . 12
2.2.1 Using Python’s Built-in Functions . . . . . . . . . . . . . . . . . . . . . 12
2.2.2 Using random module . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1 Function
• A function is a portion of code within a larger program that performs a specific task.
• Functions are useful in reusing the code and eliminate code redundancy.
• Functions are also used to organise our code into manageable blocks.
1.1 Syntax for Function
def function name ( parameters ) :
””” d o c s t r i n g ”””
statement ( s )
return [ expression ]
1.2 Example:Function
f(x) a mathematical function
f (x) = x2
Above mentioned mathematical function f(x) can be written in Python like this:
def f ( x ) :
return x∗x
1.3 Anatomy of Python function
Let us dissect functions’ definition to know about various components.
• Function header: function definition starts with keyword def and ends with a colon(:),
specifies function’s name and its parameters
2
• Parameters: variables that are listed within parenthesis of a function header
• Function body: the block of statements/indented statements beneath function header
that defines the action performed by the function
• Indentation: the blank space in the beginning of a statement; All the statements within
same block have same indentation
1.4 Python Function types
pre-defined functions and are always available
Built-in for use. e.g. len(), type(), int(), input() etc.
pre-defined in particular modules and can only
defined in be used when the corresponding module is im-
modules ported e.g. math module contains sin() function
User-
defined by programmer
defined
1.5 Arguments and Parameters
Consider the following program:
def m u l t i p l y ( a , b ) : #Function h e a d e r
print ( a∗b )
y=3
multiply (12 , y) #Function c a l l 1
multiply (y , x) #Function c a l l 2
• Arguments vs Parameters:
– values being passed through function call are refered as Arguments /Actual Ar-
guments
– values being reveived through function definition are referred as Parameters /For-
mal Arguments
1.6 Passing parameters
Python supports three types of formal arguments/parameters:
1. Positional arguments (Required arguments)
3
2. Default arguments
3. Keyword (or named ) arguments
1.6.1 Positional/Required Arguments
In a function call statement, number and order of arguments matches with function definition,
this is called the positional argumenting. e.g.
i f a f u n c t i o n d e f i n i t i o n header i s l i k e :
def check ( a , b , c ) :
.
.
then p o s s i b l e f u n c t i o n c a l l s for t h i s can be :
check ( x , y , z ) # 3 values ( a l l v a r i a b l e s ) passed
check ( 2 , x , y ) # 3 v a l u e s ( l i t e r a l +v a r i a b l e ) p a s s e d
check ( 2 , 5 , 7 ) # 3 values ( a l l l i t e r a l s ) passed
1.6.2 Default Arguments
• Python allows us to assign default value(s) to a function’s parameter(s) which is useful
in case a matching argument is not passed in the function call statement.
• In a function header, any parameter cannot have a default value unless all parameters
appearing on its right have their default values.
e.g.
Example o f f u n c t i o n header with d e f a u l t v a l u e s :
def i n t e r e s t ( p r i n c i p a l , time , r a t e = 0 . 1 0 ) :
Function c a l l s for t he f u n c t i o n :
s i i n t =i n t e r e s t ( 5 4 0 0 , 2 ) #t h i r d argument m i s s i n g
s i i n t =i n t e r e s t ( 6 1 0 0 , 3 , 0 . 1 5 ) #no argument m i s s i n g
1.6.3 Keyword (Named) Arguments
• Keyword arguments are the named arguments with assigned values being passed in the
function call statement.
• We can write any argument in any order provided we name the arguments when calling
the function.
If f u n c t i o n header i s :
def i n t e r e s t ( p r i n , time , r a t e ) :
Function c a l l s u s i n g keyword arguments :
4
i n t e r e s t ( p r i n =2000 , time =2, r a t e =0.10)
i n t e r e s t ( time =4, p r i n =2000 , r a t e =0.10)
i n t e r e s t ( time =2, r a t e =0.12 , p r i n =2000)
1.6.4 Rules for using multiple argument types together
1. An argument list first contain positional(required) arguments followed by any keyword
argument.
2. We cannot specify a value for and argument more than once.
For instance, consider the following function header:
def i n t e r e s t ( p r i n , cc , time =2, r a t e = 0 . 0 9 ) :
return p r i n ∗ time ∗ r a t e
Call statements and their validity:
Function call statement Legal/illegal Reason
interest(cc=4,rate=0.12,prin=5000) legal with keyword arguments, we can
give values in any order
interest(rate=0.05,500,3) illegal keyword argument before posi-
tional arguments
interest(5000,prin=300,cc=2) illegal multiple values provided for prin;
once as positional and again as
keyword argument
1.7 Returning values from functions
1.7.1 Functions returning some values(non-void functions)
The value being returned can be one of the following:
• a literal, e.g. return 5
• a variable, e.g. return a
• an expression, e.g. return a+b/c
Important Point: The return statement ends a function execution even if it is in the
middle of the function. e.g.
def check ( a ) ;
a=math . f a b s ( a ) #1
return a #2
print ( a ) #3
statement 3 is unreacheble because check() function will end with return and control will
never reach this statement.
5
1.7.2 Functions not returning any value(void functions)
The functions that perform some action or do some work but not return any value or final value
to the caller are called void functions. e.g.
Example 1: void function but no return statement
def g r e e t ( ) :
print ( ” h e l l o ” )
Example 2: void function with a return statement
def prinsum ( a , b , c ) :
print ( ”sum : ” , a+b+c )
return
1.8 Returning multiple values
Unlike other programming languages, Python lets us return more than one value from a func-
tion.
• Either receive the returned values in form a tuple variable, i.e. shown below:
def s q u a r e d ( x , y , z ) :
return x∗x , y∗y , z ∗ z
t=s q u a r e d ( 2 , 3 , 4 )
print ( t )
OUTPUT: tuple t w i l l be p r i n t e d as : ( 4 , 9 , 1 6 )
• Or we can directly unpack the received values of tuple by specifying the same number of
variables on the left hand side of assignment operator in function call:
def s q u a r e d ( x , y , z ) :
return x∗x , y∗y , z ∗ z
v1 , v2 , v3=s q u a r e d ( 2 , 3 , 4 )
print ( v1 , v2 )
OUTPUT: 4 9
1.9 Scope of variables
Part(s) of program within which a name is legal and accessible, is called scope of the name.
There are broadly two kinds of scope in Python, as being discussed below:
1.9.1 Global Scope
A name declared in top level segment ( main ) of a program is said to have a global scope and
is usable inside the whole program and all blocks(functions, other blocks) contained within the
program.
6
1.9.2 Local Scope
A name declared in a function-body is said to have local scope i.e. it can be used only within
this function and the other blocks container under it. The names of formal arguments
also have local scope.
• Scope Example 1:
1. def calcsum ( x , y ) :
2. z=x+y #s t a t e m e n t 1
3. return z #s t a t e m e n t 2
4. num1=int ( input ( ” Enter f i r s t number : ” ) ) #s t a t e m e n t 1
5. num2=int ( input ( ” Enter second number : ” ) ) #s t a t e m e n t 2
6. sum=calcsum (num1 , num2) #s t a t e m e n t 3
7. print ( ”Sum o f g i v e n number i s ” ,sum) #s t a t e m e n t 4
Flow of execution of above program:
Line1 Line4 Line5 Line6 Line2 Line3 Line6 Line7
• Scope Example 2:
1. def calcsum ( a , b , c ) :
2. s=a+b+c #s t a t e m e n t 1
3. return s # statement2
4. def a v e r a g e ( x , y , z ) :
5. sm=calcsum ( x , y , z ) #s t a t e m e n t 1
6. return sm/3 #s t a t e m e n t 2
7. num1=int ( input ( ”Number 1 : ” ) ) #s t a t e m e n t 1
8. num2=int ( input ( ”Number 2 : ” ) ) #s t a t e m e n t 2
9. num3=int ( input ( ”Number 3 : ” ) ) #s t a t e m e n t 3
10. print ( ” Average o f t h e s e numbers i s ” , a v e r a g e (num1 , num2 , num3 ) ) #
Flow of execution of above program:
Line7
Line2 Line5
Line1 Line4 Line8 Line10 Line5 Line10
Line3 Line6
Line9
1.10 LEGB Rule
For every name reference within a program, Python follows name resolution rule, also known
as LEGB [Link] every name reference, Python does the following to resolve it:
1. It checks within its Local environment, if it has a variable with the same name; Python
uses its value. If not, then it moves to step (ii)
7
2. Python now checks the Enclosing environment; If yes Python uses its value.
If the variable is not found in the current environment, Python repeats this step to higher
level enclosing environment, if any.
If not, then it moves to step(iv).
3. Python now checks the Global environment. Whether there is a variable with the same
name; If yes Python uses its value. If not, then it moves to step(iv).
4. Python checks its Built-in environment that contains all built-in variables and functions
of Python, If there is a variable with the same name; If yes, Python uses its value.
Local Enclosing Global Built-in
1.11 Passing an immutable/mutable data types to a function
• Python’s variables are not storage containers, rather Python variables are like memory
references; they refer to the memory address where the value is stored.
• Depending upon the mutability/immutability of its data type, a variable behaves differ-
ently:
– If a variable is referring to an immutable type then any changes in its value will
also change the memory address it is referring to.
– If a variable is referring to mutable type then any change in the value of mutable
type will not change the memory address of the variable.
1.11.1 Passing an immutable type value(integer) to a function
#P a s s i n g an immutable t y p e v a l u e t o a f u n c t i o n .
def myfunc1 ( a ) :
print ( ”\ t I n s i d e myfunc1 ( ) ” )
print ( ”\ t Value r e c e i v e d i n ’ a ’ as ” , a )
a=a+2
print ( ”\ t Value o f ’ a ’ now changes t o ” , a )
print ( ”\ t r e t u r n i n g from myfunc1 ( ) ” )
# main
num=3
print ( ” C a l l i n g myfunc1 ( ) by p a s s i n g ’num ’ with v a l u e ” ,num)
myfunc1 (num)
print ( ”Back from myfunc1 ( ) . Value o f ’num ’ i s ” ,num)
8
OUTPUT:
NOTE: The value got changed from 3 to 5 inside function but not reflected back to main
1.11.2 Passing a mutable type value(List) to a function
# Passing a mutable type ( L i s t ) value to a f u n c t i o n
# Making c h a n g e s i n p l a c e
def myfunc2 ( m y l i s t ) :
print ( ”\n\ t I n s i d e c a l l e d f u n c t i o n now” )
print ( ”\ t L i s t r e c e i v e d : ” , m y l i s t )
m y l i s t [0]+=2
print ( ”\ t L i s t w i t h i n c a l l e d f u n c t i o n , a f t e r changes : ” , m y l i s t )
return
l i s t 1 =[1 , ” Adilabad ” , 1 0 0 ]
print ( ”\ n L i s t b e f o r e f u n c t i o n c a l l : ” , l i s t 1 )
myfunc2 ( l i s t 1 )
print ( ”\ n L i s t a f t e r f u n c t i o n c a l l : ” , l i s t 1 )
OUTPUT:
NOTE: The value got changed from [1,’Adilabad’,100] to [3,’Adilabad’,100] inside
function and changes got reflected back to main
1.11.3 Passing a mutable type value(List) to a function - Adding/Deleting items
to it
# Passing a mutable type ( L i s t ) value to a f u n c t i o n
# Adding / D e l e t i n g i t e m s t o i t
def myfunc3 ( m y l i s t ) :
print ( ”\ t I n s i d e c a l l e d f u n c t i o n now” )
print ( ”\ t L i s t r e c i e v e d : ” , m y l i s t )
m y l i s t . append ( 2 )
m y l i s t . extend ( [ 5 , 1 ] )
print ( ”\ t L i s t a f t e r adding some e l e m e n t s : ” , m y l i s t )
m y l i s t . remove ( 5 )
9
print ( ”\ t L i s t w i t h i n c a l l e d f u n c t i o n , a f t e r a l l changes : ” , m y l i s t )
return
l i s t 1 =[” H e l l o ” , 5 0 4 2 9 6 , ’ Adilabad ’ ]
print ( ”\ n L i s t b e f o r e f u n c t i o n c a l l : ” , l i s t 1 )
myfunc3 ( l i s t 1 )
print ( ”\ n L i s t a f t e r f u n c t i o n c a l l : ” , l i s t 1 )
OUTPUT:
NOTE: The value got changed from [1,’Adilabad’,100] to [3,’Adilabad’,100] inside func-
tion and changes got reflected back to main
1.11.4 Passing a mutable type value(List) to a function - Assigning parameter to
a new value/variable
#P a s s i n g a m u t a b l e t y p e ( L i s t ) v a l u e t o a f u n c t i o n
#A s s i g n i n g parameter t o a new v a l u e / v a r i a b l e .
def myfunc4 ( m y l i s t ) :
print ( ”\n\ t I n s i d e c a l l e d f u n c t i o n now” )
print ( ”\ t L i s t r e c e i v e d : ” , m y l i s t )
new = [ 3 , 5 ]
m y l i s t=new
m y l i s t . append ( 1 0 0 )
print ( ”\ t L i s t w i t h i n c a l l e d f u n c t i o n , a f t e r changes : ” , m y l i s t )
return
l i s t 1 =[”Yanam” , 5 3 3 4 6 4 , ’U.T. ’ ]
print ( ”\ n L i s t b e f o r e f u n c t i o n c a l l : ” , l i s t 1 )
myfunc4 ( l i s t 1 )
print ( ”\ n L i s t a f t e r f u n c t i o n c a l l : ” , l i s t 1 )
OUTPUT:
NOTE: The value got changed from [’Yanam’,533464,’U.T.’] to [’Yanam’,533464,’U.T.’]
inside function and changes did not get reflected back to main
1.11.5 Summary of mutable/immutable type’s behaviour with functions
• Changes in immutable types are not reflected in the caller function at all.
10
• Changes,if any, in mutable types
– are reflected in caller function if its name is not assigned a different variable or
datatype.
– are not reflected in the caller function if it is assigned a different variable or datatype.
2 Using Python Libraries
• A Library refers to a collection of modules that together cater to specific type of needs
or [Link] commonly used Python libraries are:
1. Python standard library: This library is distributed with Python that contains
modules for various types of functionalities. Some commonly used modules of Python
standard library are:
– math module; mathematical functions
– cmath module; mathematical functiions for complex numbers
– random module; generating pseudo-random numbers
– statistics module; mathematical statistics functions
– Urllibmodule; URL handling functions
2. NumPy library: some advance math functionalities alongwith tools to create and
manipulate numeric arrays.
3. SciPy library: offers algorithmic and mathematical tools for scientific calculations.
4. tkinter library: for creating userfriendly GUI interface.
5. Matplotlib library: plots, charts, graphs etc.
• A Python module is a file (.py file) containing variables, class definitions, statements
and functions related to a particular task.
– A module is independent grouping of code and data(variable, definitions, statements
and functions)
– can be re-used in other programs
– can depend on other modules
2.1 Importing Modules in a Python program
Python provides import statement to import modules in a program. The import statement
can be used in two forms:
1. To import entire module:
• To import a module e.g.
import time
• To import two modules viz. decimals and fractions e.g.
import decimals,fractions
• dot notation: Consider a module tempConversion contains a function to centigrade()
import tempConversion
[Link] centigrade(98.6)
11
• Using alias name
import tempConversion as tc
[Link](98.6)
2. Importing select objects from module:
• To import single object:
from math import pi print([Link])
• To import multiple object:
from math import sqrt,pow
• To import all objects of a module:
from math import *
2.2 Using Python standard library’s functions and modules
Python’s standard library also offers, other than the built-in functions, some modules for spe-
cialized type of functionality, such as math module for mathematical function;random module
for pseudo-random number generation;urllib for functionality of website address.
2.2.1 Using Python’s Built-in Functions
The Python interpreter has a number of functions built into it that are always available; you
need not import any module for them e.g. input(), int(), float(), type(), len() etc.
Mathematical and String Functions:
• oct(): returns octal string for a given number i.e. 0o + octal equivalent of a number.
• hex(): returns hex string for a given number i.e. 0x + hexadecimal equivalent of a num-
ber.
• int(): truncates the fractional part of given number and returns only the integer or whole
part.
• round(): returns number rounded to n digits after decimal points. If n digits is not
given, it returns nearest integer to its input.
12
• <str>.join():
– If the string based iterator is a string then <str> is inserted after every character of
the string.
– If the string based iterator is a list or tuple of a strings then, the given string/char-
acter is joined with each member of the list or tuple, But the tuple or list must have
all member.
• <str>.split():
– If you do not provide any argument to split then by default it will split the given
string considering whitespace as a separator.
– If you provide a string or a character as an argument to split(), then the given
string is divided into parts considering the given string/character as separator and
separator character is not included in the split strings.
13
• <str>.replace(): It replaces a string by a given string.
2.2.2 Using random module
Python has a module namely random that provides random-number generators. To use ran-
dom number generators in your Python program, you first need to import module random
using import command.
• random(): It returns floating point number N in the range [0.0,1.0), i.e. 0.0 ≤ N < 1.0
• randint(a,b): It returns a random integer N in the range (a,b), i.e. a ≤ N ≤ b
Let us consider some examples:
1. To generate a random floating-point number between 0.0 to 1.0
2. To generate a random floating-point number between 15.0 to 35.0
3. To generate a random integer number between 15 to 35
14