Python Modules 2

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
>>>

Method:3
importing all the function at the same time
from module_name import *

filename: m3.py

from example1 import *

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

#2(using user 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 2
Enter 2nd no 3
sum = 5
prod = 6
diff = 1
>>>

Method:4
importing the function with different names

from module_name impory function_name as user_defined_name

filename: m4.py

from example1 import sum as s
from example1 import prod as p
from example1 import diff as d

#1(without input)

s(10,20)
p(10,20)
d(10,20)

#2(using user input)

a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
s(a,b)
p(a,b)
d(a,b)

Output:


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

Visitor Counter

0051022