Create a Simple Calculator in Python

In this Python lesson, we will practice how to write a program to make a simple basic calculator. This is not the type of electronic calculator we use every day. This type is the most basic which will help us to understand how the calculator works using condition/decision-making statements.

Example: Simple Calculator using +, *, -, /

# function to add two numbers
def add(x, y):
    return x + y

# function to subtract two numbers
def sub(x, y):
    return x - y

# function to multiply two numbers
def mul(x, y):
    return x * y

# function to divide two numbers
def div(x, y):
    return x / y

# accept operator input from user
opr = input('Choose an operator (a, s, m, d): ')


# Check if opr is one of the four options
if opr in ('a', 's', 'm', 'd'):
    num1 = float(input('Enter first number: '))
    num2 = float(input('Enter second number: '))

    if opr == 'a':
        print(num1, "+", num2, "=", add(num1, num2))

    elif opr == 's':
        print(num1, "-", num2, "=", sub(num1, num2))

    elif opr == 'm':
        print(num1, "*", num2, "=", mul(num1, num2))

    elif opr == 'd':
        print(num1, "/", num2, "=", div(num1, num2))
else:
    print("Invalid Operator")

Output

Choose an operator (a, s, m, d): m
Enter first number: 5
Enter second number: 7

5.0 * 7.0 = 35.0

In the above example, we request the user to first choose an operation symbol where a stands for addition, s stands for subtraction, m stands for multiplication and d stands for division. If the user inserts any other input apart from the expected values, the output will become “Invalid Operator”.

Do you want to become an expert programmer? See books helping our students, interns, and beginners in software companies today (Click here)!

Leave a Comment

Python Tutorials