Class 12: Using Libraries 4

By: Archana Shukla and Rajesh Shukla

Example: 2

This is a menu-driven program
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)

Filename: menu1.py

Using this program the function in the above module are imported and used.

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

Example:3

In this example, we have module containing functions returning values

filename: example2.py

def sum(a,b):
    s=a+b
    return(s)

def prod(a,b):
    p=a*b
    return(p)

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

def max(a,b,c):
    if (a>b and a>c):
        m=a
    else:
        if(b>c):
            m=b
        else:
            m=c
    return(m)

Now we make a file from which the function of the above module are accessed.

filename: menu2.py

import example2

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. max of 3 nos")
    print("5. Exit")
    print("enter your choice ")
    ch=int(input())
    if(ch==1):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        c=example2.sum(a,b)
        print("Sum = ",c)
    elif(ch==2):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        c=example2.prod(a,b)
        print("prod = ",c)
    elif(ch==3):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2nd no "))
        c=example2.diff(a,b)
        print("diff = ",c)
    elif(ch==4):
        a=int(input("Enter 1st no "))
        b=int(input("Enter 2 nos "))
        c=int(input("Enter 3rd no "))
        c=example2.max(a,b,c)
        print("max no = ",c)
        
    elif(ch==5):
        print("Thank you")
        break
    else:
        print("Invalid choice")