Table of Contents
Planning the Simple Calculator
In this mini project, you will build a text-based calculator that can:
- Ask the user which operation to perform
- Ask for one or two numbers (depending on the operation)
- Perform the calculation
- Show the result
- Keep running until the user chooses to quit
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:
- Show a menu of options (add, subtract, multiply, divide, quit).
- Get the user’s choice.
- If they chose to quit, stop the program.
- If they chose a valid operation:
- Ask for the numbers.
- Perform the calculation.
- Show the result.
- If they chose something invalid, show an error message.
- Repeat from step 1.
You can later improve it by:
- Handling invalid number input
- Handling division by zero
- Organizing code into functions
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:
- All user input starts as text (strings), so we convert the numbers with
float(...)so the calculator can handle decimals. - The operation is chosen using
if/elif/else. - There is no loop yet: after one calculation, the program ends.
Adding a Loop: Calculator That Keeps Running
Next, make the calculator repeat until the user chooses to quit. A common pattern:
- Use a
while True:loop. - Inside, show the menu and handle the choice.
- Use
breakto exit the loop when the user wants to quit.
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:
- Using
continueto skip the rest of the loop and start over for an invalid choice. - Moving the repeated menu into the loop so it shows every time.
- Using the same variables (
num1,num2,result) again on each loop.
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 / num2Full 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:
- A function to show the menu and get a valid choice.
- A function to ask for a number.
- Separate functions for each operation (add, subtract, multiply, divide).
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:
- The loop is now easier to read.
- Each function has a single, clear job.
dividereturnsNonewhen division is not possible, and the main loop checks for that before printing.
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:
- More operations:
- Power: $a^b$ using
a ** b - Square root: using a library function
- Memory features:
- Store the last result and allow using it in the next calculation
- Single-number operations:
- Example: square a number (only one input)
You don’t need to add everything at once. The important part of this mini project is:
- Turning a real-world task into clear steps.
- Using loops and conditions to control the flow.
- Collecting and organizing your code using functions.