Build a Simple Python Calculator: A Step-by-Step Guide for Beginners
Build a Simple Python Calculator: A Step-by-Step Guide
Ready to write your first functional program? Learn how to take user input, write conditional logic, and handle basic mathematical operations in Python.
Building a calculator is a classic rite of passage for every new programmer. It is the perfect project to transition from basic syntax to writing software that actually does something useful.
In this tutorial, we will write a command-line calculator from scratch. You will learn how to capture user input, convert text to numbers, use if/elif/else statements to decide which math operation to run, and use a while loop so your program keeps running until the user wants to quit.
1 Setting Up and Getting Input
Before we do any math, our program needs to talk to the user. We will use Python's built-in input() function to ask the user what kind of operation they want to perform, and what numbers they want to calculate.
The concept:
By default, Python treats everything a user types as a "string" (text). If someone types "5", Python sees it as a word, not a number. We need to use the float() function to convert their text into a decimal number before we can add or subtract it.
2 The Logic (If / Elif / Else)
Once we know what the user wants to do (Add, Subtract, Multiply, or Divide), we need a way to tell the computer which path to take. We do this using conditional statements.
- if: Checks the first condition (e.g., "Did they choose option 1?").
- elif: Stands for "else if". It checks the next conditions if the first one was false.
- else: The fallback option. If the user types a letter instead of a number, we use this to catch the error.
3 The Full Calculator Code
Here is how all these pieces fit together. We wrap the entire logic in a while True: loop. This creates an infinite loop, meaning the calculator will keep asking for new numbers until the user specifically types 'q' to break out of the loop.
def calculator():
print("Welcome to the Python Calculator!")
print("Select an operation:")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (*)")
print("4. Divide (/)")
while True:
# Get the user's choice
choice = input("\nEnter choice (1/2/3/4) or 'q' to quit: ")
# Check if the user wants to quit
if choice.lower() == 'q':
print("Exiting calculator. Goodbye!")
break
# Check if the choice is one of the valid options
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Invalid input. Please enter a valid number.")
continue
# Perform the math based on the choice
if choice == '1':
print(f"Result: {num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"Result: {num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"Result: {num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 == 0:
print("Error: Cannot divide by zero!")
else:
print(f"Result: {num1} / {num2} = {num1 / num2}")
else:
print("Invalid Input. Please select a valid operation (1-4).")
if __name__ == "__main__":
calculator()
What Makes This Code Good?
Error Handling
The try/except block prevents the program from crashing if the user types a letter like "apple" when asked for a number.
Zero Division Check
Dividing by zero causes a fatal error in Python. Our code specifically checks if num2 == 0 before doing the math.