Chapter 2 - Functions in Python
Chapter 2 - Functions in Python
What is Module?
A Module is a file that contains functions, classes and
variables. Example – math, random etc.
Functions
✔ These are also known as Subprogram.
✔ These can be built in, module function or user
defined function.
✔ These takes some arguments and returns some
value.
✔ By default these return None.
Advantages
➢It reduces program size. (i.e, Reuse of existing
code)
➢Big and complex program is broken down into
smaller programs (Subprograms).
➢Less memory is required to run program (using
local variables).
Types of Functions
Built in functions (Standard Library Function)
These are pre defined functions which are available
for direct use.
Example – print(), read(), int(), input() etc.
Module functions (Functions inside module)
These functions are used when we import these
modules. import or from keyword is used to import
these modules.
Example
math module → pow(), fabs(), sqrt() etc.
random module → radom(), randrange(), randint()
and choice()
Example
def hello():
print(“Simple Function”)
print(“Second Statement”)
hello()
hello()
Output
Simple Function
Second Statement
Simple Function
Second Statements
def sum(a,b):
c= a+b
return c
print(sum(4,2))
p=sum(8,9)
Output
6
17
Arguments
These are the values given while Function Call.
Example
hello(10)
hello(14,16)
Output:
20
30
Types of Arguments
Positional/Required/Mandatory
def hello(a,b):
c=a+b
print(c)
hello(2,4) →Positional Arguments
Default Arguments
def hello(a, b=10, c=30): #Here b and c are Default Arguments.
print(a+b+c)
hello(5)
def hello():
print(“First type”)
hello()
def hello():
print(“It returns 100)
return 100
print(hello())
def hello(a,b):
print(a+b)
hello(4,6)
def hello(a,b):
print(“Argument and return both”)
return(a+b)
print(hello(2,6))
Flow of Execution
Example
1 def hello(a, b):
2 print(a+b0
3 return a+b+4
4 print(“Hello”)
5 t=hello(8,2)
6 print(hello(4,6))
1→4→5→1→2→3→5→6→1→2→3→6
Scope of Variables
Parts of program in which a variable can be used is
called scope of that variable.
Global Scope
Variable that are declared in Top Level Segment (i.e,
main).
These are not declared inside function’s body.
These can be used anywhere within a program.
Local Scope
Variables that are declared inside functions have local
scope.
They cannot be used outside body of a function.
def hello():
a=4 →Local Scope
print(a,p)
p=90 →Global Scope
print(p)
Lifetime of a Variable
The time for which a variable remains in the memory
is called lifetime of a variable.
Global Keyword
Global keyword is used inside a user defined function
definition to create a global variable inside a user
defined function.
def hello():
global a
a=10
m=20
print(a, m)
hello()
print(a, m) #Here a will print value (10) and m will give an error.