How to make a basic calculator program in python



Expected question: Create a basic calculator program that can perform the basic arithmetic operations. The operation such as addition, subtraction, multiplication, and division depending upon the user input.

This program uses a function to create a basic calculator and each operation has its own function definition. The mathematical calculation is done based on the two numbers (a & b) entered by the user. Importantly, this program won’t let any exception pass silently. Therefore, the division by zero exception will be raised if you happen to divide any number by zero.

The calculator program teaches the concept of;

  1. functions
  2. operators
  3. conditional statements
  4. while loop

Source code:

import sys

def addition(a,b):
    add = a + b
    print(f"{a} + {b} = {add}")
    
def multiplication(a,b):
    mul = a * b
    print(f"{a} * {b} = {mul}")
    
def subtraction(a,b):
    sub = a - b
    print(f"{a} - {b} = {sub}")
    
def division(a, b):
    try:
        div = a / b
    except ZeroDivisionError as e:
        print("Exception raised: ",e)
    else:
        print("{} / {} = {:.2f}".format(a,b,div))

print("""
Calculator menu:
+ for addition
- for subtraction
* for multiplication
/ for division
q for Exit
""")

a = float(input("Enter number a:"))
b = float(input("Enter number b:"))

while True:
    operation = input("\nEnter an operator(+,-,*,/,q):")

    if operation == "+":
        addition(a,b)
        
    elif operation == "*":
        multiplication(a,b)
        
    elif operation == "-":
        subtraction(a,b)
        
    elif operation == "/":
        division(a,b)
        
    elif operation == "q":
        print("Calculator closed!")
        sys.exit()
        
    else:
        print("Wrong operator!")



Output:

Calculator menu:
+ for addition
- for subtraction
* for multiplication
/ for division
q for Exit

Enter number a:10
Enter number b:5

Enter an operator(+,-,*,/,q):+
10.0 + 5.0 = 15.0

Enter an operator(+,-,*,/,q):-
10.0 - 5.0 = 5.0

Enter an operator(+,-,*,/,q):*
10.0 * 5.0 = 50.0

Enter an operator(+,-,*,/,q):/
10.0 / 5.0 = 2.00

Enter an operator(+,-,*,/,q):q
Calculator closed!

>>> 
Calculator menu:
+ for addition
- for subtraction
* for multiplication
/ for division
q for Exit

Enter number a:5
Enter number b:0

Enter an operator(+,-,*,/,q):/
Exception raised:  float division by zero

Enter an operator(+,-,*,/,q):q
Calculator closed!