Complete Projects source code Final Year Projects Source Projects Python

Simple Calculator in Python Free Source Code 2026

simple calculator project source code 2026 feature techprofree

Every programmer builds a calculator at some point — it’s a rite of passage. And there’s a good reason a simple calculator in Python is project #2 on our roadmap for 2026: in about 20 lines you’ll practice user input, type conversion, and if-elif decision-making, and in the upgraded version you’ll meet two skills that follow you forever — functions and error handling.

Below are two complete, tested versions with free source code: a basic calculator to learn from, and a pro version that never crashes, supports six operations, and keeps running until you quit. This is project #2 of our 145+ Python Projects roadmap — project #1 was the Number Guessing Game.

What This Project Does

  • Takes two numbers and an operator from the user
  • Performs the calculation: add, subtract, multiply, divide (+ modulus and power in version 2)
  • Handles the classic trap — division by zero — without crashing
  • Version 2 keeps running so you can calculate again and again

Version 1 — Basic Calculator (Best for Learning)

Save this as calculator.py and run it. No libraries needed — pure Python.

print("=== Simple Calculator ===")

num1 = float(input("Enter first number: "))
op = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if op == "+":
    result = num1 + num2
elif op == "-":
    result = num1 - num2
elif op == "*":
    result = num1 * num2
elif op == "/":
    if num2 == 0:
        result = "Error: cannot divide by zero"
    else:
        result = num1 / num2
else:
    result = "Invalid operator"

print(f"Result: {result}")
Run it: open a terminal in the file’s folder and type python calculator.py

How the Code Works (Line by Line)

  • float(input(…)) — input() always gives text, so we convert it to a number. float (not int) lets users type decimals like 7.5.
  • if / elif chain — checks the operator and picks the right math. One branch runs, the rest are skipped.
  • The zero check — dividing by zero crashes Python with a ZeroDivisionError. We catch it with a simple if before it happens. Examiners love seeing this.
  • else → “Invalid operator” — anything unexpected gets a friendly message instead of silent failure.
  • f-string output — f”Result: {result}” drops the value straight into the sentence.

Version 2 — Pro Calculator With Functions & Error Handling

The basic version has two weaknesses: type a letter instead of a number and it crashes, and it exits after one calculation. This version fixes both — and introduces functions, try/except, and a proper program loop.

def calculate(a, op, b):
    """Perform the calculation and return the result."""
    if op == "+":
        return a + b
    elif op == "-":
        return a - b
    elif op == "*":
        return a * b
    elif op == "/":
        if b == 0:
            return "Error: cannot divide by zero"
        return a / b
    elif op == "%":
        if b == 0:
            return "Error: cannot divide by zero"
        return a % b
    elif op == "**":
        return a ** b
    else:
        return "Invalid operator"


def get_number(prompt):
    """Keep asking until the user enters a valid number."""
    while True:
        value = input(prompt)
        try:
            return float(value)
        except ValueError:
            print("That's not a number — try again.")


print("=== Python Calculator ===")
print("Operators: +  -  *  /  %  **")
print("Type 'q' as the operator to quit.\n")

while True:
    num1 = get_number("First number: ")
    op = input("Operator: ").strip()

    if op.lower() == "q":
        print("Goodbye!")
        break

    num2 = get_number("Second number: ")
    result = calculate(num1, op, num2)

    print(f"→ {num1} {op} {num2} = {result}\n")
What’s new here: calculate() holds the math in one reusable place, get_number() uses try/except so bad input can never crash the program, and the while loop keeps the calculator running until you type q. Two extra operators too: % (remainder) and ** (power).

What You’ll Learn From This Project

  • Type conversion — turning text input into numbers with float()
  • if / elif / else — clean multi-way decisions
  • Functions with return values — the single most important habit in programming
  • try / except — professional error handling that keeps programs alive
  • Defensive coding — checking for divide-by-zero before it bites

5 Ways to Extend This Project

  • Calculation history — store every result in a list and print it when the user types “history”
  • Square root & more — import the math module and add sqrt, sin, cos
  • Single-line input — accept “12 + 7” in one go and split() it apart
  • Save to file — write the history to calculations.txt so it survives closing
  • GUI version — rebuild it with Tkinter buttons like a real desktop calculator

Ready for the next one? Project #3 is Rock, Paper, Scissors in Python — your first game against the computer.

Frequently Asked Questions

 

Project #2 done — keep the streak going 🚀

Head back to the roadmap and pick your next build.

See all 145+ Python Projects →

 

Is a calculator a good first Python project?

It’s one of the best. It’s small, useful, and covers input, type conversion, and decision-making — and version 2 introduces functions and error handling, which you’ll use in every program after this.

Why use float() instead of int()?

int() only accepts whole numbers — typing 7.5 would crash it. float() handles both whole numbers and decimals, so it’s the safer choice for a calculator.

What happens if I divide by zero?

In plain Python it raises a ZeroDivisionError and the program crashes. Our code checks if the second number is zero first and shows a friendly message instead — that check is worth real marks in an assignment.

What does try/except do in version 2?

It attempts the conversion to float, and if the user typed something invalid (like “abc”), Python jumps to the except block instead of crashing — so we can ask again. That pattern is how real applications handle bad input.

Can I use this code for my assignment?

Yes, completely free. Read the line-by-line section so you can explain every part, add one extension of your own, and it’s genuinely yours.