Warmup

Write a function is_sum_even that takes two integers and returns whether their sum is even. Starter code with tests:

def test_func(result, expected):
    assert result == expected, f"result:{result} expected:{expected}"

# replace with your implementation of is_sum_even

cases = [
    (is_sum_even(3, 1), True),
    (is_sum_even(3, 4), False),
]

# loop over the cases and call test_func on each one
for result, expected in cases:
    test_func(result, expected)

Agenda

  • Exceptions for the rest of the week
  • Monday: Unit 4 practice
  • Unit 4 Quiz moved to next Tuesday
    • 20 questions in Canvas, rehearse grade
  • Next Wednesday: Midterm review & practice
  • Thursday: midterms begin

Lesson 4.4: Errors and Exceptions

Review

  • Functions let us structure programs
  • Scope controls where variables live
  • Now: what happens when something goes wrong?

What is an Error?

  • An error happens when Python cannot complete an instruction
  • Example:
print(5 / 0)   # ZeroDivisionError
  • Errors stop the program unless handled

Syntax Errors vs. Exceptions

  • Syntax Error: mistake in code structure (caught before running)
if True print("hi")   # SyntaxError
  • Exception: happens while code is running
nums = [1, 2, 3]
print(nums[5])   # IndexError

Common Exceptions

  • ZeroDivisionError – dividing by zero
  • ValueError – wrong type of value
int("hello")   # ValueError
  • IndexError – list index out of range
  • KeyError – dictionary key doesn’t exist

Unhandled Exceptions

  • If not handled, program crashes
  • Example:
name = input("Enter a number: ")
number = int(name)  # crashes if input is not a number

Why Learn Exceptions?

  • Real programs deal with unexpected input
  • Handling exceptions keeps programs from crashing
  • Builds robust software

Quick Check

  • What’s the difference between a syntax error and an exception?
  • Name two common exceptions.
  • What happens when an exception is not handled?

Practice Challenge

Write code that tries to divide two numbers.

  • First try dividing normally.
  • Then, test dividing by zero and observe the error message.