Codzy

Project 1: a robust calculator

First complete project: a calculator that reads an expression like "7 / 2" and returns the result. The core fits in three lines thanks to a dictionary of operations (operator.add, operator.mul…): no more long chain of if/elif.

What sets a real program apart from an exercise is error handling: users will type anything. A malformed expression raises ValueError, an unknown operator KeyError, a division by zero ZeroDivisionError. We catch them one by one to show a clear message instead of crashing. Bonus: show 4 rather than 4.0.

import operator

OPS = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv}

def calculate(expression):
    a, op, b = expression.split()
    return OPS[op](float(a), float(b))

for e in ["3 + 4", "10 / 4", "6 * 7"]:
    print(e, "=", calculate(e))

Start the lesson