Coding: Creating a Simple Calculator
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.
- A computer with a web browser
- A free online Python interpreter, such as online-python.com, where you can type code and press Run
The Plan, Before Any Code
A calculator only ever does four things, in this order:
- Ask for two numbers. The program cannot work on anything until it has something to work on.
- Ask which operation. Add, subtract, multiply or divide.
- Do the sum. Choose the right calculation for the operation asked for.
- 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?
- Zero is difficult for computers to store
- Dividing by zero has no answer, so the program would break
- To make the program run faster
Make It Better
- Add exponents, using
**for "to the power of". - After showing an answer, ask whether the user wants another go.
- Try typing
bananawhen it asks for a number. It breaks — now go and stop it breaking.
If It Goes Wrong
- Nothing happens. Check your indentation. In Python the spaces at the start of a line are part of the code, not decoration.
- You get an error message. Read it. It names the line number. That is the program telling you exactly where to look, which is more help than it sounds.
- The answer is wrong. Check you typed the operation symbol on its own, with no spaces around it.