KAHIBARO Bookshelves
Discord Login Register

17.2. Simple calculator

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:

  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:

  • 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 break to 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 continue to 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 / 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:

  • 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.
  • divide returns None when 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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms