Python Program to Make a Simple Calculator

In this example, we will learn to make a simple calculator using the functions. To better understand this example, make sure you have knowledge of the following tutorials:-

Python Program to Make a Simple Calculator

def add(x, y):
    return x + y


def subtract(x, y):
    return x - y


def multiply(x, y):
    return x * y


def divide(x, y):
    return x / y


while True:
    print("#### CALCULATOR ####")
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))

    print("Select operation.")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")

    choice = input("Enter choice(1/2/3/4):")
    result = 0

    if choice == '1':
        result = add(num1, num2)
    elif choice == '2':
        result = subtract(num1, num2)
    elif choice == '3':
        result = multiply(num1, num2)
    elif choice == '4':
        result = divide(num1, num2)
    else:
        print("Invalid Input")

    print("Result = ", result)

    quit = input("Do you want to continue (y/n) ?")
    if quit == 'n':
        break

The output of the above program is:-

#### CALCULATOR ####
Enter first number: 5
Enter second number: 3
Select operation.
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice(1/2/3/4):1
Result = 8
Do you want to continue (y/n) ?n
Program Explanation:
Functions for performing the operations such as add, subtract, divide and multiply are defined using a def keyword which accepts two arguments and performs the action on them. The user input is taken for two numbers to be operated with choice of operation using number 1/2/3/4. The if-else conditions check the operation to be performed and call the required function to do the job. The result is printed and the user is asked if he/she wants to continue the calculation or stop.
SHARE Python Program to Make a Simple Calculator

You may also like...

Leave a Reply

Your email address will not be published.

Share