Interactive Calculator Demo
Use this simple calculator while learning how the same logic is written in Python.
Want to learn Python through a practical mini-project? A calculator is one of the best beginner builds. You practice variables, input handling, conditional logic, functions, loops, and error handling—all in a program small enough to finish in one sitting.
Why a calculator is a great Python starter project
- Immediate feedback: you type input and instantly see output.
- Real-world logic: arithmetic operators are simple but useful.
- Easy to scale: start with + and -, then add more features.
- Builds confidence: you end with a working app quickly.
Step 1: Define your calculator features
Before coding, decide what version you want to build. A clean beginner plan looks like this:
- Accept two numbers from the user
- Ask for an operator (+, -, *, /)
- Perform the selected operation
- Display the result
- Handle bad input and divide-by-zero errors
Step 2: Build the simplest version first
Basic command-line calculator (Python)
num1 = float(input("Enter first number: "))
operator = input("Enter operation (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 == 0:
result = "Error: Cannot divide by zero."
else:
result = num1 / num2
else:
result = "Invalid operator."
print("Result:", result)
This version proves the concept. You are already using user input, numeric conversion, conditionals, and output formatting.
Step 3: Improve structure using functions
As soon as your script grows, use functions to keep code readable and reusable.
def calculate(a, op, b):
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/":
if b == 0:
return "Error: Cannot divide by zero."
return a / b
return "Invalid operator."
Now your main program can focus on flow, while the function handles logic.
Add a repeat loop
while True:
try:
first = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
second = float(input("Second number: "))
print("Result:", calculate(first, op, second))
except ValueError:
print("Please enter valid numbers.")
again = input("Do another calculation? (y/n): ").lower()
if again != "y":
print("Goodbye!")
break
Step 4: Handle errors like a pro
Most beginner bugs happen during input parsing. Python makes this easy with try/except blocks.
- ValueError: catches invalid numeric input (like "abc").
- ZeroDivisionError: if you divide directly and denominator is zero.
- Custom messages: guide the user instead of crashing.
Step 5: Expand calculator operations
After the core works, add more math:
- Power (
**) - Modulus (
%) - Square root (using
math.sqrt()) - Round results to specific decimals
Cleaner operation mapping with a dictionary
import operator
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
}
def calc(a, op, b):
if op not in ops:
return "Invalid operator."
if op == "/" and b == 0:
return "Error: Cannot divide by zero."
return ops[op](a, b)
Common mistakes to avoid
- Forgetting to convert input strings to numbers
- Not validating the operator
- Skipping divide-by-zero checks
- Letting one invalid input crash the entire script
- Writing everything in one giant block instead of functions
A polished beginner-to-intermediate calculator script
def calculate(a, op, b):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
if b == 0:
return "Error: division by zero"
return a / b
elif op == "%":
if b == 0:
return "Error: modulus by zero"
return a % b
elif op == "**":
return a ** b
else:
return "Error: unknown operator"
def main():
print("Python Calculator")
print("Supported operators: +, -, *, /, %, **")
while True:
try:
a = float(input("\nEnter first number: "))
op = input("Enter operator: ").strip()
b = float(input("Enter second number: "))
except ValueError:
print("Invalid number. Try again.")
continue
result = calculate(a, op, b)
print("Result:", result)
again = input("Another calculation? (y/n): ").strip().lower()
if again != "y":
print("Exiting calculator.")
break
if __name__ == "__main__":
main()
Next steps after command-line
If you want to continue leveling up, try one of these:
- Build a GUI calculator with Tkinter buttons
- Create a web calculator using Flask
- Support full expressions like
(3+5)*2 - Add unit tests with
unittestorpytest
Start simple, keep your code clean, and iterate. A small Python calculator can teach a surprisingly large chunk of core programming skills.