Kahibaro
Discord Login Register

Simple calculator

Planning the Simple Calculator

In this mini project, you will build a text-based calculator that can:

You will use concepts you already know: variables, input, if/elif/else, loops, and basic functions.

A good way to think about this project is to break it into small steps:

  1. Show a menu of options (add, subtract, multiply, divide, quit).
  2. Get the user’s choice.
  3. If they chose to quit, stop the program.
  4. If they chose a valid operation:
    • Ask for the numbers.
    • Perform the calculation.
    • Show the result.
  5. If they chose something invalid, show an error message.
  6. Repeat from step 1.

You can later improve it by:

Basic Version: One Operation at a Time

Start with the simplest version: choose an operation, enter two numbers, get the answer, then the program ends.

print("Simple Calculator")
print("------------------")
print("Choose an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter your choice (1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == "1":
    result = num1 + num2
    print("Result:", result)
elif choice == "2":
    result = num1 - num2
    print("Result:", result)
elif choice == "3":
    result = num1 * num2
    print("Result:", result)
elif choice == "4":
    result = num1 / num2
    print("Result:", result)
else:
    print("Invalid choice")

Things to notice:

Adding a Loop: Calculator That Keeps Running

Next, make the calculator repeat until the user chooses to quit. A common pattern:

while True:
    print("\nSimple Calculator")
    print("------------------")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("5. Quit")
    choice = input("Enter your choice (1/2/3/4/5): ")
    if choice == "5":
        print("Goodbye!")
        break
    if choice not in ("1", "2", "3", "4"):
        print("Invalid choice, please try again.")
        continue
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))
    if choice == "1":
        result = num1 + num2
    elif choice == "2":
        result = num1 - num2
    elif choice == "3":
        result = num1 * num2
    elif choice == "4":
        result = num1 / num2
    print("Result:", result)

New ideas in this version:

Handling Division by Zero

If the user tries to divide by zero, Python will raise an error. You can prevent that with a simple check before dividing.

Modify just the division part:

elif choice == "4":
    if num2 == 0:
        print("Error: Cannot divide by zero.")
        continue
    result = num1 / num2

Full loop with this check included:

while True:
    print("\nSimple Calculator")
    print("------------------")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("5. Quit")
    choice = input("Enter your choice (1/2/3/4/5): ")
    if choice == "5":
        print("Goodbye!")
        break
    if choice not in ("1", "2", "3", "4"):
        print("Invalid choice, please try again.")
        continue
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))
    if choice == "1":
        result = num1 + num2
    elif choice == "2":
        result = num1 - num2
    elif choice == "3":
        result = num1 * num2
    elif choice == "4":
        if num2 == 0:
            print("Error: Cannot divide by zero.")
            continue
        result = num1 / num2
    print("Result:", result)

Organizing Code with Functions

To make your calculator easier to read and extend, you can split it into functions:

This is good practice for structuring slightly larger programs.

def show_menu():
    print("\nSimple Calculator")
    print("------------------")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("5. Quit")
    return input("Enter your choice (1/2/3/4/5): ")
def get_number(prompt):
    return float(input(prompt))
def add(a, b):
    return a + b
def subtract(a, b):
    return a - b
def multiply(a, b):
    return a * b
def divide(a, b):
    if b == 0:
        print("Error: Cannot divide by zero.")
        return None
    return a / b
while True:
    choice = show_menu()
    if choice == "5":
        print("Goodbye!")
        break
    if choice not in ("1", "2", "3", "4"):
        print("Invalid choice, please try again.")
        continue
    num1 = get_number("Enter first number: ")
    num2 = get_number("Enter second number: ")
    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)
    if result is not None:
        print("Result:", result)

Here you can clearly see:

Simple Input Validation (Optional Improvement)

If the user types something that is not a number, float(...) will raise an error. You can handle this with try / except and a loop that keeps asking until a valid number is entered.

Replace get_number with this version:

def get_number(prompt):
    while True:
        value = input(prompt)
        try:
            return float(value)
        except ValueError:
            print("That is not a valid number, please try again.")

Now your calculator is more robust: it will not crash when the user types text instead of a number.

Possible Extensions

Once the basic calculator works, try adding features like:

You don’t need to add everything at once. The important part of this mini project is:

Views: 17

Comments

Please login to add a comment.

Don't have an account? Register now!