Python Calculator Application

In the last lesson, Introduction to LLMs, you finished the AI part of the course. So you have learned a lot of separate pieces: variables, functions, loops, input, and error handling. Now comes the fun part, where it all clicks together. We are going to build real, complete programs. We start with a project everyone should build once: a working calculator. It is small, but it uses almost every basic skill you have, and you will end up with a program you can actually run and use.

🤔 Why build a calculator first?

A calculator is the perfect first project. It is simple enough to finish in one sitting, but real enough to teach you how the pieces fit. By building it you practice the everyday tools you will use in every program after this.

In this one project you will use:

  • Functions, to give each operation its own clear block of code.
  • User input, to ask the person what they want to calculate.
  • A loop, so the calculator keeps running until they choose to quit.
  • Error handling, so a mistake like dividing by zero does not crash the program.

So it is not really about the math. It is about wiring those pieces into one tidy program. Let’s build it step by step, then see the whole thing.

🧩 Step 1: The operation functions

We start with the actual math. Each operation gets its own small function. This keeps things tidy: one job per function, easy to read and easy to fix.

These four functions each do one calculation and return the result:

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:
return "Error: cannot divide by zero"
return a / b

Most of these are one line: take two numbers, return the answer. The interesting one is divide. Before dividing, it checks if b is zero, because dividing by zero is not allowed and would crash the program. So instead it returns a friendly message. This is a small example of thinking ahead about what could go wrong.

⌨️ Step 2: Getting the numbers safely

Next we ask the user for two numbers. But input always comes in as text, so we must turn it into a number with float. And the user might type something that is not a number, so we wrap it in try and except to handle that without crashing.

This function asks for one number and keeps asking until it gets a valid one:

def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("That is not a number. Please try again.")

Read what happens here:

  • input(prompt) shows a message and reads what the user types, as text.
  • float(...) turns that text into a number. If the user typed “hello”, float raises a ValueError.
  • The try / except catches that error, prints a gentle message, and the while True loop asks again.
  • Once a real number comes in, return hands it back and the loop ends.

So this function refuses to give up until it has a proper number. That is a common, friendly pattern for reading input.

🔁 Step 3: The main loop

Now we tie it together. The main part shows a menu, asks what to do, runs the right function, and then asks again. A loop keeps the calculator alive until the user chooses to quit.

This is the heart of the program:

def calculator():
print("Simple Calculator")
print("Operations: + - * /")
while True:
choice = input("\nChoose an operation (or 'q' to quit): ")
if choice == "q":
print("Goodbye!")
break
if choice not in ["+", "-", "*", "/"]:
print("Not a valid choice. Pick +, -, *, / or q.")
continue
num1 = get_number("Enter the first number: ")
num2 = get_number("Enter the second number: ")
if choice == "+":
result = add(num1, num2)
elif choice == "-":
result = subtract(num1, num2)
elif choice == "*":
result = multiply(num1, num2)
else:
result = divide(num1, num2)
print("Result:", result)

Let’s walk through the logic:

  • The while True loop keeps the calculator running round after round.
  • If the user types q, break stops the loop and the program ends.
  • If they type something that is not an operation, continue skips straight back to the top and asks again.
  • Otherwise it reads two numbers, picks the matching function with if / elif, and prints the result.

🖥️ Step 4: The complete program

Here is everything together, ready to run. Save it as calculator.py and run it with python calculator.py.

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:
return "Error: cannot divide by zero"
return a / b
def get_number(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("That is not a number. Please try again.")
def calculator():
print("Simple Calculator")
print("Operations: + - * /")
while True:
choice = input("\nChoose an operation (or 'q' to quit): ")
if choice == "q":
print("Goodbye!")
break
if choice not in ["+", "-", "*", "/"]:
print("Not a valid choice. Pick +, -, *, / or q.")
continue
num1 = get_number("Enter the first number: ")
num2 = get_number("Enter the second number: ")
if choice == "+":
result = add(num1, num2)
elif choice == "-":
result = subtract(num1, num2)
elif choice == "*":
result = multiply(num1, num2)
else:
result = divide(num1, num2)
print("Result:", result)
# Start the calculator
calculator()

Here is a sample run, showing a couple of calculations and then quitting:

Output

Simple Calculator
Operations: + - * /
Choose an operation (or 'q' to quit): +
Enter the first number: 10
Enter the second number: 5
Result: 15.0
Choose an operation (or 'q' to quit): /
Enter the first number: 8
Enter the second number: 0
Result: Error: cannot divide by zero
Choose an operation (or 'q' to quit): q
Goodbye!

Look at what you built. It runs in a loop, handles bad input without crashing, refuses to divide by zero, and quits cleanly. That is a real, complete program made from the small pieces you already knew.

⚠️ Common Mistakes

A few traps when building this:

  • Forgetting to convert input to a number. input() always gives text, so "10" + "5" becomes "105", not 15. You must use float() or int().
  • Not checking for divide by zero. Dividing by zero crashes the program with a ZeroDivisionError. The check inside divide prevents it.
  • Forgetting break, so the loop never ends. Without break when the user types q, the calculator would run forever.

✅ Best Practices

Habits this project teaches:

  • Give each job its own function, like add and get_number. Small, named functions are easy to read and fix.
  • Validate input where you read it, so bad data never reaches the math.
  • Handle the things that can go wrong, like bad input and dividing by zero, instead of hoping they will not happen.
  • Let the user quit cleanly with a clear option, rather than forcing them to close the window.

🧩 What You’ve Learned

✅ You built a complete calculator that adds, subtracts, multiplies, and divides.

✅ Each operation lives in its own small function, keeping the code tidy and clear.

try / except with float() reads numbers safely, asking again when the input is not a number.

✅ A while True loop keeps the program running, with break to quit and continue to skip a bad choice.

✅ Checking for divide by zero stops a crash and shows a friendly message instead.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    Why must you wrap input() with float() in the calculator?

    Why: input() always returns text. Without float() or int(), '10' + '5' would join into '105' instead of adding to 15.

  2. 2

    What does the check 'if b == 0' inside divide() prevent?

    Why: Dividing by zero raises a ZeroDivisionError and crashes the program. The check catches that case and returns a friendly message instead.

  3. 3

    What is the role of the while True loop in the calculator?

    Why: The while True loop lets the user do calculation after calculation. break ends it when they type q, and continue skips an invalid choice.

  4. 4

    Why does get_number use try / except around float(input(...))?

    Why: If the user types text like 'hello', float() raises a ValueError. The try / except catches it and re-asks, so the program never crashes.

🚀 What’s Next?

You built your first complete app and saw how the basics combine into one program. Next we build something genuinely useful that you might use yourself: a password generator that makes strong, random passwords.

Password Generator

Share & Connect