BrightKidz Library
Subjects
A calculator and its four operations A pocket calculator with a wide display along the top showing a row of figures, and six keys below it. Four of the keys carry the signs for the only four things a calculator ever does: add, take away, multiply and divide.

Coding: Creating a Simple Calculator

About 5 minutes

You are going to write a calculator in Python that adds, subtracts, multiplies and divides. It is about twenty lines long, and every one of them does something you can point at and explain.

The Plan, Before Any Code

A calculator only ever does four things, in this order:

  1. Ask for two numbers. The program cannot work on anything until it has something to work on.
  2. Ask which operation. Add, subtract, multiply or divide.
  3. Do the sum. Choose the right calculation for the operation asked for.
  4. Show the answer.

Writing the plan down first is not a formality. Almost every program you will ever write is a plan like this one with the details filled in afterwards.

The Code

# Get the first number from the user
num1 = float(input("Enter first number: "))

# Get the second number from the user
num2 = float(input("Enter second number: "))

# Ask the user for the operation
operation = input("Enter operation (+, -, *, /): ")

# Perform the calculation
if operation == '+':
    result = num1 + num2
elif operation == '-':
    result = num1 - num2
elif operation == '*':
    result = num1 * num2
elif operation == '/':
    if num2 == 0:
        result = "Error! Cannot divide by zero."
    else:
        result = num1 / num2
else:
    result = "Invalid input"

# Display the result
print("Result:", result)

Copy this into your Python interpreter and press Run. It will ask you three questions, one at a time — type your answer and press Enter after each one.

The Interesting Line

Most of that code is straightforward. One part is not:

if num2 == 0:
    result = "Error! Cannot divide by zero."

Dividing by zero is not a hard sum. It is a sum with no answer at all. Ask "how many zeros fit into 6?" and you can keep putting zeros in forever without ever reaching 6. A calculator that tried it would either crash or sit there thinking, so this program checks first and says so politely instead.

Guarding against the one input that breaks your program is a habit worth starting now. Real programs are mostly made of these checks.

Why does the program check whether the second number is zero before dividing?

Make It Better

If It Goes Wrong