Class 12: Using Libraries 2

By: Archana Shukla and Rajesh Shukla

Examples Of Python Modules

Example:1

filename: example1.py
The “example1.py” is created with a number of functions to perform various operations like sum of 2 nos, product of 2 nos, difference between 2 nos. and saved with the filename “example1.py”

def sum(a,b):
    s=a+b
    print("sum = ",s)

def prod(a,b):
    p=a*b
    print("prod = ",p)

def diff(a,b):
    if(a>b):
        d=a-b
    else:
        d=b-a
    print("diff = ",d)

Now want to use the functions stored in the module “example1.py”. there are different ways to use the functions.

Method: 1

import module_name

filename: m1.py

import example1

# 1(without input)

example1.sum(10,20)
example1.prod(10,20)
example1.diff(10,20)

# 2(with input)

a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
example1.sum(a,b)
example1.prod(a,b)
example1.diff(a,b)
Output:

sum = 30
prod = 200
diff = 10
Enter 1st no 25
Enter 2nd no 6
sum = 31
prod = 150
diff = 19
>>>

Method:2

from module_name imort function_name

filename: m2.py

from example1 import sum
from example1 import prod
from example1 import diff

# 1(without input)
sum(10,20)
prod(10,20)
diff(10,20)

# 2(using input)
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
sum(a,b)
prod(a,b)
diff(a,b)
Output:

sum = 30
prod = 200
diff = 10
Enter 1st no 10
Enter 2nd no 6
sum = 16
prod = 60
diff = 4
>>>

Number Of Visitors

0270413