Python Modules 3

Example:2

Here we want to create a module name “example1.py” which will contain functions of for the following operations:
1. Sum of 2 nos
2. Prod of 2 nos
3. Difference between 2 nos

And further, we will write a menu-driven program to access these functions from the module.

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)

Method:1
All the functions in the module are imported directly and used in the program.

syntax used to access functions

module.function_name

import example1

a=0
b=0
c=0
while True:
    print("1. sum of 2 nos")
    print("2. prod of 2 nos")
    print("3. diff between 2 nos")
    print("4. Exit")
    print("enter your choice ")
    ch=int(input())
    if(ch==1):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        example1.sum(a,b)
    elif(ch==2):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        example1.prod(a,b)
    elif(ch==3):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        example1.diff(a,b)
    elif(ch==4):
        print("Thank you")
        break
    else:
        print("Invalid choice")
      

Method:2
All the functions in the module are imported by using name and used in the program.

syntax used to access functions
function_name()

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


a=0
b=0
c=0
while True:
    print("1. sum of 2 nos")
    print("2. prod of 2 nos")
    print("3. diff between 2 nos")
    print("4. Exit")
    print("enter your choice ")
    ch=int(input())
    if(ch==1):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        sum(a,b)
    elif(ch==2):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        prod(a,b)
    elif(ch==3):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        diff(a,b)
    elif(ch==4):
        print("Thank you")
        break
    else:
        print("Invalid choice")
        
        

Python Basic Programming Tutorial

Python Introduction     Getting started in Python Programming      Python propgramming fundamentals     Python Operators    Python If Condition     Python for loop    Python range construct      Python While loop    break and continue statements     Different looping techniques     Python List     Python String     Python Functions    Python Inbuilt Functions     Python Recursion     Using Python Library     Python Tuples     Python Dictionary     Python Sets     Python Strings     Python Exception Handling     Python Data File Handling

Visitor Counter

0056688