User Defined Function: Part-Iv
User Defined Function: Part-Iv
PART-IV
“Different ways to import module in program”
and
“Types of User defined function”
Different ways for importing Module in a program
Suppose we have created a module “Area” in which we have defined
three functions circle(), triangle(), rectangle() to find the area of circle,
triangle and rectangle respectively.
# Program 1 : Area.py 1. import modulename
def circle(r):
Example:- import Area
ar = 3.14*r*r
return ar 2. import modulename as alias
Example:- import Area as Ar
def rectangle(l,b):
3. from modulename import *
ar = l*b
Example:- from Area import *
return ar
4. from modulename import functionname
def triangle(b,h): Example:- from Area import circle
ar = (b*h)/2
return ar
Different ways for importing Module in a program
Method – 1 : import modulename
# Program 1 : Area.py # Method:1
import Area
def circle(r):
a = Area.circle(2)
ar = 3.14*r*r
print(“Area of circle=“, a)
return ar
a = Area.rectangle(2,3)
def rectangle(l,b): print(“Area of rectangle=“, a)
ar = l*b
return ar a = Area.triangle(5,4)
print(“Area of triangle=“, a)
def triangle(b,h):
ar = (b*h)/2 Output:
return ar Area of circle=12.56
Area of rectangle=6
Area of triangle=10
Different ways for importing Module in a program
Method – 1 : import modulename
# Program 1 : Area.py # Method:2
import Area as Ar
def circle(r): a = Ar.circle(2)
ar = 3.14*r*r print(“Area of circle=“, a)
return ar
a = Ar.rectangle(2,3)
def rectangle(l,b): print(“Area of rectangle=“, a)
ar = l*b
a = Ar.triangle(5,4)
return ar
print(“Area of triangle=“, a)
def triangle(b,h):
Output:
ar = (b*h)/2
Area of circle=12.56
return ar
Area of rectangle=6
Area of triangle=10
Different ways for importing Module in a program
Method – 2 : from modulename import *
# Program 1 : Area.py # Method:3
a = rectangle(2,3)
def rectangle(l,b):
print(“Area of rectangle=“, a)
ar = l*b
return ar
a = triangle(5,4)
def triangle(b,h): print(“Area of triangle=“, a)
ar = (b*h)/2 Output:
return ar Area of circle=12.56
Area of rectangle=6
Area of triangle=10
Different ways for importing Module in a program
Method – 3 : from modulename import functionname
# Method:3
a = rectangle(2,3) #Error
print(“Area of rectangle=“, a)
a = triangle(5,4) #Error
print(“Area of triangle=“, a)
Output:
Area of circle=12.56
Types of User defined Function
# main # main
b, h = 10, 5 b, h = 10, 5
AreaTriangle(b,h) r = AreaTriangle(b,h)
print(“Area is “, r)
Output:
Output: Area is 25
Area is 25
3. Function with no arguments and 4. Function with no arguments and no
return type return type
# main # main
r = AreaTriangle( ) AreaTriangle( )
print(“Area is “, r)
Output: Output:
Area is 25 Area is 25
Thank You