Head add

Calculator Program in Python using while loop

In this program, we are going to create a calculator program in python using while loop and functions.
  According to the input by the user, it will perform addition, subtraction, multiplication, and division of two numbers.

Calculator Program in Python using while loop

We will make a calculator by making a menu-driven program in python for addition, subtraction, multiplication, and division of two numbers.
def addition(num1,num2):
    print("Addition=",num1+num2)

def subtraction(num1,num2):
    print("Subtraction=",num1-num2)

def multiplication(num1,num2):
    print("Multiplication=",num1*num2)

def division(num1,num2):
    print("Division=",num1/num2)

while True:
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")    
    print("5. Exit")
    choice=int(input("Enter your choice(1-5):"))

    if choice==1:
        num1=int(input("Enter 1st Number:"))
        num2=int(input("Enter 2nd Number:"))
        addition(num1,num2)


    elif choice==2:
        num1=int(input("Enter 1st Number:"))
        num2=int(input("Enter 2nd Number:"))
        subtraction(num1,num2)
    
    elif choice==3:
        num1=int(input("Enter 1st Number:"))
        num2=int(input("Enter 2nd Number:"))
        multiplication(num1,num2)
    
    elif choice==4:
        num1=int(input("Enter 1st Number:"))
        num2=int(input("Enter 2nd Number:"))
        if num2 == 0:
            print('Infinity')
        else:
            division(num1,num2)
                
    elif choice==5:
        break
    else:
        print("Wrong Choice")

Calculator Program in Python using while loop

Output:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit Enter your choice(1-5):1
Enter 1st Number:2
Enter 2nd Number:6
Addition= 8

Quick algorithm for Calculator Program in Python:
  • Print the menu for those arithmetic operations that our program can perform i.e, addition, subtraction, multiplication, and division.
  • Take the input from the user.
  • According to his/her choice, display the answer of the arithmetic operation using the if-else statement.
For ex: 
    if choice==1:
        num1=int(input("Enter 1st Number:"))
        num2=int(input("Enter 2nd Number:"))
        addition(num1,num2)
 

About this Program:

We made a simple calculator program in python using while loop, if-else statements, and functions. According to the choice of the user, this program can add, subtract, multiply and divide the two numbers. It is also a menu-driven program to perform arithmetic operations in python.

Siddharth Jha
• Hackerrank 5* • Full Stack Developer • Masters in SEO

Related Posts

Post a Comment