Warmup

Write a function big_mac that returns a dictionary with a key-value pair for each part of the big mac. It should have default parameters for cheese, onion, lettuce and tomato (booleans) so that the caller can customize their order.

print(big_mac(cheese=False))

assert big_mac(cheese=False) == {"cheese":False, "lettuce":True, "sesame_bun":True, "tomato":True}

Lesson 4.8: Unit 4 Review

Review Goals

  • Make sure we understand:
    • Functions and parameters
    • Scope (local vs. global)
    • Returning values
    • Handling exceptions with try/except
    • Raising exceptions
    • Combining functions with exceptions

Warm-Up

  • Quick questions:
    • What’s the difference between local and global variables?
    • Why use return instead of print in functions?
    • What happens when a ValueError is not caught?

Group Activity: Debugging

  1. Work with a partner.
  2. I’ll give you buggy code with errors.
  3. Your task: find the error and fix it.

Example:

def add_numbers(a, b):
    return a + c   # bug: c not defined

Practice Problems

  • Write a function that multiplies three numbers.
  • Write a function that takes *args and returns the largest value.
  • Show what happens when a local variable shadows a global one.
  • Write a safe division function that handles divide-by-zero.
  • Write a function that raises a ValueError if given a negative number.

Game: “Name That Error”

  • I’ll show you an error message
  • You guess the exception type

Problem 1

print(5 / 0)
# ?

Problem 2

nums = [1, 2, 3]
print(nums[5])
# ?

Problem 3

int("hello")
# ?

Problem 4

person = {"name": "Alex"}
print(person["age"])
# ?

Quick Check

  • What keyword is used to raise an exception?
  • What does a bare except: do, and why is it discouraged?
  • Why should functions avoid using global variables?

Wrap-Up

  • Share solutions with classmates
  • Ask questions to clear up misunderstandings
  • Get ready for the Lesson 4.9 quiz and the midterm coming up next