Preplp
Daily Python
Day 11Python~35 min

Exceptions

try / except / else / finally

Track progress0/15 days
x

What you'll learn

tryexceptValueErrorZeroDivisionErrorraise
  • Catch common errors without crashing
  • Build a safe calculator with error handling

Lesson & examples

Read the code, then the explanation — try changing values before the project.

Handle division by zero
try:
    num = int(input("Number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero.")

Today's exercise: Safe Calculator

Calculator that handles invalid input and divide-by-zero.

Steps

  1. 1

    Operation functions

    add, subtract, multiply, divide with try/except.

  2. 2

    Menu loop

    Let user pick operation and two numbers.

Full project source — copy into a folder or use the zip above

starter.py
def divide(x, y):
    return x / y

while True:
    try:
        a = float(input("First number (or 'q' to quit): "))
        if str(a) == "q":
            break
        b = float(input("Second number: "))
        op = input("Operator (+ - * /): ")
        if op == "+":
            print(a + b)
        elif op == "-":
            print(a - b)
        elif op == "*":
            print(a * b)
        elif op == "/":
            print(divide(a, b))
    except ValueError:
        print("Invalid number.")
    except ZeroDivisionError:
        print("Cannot divide by zero.")

One rehearsal platform

Certification mocks, daily lessons, project labs, and in-browser drills

Structured for exam day and portfolio proof — timed tests, guided builds, and quick reps on one platform.