In [ ]:
# Initialize Otter
import otter
grader = otter.Notebook("07_lab_functions.ipynb")

Functions in Python - Campus Cookout Planner

Your student org is hosting an end-of-semester cookout and you're in charge of food. You need to figure out how much of each ingredient to buy for 75 people, stay under the $500 budget, and make sure you have enough variety.

In this lab, you'll build reusable Python functions to scale recipes, calculate costs with bulk discounts, suggest menus within a budget, and generate a complete shopping list. Along the way, you'll see how writing a function once can save you from repeating yourself dozens of times.

Run every cell in order from top to bottom. Later cells depend on earlier ones.


In [ ]:
# Validation: Check Python version and file location
import os
import sys

# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"

if current_version not in SUPPORTED_VERSIONS:
    raise EnvironmentError(
        f"Python version mismatch!\n"
        f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
        f"Found: {current_version}\n"
        f"Please use Python 3.12 or 3.13 for this course."
    )
print(f"Python version: {current_version}")

# Expected filename for this assignment
EXPECTED_FILE = "07_lab_functions.ipynb"

# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lab_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)

if required_path_segment not in current_path and not in_allowed_env:
    raise EnvironmentError(
        f"File location error!\n"
        f"This notebook should be in: ~/Documents/CSC115/lab_notebooks/\n"
        f"Current location: {current_path}\n"
        f"Please move this file to the correct directory."
    )

# Verify filename (skip in grading/development environments)
if not in_allowed_env:
    if not os.path.exists(EXPECTED_FILE):
        notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
        raise EnvironmentError(
            f"Filename mismatch!\n"
            f"Expected: {EXPECTED_FILE}\n"
            f"Found notebooks: {notebooks}\n"
            f"Please rename your notebook to '{EXPECTED_FILE}'."
        )

print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")
In [ ]:
# ──── Imports ────
import math
import random

# ──── Ingredient tuple indices ────
# Each ingredient is a tuple: (name, amount, unit, cost_per_unit)
NAME = 0
AMOUNT = 1
UNIT = 2
COST_PER_UNIT = 3

# ──── Recipe tuple indices ────
# Each recipe is a tuple: (name, base_servings, ingredients_list)
RECIPE_NAME = 0
RECIPE_BASE_SERVINGS = 1
RECIPE_INGREDIENTS = 2

# ──── Recipe Data ────
bbq_sliders = ("BBQ Pulled Pork Sliders", 8, [
    ("pulled pork", 2.0, "lbs", 4.99),
    ("slider buns", 8.0, "count", 0.45),
    ("bbq sauce", 1.0, "cups", 1.50),
    ("coleslaw mix", 2.0, "cups", 1.25),
    ("pickles", 8.0, "slices", 0.10),
    ("butter", 2.0, "tbsp", 0.15),
])

pasta_salad = ("Veggie Pasta Salad", 6, [
    ("rotini pasta", 1.0, "lbs", 1.29),
    ("cherry tomatoes", 2.0, "cups", 1.75),
    ("cucumber", 1.0, "count", 0.89),
    ("bell pepper", 1.0, "count", 1.29),
    ("italian dressing", 0.5, "cups", 1.20),
    ("feta cheese", 0.5, "cups", 2.99),
])

lemonade = ("Fresh Lemonade", 10, [
    ("lemons", 6.0, "count", 0.50),
    ("sugar", 1.0, "cups", 0.35),
    ("water", 8.0, "cups", 0.00),
    ("mint leaves", 0.25, "cups", 2.00),
    ("ice", 10.0, "cups", 0.05),
])

sheet_cake = ("Chocolate Sheet Cake", 12, [
    ("flour", 3.0, "cups", 0.30),
    ("sugar", 2.0, "cups", 0.35),
    ("cocoa powder", 0.75, "cups", 1.80),
    ("eggs", 3.0, "count", 0.35),
    ("butter", 1.0, "cups", 2.50),
    ("milk", 1.5, "cups", 0.40),
    ("vanilla extract", 2.0, "tsp", 0.75),
])

trail_mix = ("Trail Mix Cups", 8, [
    ("peanuts", 2.0, "cups", 1.20),
    ("raisins", 1.0, "cups", 1.50),
    ("chocolate chips", 1.0, "cups", 2.00),
    ("pretzels", 1.0, "cups", 0.80),
    ("coconut flakes", 0.5, "cups", 1.75),
])

all_recipes = [bbq_sliders, pasta_salad, lemonade, sheet_cake, trail_mix]

# ──── Test recipe (used in Q5) ────
test_punch = ("Test Punch", 5, [
    ("juice", 3.0, "cups", 1.00),
    ("soda", 2.0, "liters", 1.50),
    ("fruit", 1.0, "cups", 2.00),
])

print("Data loaded! Recipes available:")
for recipe in all_recipes:
    print(f"  {recipe[RECIPE_NAME]} (serves {recipe[RECIPE_BASE_SERVINGS]}, {len(recipe[RECIPE_INGREDIENTS])} ingredients)")

1. Building Blocks - Utility Functions

Quick vocabulary review from lecture:

  • Define vs Call - writing the recipe vs cooking the dish
  • Parameters vs Arguments - the blanks on a form vs the values you fill in
  • Return - how a function gives back a result

Let's start with a quick refresher.

In [ ]:
# Quick refresher: a simple function
def double(number):
    return number * 2

# Defining a function does NOT run it. We have to CALL it:
result = double(5)
print(f"double(5) = {result}")
print(f"double(3.7) = {double(3.7)}")

Q1: Scale Functions (2 points)

The cookout planning starts with the most fundamental operation: scaling a single ingredient. If a recipe serves 8 and you need to serve 75, every ingredient amount needs to multiply by the same factor.

Part A - Write a function called scale_ingredient_amount that takes two parameters: the original amount and a scaling factor. Since you can't buy partial units at the store (half an egg doesn't help anyone), always round UP to the next whole number. The math.ceil() function does this. Return the rounded-up result.

Part B - Write a function called scale_ingredients that takes a recipe tuple and an optional target number of servings (default: 4). It should figure out the scaling factor from the recipe's base servings, then build and return a list of scaled ingredient tuples. Each scaled tuple should have the same structure as the original: (name, scaled_amount, unit, cost_per_unit).

Hint for Part B: To build the result list, start with an empty list and use .append() to add each scaled ingredient. We haven't formally covered .append() yet, but it simply adds an item to the end of a list. You'll learn more about list methods in a few weeks. The scaling factor is target_servings / base_servings.

In [ ]:
# ✏️ YOUR ANSWER HERE
# Part A: scale_ingredient_amount(base_amount, scale_factor)
# Part B: scale_ingredients(recipe, target_servings=4)

...
In [ ]:
grader.check("q1_scale_functions")
In [ ]:
# YOUR function, called 6 times automatically:
print("BBQ Pulled Pork Sliders (75 servings):")
for ingredient in scale_ingredients(bbq_sliders, 75):
    print(f"  {ingredient[NAME]:<20} {ingredient[AMOUNT]:>4} {ingredient[UNIT]}")

print()

# Same function, different recipe - called 6 MORE times:
print("Veggie Pasta Salad (75 servings):")
for ingredient in scale_ingredients(pasta_salad, 75):
    print(f"  {ingredient[NAME]:<20} {ingredient[AMOUNT]:>4} {ingredient[UNIT]}")

print()

# And again - 5 more calls:
print("Fresh Lemonade (75 servings):")
for ingredient in scale_ingredients(lemonade, 75):
    print(f"  {ingredient[NAME]:<20} {ingredient[AMOUNT]:>4} {ingredient[UNIT]}")

You wrote scale_ingredient_amount once. It just ran 17 times across 3 recipes. That's the power of reusable functions.


2. Scope - What Happens Inside Stays Inside

Before we write more functions, we need to understand an important rule about variables inside functions.

In [ ]:
# Demo 1: Local variables
# Variables created INSIDE a function only exist inside that function.

def demo_local_variable(base_amount, scale_factor):
    scaled_value = base_amount * scale_factor  # 'scaled_value' only exists HERE
    return math.ceil(scaled_value)

demo_local_variable(2.0, 9.375)
# Try uncommenting the next line - you'll get a NameError!
# print(scaled_value)

The variable scaled_value was created inside the function. It doesn't exist outside. This is called local scope.

In [ ]:
# Demo 2: Global constants are readable from inside functions
# Our named constants (NAME, AMOUNT, etc.) are GLOBAL - defined outside any function.

print(f"NAME index is: {NAME}")       # Works everywhere
print(f"AMOUNT index is: {AMOUNT}")   # Works everywhere

def show_first_ingredient(recipe):
    # We can READ global constants inside functions - no problem
    first = recipe[RECIPE_INGREDIENTS][0]
    print(f"{first[NAME]}: {first[AMOUNT]} {first[UNIT]}")

show_first_ingredient(bbq_sliders)
In [ ]:
# Demo 3: The shadowing trap
# Assigning inside a function creates a NEW local variable.
# It does NOT change the global one.

demo_servings = 75  # Global variable

def bad_function():
    demo_servings = 10  # This creates a NEW local variable!
    print(f"Inside function: demo_servings = {demo_servings}")

bad_function()
print(f"Outside function: demo_servings = {demo_servings}")  # Still 75!

The only way to get data out of a function is through return.


3. Calculating Costs

Now that you can scale recipes, the next question is: how much will it cost?

Here's a real-world detail: when you're buying 19 lbs of pulled pork instead of 2, the store gives you a bulk discount.

In [ ]:
# Walk through cost calculation for one ingredient
scaled_pork = scale_ingredient_amount(2.0, 75 / 8)  # 19 lbs
print(f"Scaled amount: {scaled_pork} lbs")

# Without bulk discount:
full_price = scaled_pork * 4.99
print(f"Full price: {scaled_pork} x $4.99 = ${full_price:.2f}")

# With 15% bulk discount (buying 10+ units):
BULK_THRESHOLD = 10
BULK_DISCOUNT = 0.15
if scaled_pork >= BULK_THRESHOLD:
    discounted = full_price * (1 - BULK_DISCOUNT)
    print(f"Bulk discount (15% off): ${discounted:.2f}  -- saved ${full_price - discounted:.2f}!")

Buying in bulk saves money. Let's build functions to handle this automatically.

Q2: Ingredient Pricing and Recipe Cost (2 points)

Time to figure out what this cookout will cost. When you're buying for 75 people, you're purchasing large quantities - and stores give bulk discounts for that.

Part A - Write a function called get_ingredient_cost that calculates the cost of a single ingredient. It takes the quantity needed and the price per unit, plus two optional parameters: a bulk threshold (default: 10) and a bulk discount rate (default: 0.15, meaning 15% off). If the quantity meets or exceeds the threshold, apply the discount to the total. Return the cost rounded to 2 decimal places.

Part B - Write a function called calculate_recipe_cost that calculates the total cost for an entire recipe at a given number of servings. It should take a recipe tuple and a target number of servings. For each ingredient, figure out how much you need (you have a function for this!) and then calculate its cost (you're about to have a function for this too!). Return the total cost rounded to 2 decimal places.

Hint: Part B should call BOTH scale_ingredient_amount (from Q1) and get_ingredient_cost (from Part A). That's three layers of function composition!

In [ ]:
# ✏️ YOUR ANSWER HERE
# Part A: get_ingredient_cost(quantity, price_per_unit, bulk_threshold=10, bulk_discount=0.15)
# Part B: calculate_recipe_cost(recipe, target_servings)

...
In [ ]:
grader.check("q2_recipe_cost")
In [ ]:
# Cost comparison: buying for 8 vs 75 people
print("Per-person cost comparison (bulk discount kicks in at scale):")
print(f"  {'Recipe':<30} {'8 guests':>12} {'75 guests':>12}")
print(f"  {'-' * 54}")
for recipe in all_recipes:
    cost_small = calculate_recipe_cost(recipe, 8)
    cost_large = calculate_recipe_cost(recipe, 75)
    per_person_small = cost_small / 8
    per_person_large = cost_large / 75
    print(f"  {recipe[RECIPE_NAME]:<30} ${per_person_small:>8.2f}/ea  ${per_person_large:>8.2f}/ea")

Bulk discount makes the per-person cost drop when you scale up. Your get_ingredient_cost function just ran ~60 times in that comparison.

Notice that total_cost inside calculate_recipe_cost is completely independent of any variable in scale_ingredients or get_ingredient_cost. Each function has its own workspace.


4. Smart Suggestions

What if you're not sure which recipes to make? Let's build a function that randomly suggests a menu and checks whether it fits your budget.

In [ ]:
# random.sample picks N items from a list without repeats
random.seed(42)  # Makes the "random" choice repeatable (important for testing!)
picks = random.sample(all_recipes, 3)
for pick in picks:
    print(pick[RECIPE_NAME])
In [ ]:
# Default parameters let callers skip common values
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("class")            # Uses default: "Hello, class!"
greet("class", "Hey")     # Overrides: "Hey, class!"

Q3: Menu Suggester (2 points)

Write a function called suggest_menu that randomly picks recipes for the cookout and checks if they fit the budget. It should take the full list of recipes, the group size, the total budget, and optionally how many recipes to suggest (default: 3).

The function should:

  1. Randomly select the specified number of recipes (use random.sample)
  2. Calculate the cost of each selected recipe for the given group size
  3. Print each selected recipe with its cost
  4. Determine the total cost and whether it's within budget
  5. Return the total cost and a boolean indicating if it's under budget

Hint: You already have a function that calculates recipe costs. And remember, random.seed() before calling makes the results repeatable for testing.

In [ ]:
# ✏️ YOUR ANSWER HERE
# suggest_menu(recipes, group_size, budget, num_picks=3)

...
In [ ]:
grader.check("q3_suggest_menu")
In [ ]:
# Try it with different seeds to see different suggestions:
print("Menu suggestion (tight budget):")
random.seed(1)
suggest_menu(all_recipes, 75, 200.0)

5. The Full Picture

Time to bring it all together. You've built every piece - now combine them into one function that produces a complete shopping list.

Here's the composition chain - one call triggers dozens of function calls:

generate_shopping_list(all_recipes, 75)
  |-- for each recipe (x5):
       |-- scale_ingredients(recipe, 75)
       |    |-- scale_ingredient_amount (x5-7 per recipe)
       |
       |-- calculate_recipe_cost(recipe, 75)
            |-- scale_ingredient_amount (x5-7 per recipe)
            |-- get_ingredient_cost (x5-7 per recipe)

Q4: Shopping List Generator (2 points)

Write a function called generate_shopping_list that produces a complete, formatted shopping list for the cookout. It takes the list of all recipes and the number of guests.

For each recipe, display the recipe name, show each scaled ingredient with its amount, unit, and cost, then show the recipe subtotal. At the end, display the grand total across all recipes.

Return the grand total cost (so other functions could use this value later).

Expected output format:

====== COOKOUT SHOPPING LIST (75 guests) ======

BBQ Pulled Pork Sliders (scaled to 75 servings):
  pulled pork          19 lbs          $  80.59
  slider buns          75 count        $  28.69
  ...
  Subtotal:                            $ 151.02

================================================
  GRAND TOTAL:                         $ 402.21
================================================

Hint: You already have scale_ingredients, calculate_recipe_cost, and get_ingredient_cost. Call them! For formatting, remember f-string alignment from the for loops lab: f"{'text':<20}" left-aligns in a 20-character space.

In [ ]:
# ✏️ YOUR ANSWER HERE
# generate_shopping_list(recipes, group_size)

...
In [ ]:
grader.check("q4_shopping_list")

Let's count: generate_shopping_list called scale_ingredients 5 times and calculate_recipe_cost 5 times. Each of those looped over every ingredient, calling scale_ingredient_amount and get_ingredient_cost for each one. You wrote about 25 lines of function code. Python executed them over 120 times.


6. Behind the Curtain - Writing Your Own Tests

Every time you run a test cell in this course, you're running a test function - a function whose only job is to call YOUR function and check the result. There's nothing magical about it. A test function is just a regular Python function that raises an error if something is wrong.

When you write your own programs outside this class, there won't be an autograder. You'll need to test your own code. Let's learn how.

In [ ]:
# This is EXACTLY what the autograder does behind the scenes:
def test_scale_doubles():
    """Test that doubling works correctly."""
    result = scale_ingredient_amount(5.0, 2.0)
    if result != 10:
        raise AssertionError(
            f"Expected 10, got {result}. 5.0 * 2.0 should be exactly 10."
        ) from None

# Run the test:
test_scale_doubles()
print("test_scale_doubles passed!")

The pattern is:

  1. Call the function you want to test with known inputs
  2. Compare the result to what you expect
  3. Raise AssertionError with a helpful message if it's wrong
  4. from None suppresses the messy traceback (cleaner error output)
  5. If the function finishes without raising, the test passed
In [ ]:
# What if someone wrote scale_ingredient_amount using round() instead of ceil()?
def buggy_scale(base_amount, scale_factor):
    return round(base_amount * scale_factor)  # BUG: rounds to nearest, not up!

# This test would CATCH that bug:
def test_rounds_up():
    """Test that amounts always round UP (can't buy half an egg)."""
    result = buggy_scale(3.0, 1.5)  # 3.0 * 1.5 = 4.5
    if result != 5:
        raise AssertionError(
            f"Expected 5 (rounded UP from 4.5), got {result}. "
            f"Are you using math.ceil()?"
        ) from None

# Uncomment the next line to see the error message:
# test_rounds_up()

Good tests catch bugs. The test above would immediately tell someone their rounding is wrong.

Q5: Write Your Own Tests (1 point)

Now it's your turn. Write a function called test_cookout_functions that tests your scale_ingredient_amount and calculate_recipe_cost functions.

A test recipe has been provided for you (loaded in the setup cell):

test_punch = ("Test Punch", 5, [
    ("juice", 3.0, "cups", 1.00),
    ("soda", 2.0, "liters", 1.50),
    ("fruit", 1.0, "cups", 2.00),
])

Your test function should verify at minimum:

  1. scale_ingredient_amount returns the correct value when the result is exact (no rounding needed)
  2. scale_ingredient_amount always rounds UP, not to the nearest number or down (test with a value where this matters!)
  3. calculate_recipe_cost returns the correct total for test_punch at 10 servings (you'll need to work out what the right answer is - think through the math!)

Raise AssertionError with a helpful message if any check fails. If all checks pass, return the string "All tests passed!".

Good tests don't just confirm correct behavior - they catch bugs. Think about what could go wrong: what if someone used round() instead of math.ceil()? What if they forgot to scale the amounts before calculating cost? Your tests should catch these kinds of mistakes.

Hint: For the cost check, work out each ingredient: scale the amount (factor = 10/5 = 2.0), multiply by cost_per_unit, then add them up. None of the scaled amounts hit the bulk threshold.

In [ ]:
# ✏️ YOUR ANSWER HERE
# test_cookout_functions()

...
In [ ]:
grader.check("q5_write_tests")

You just wrote your first test suite. Every professional Python developer writes tests like this (usually with a library called pytest that automates the process). The autograder in this course? It's running functions exactly like the ones you just wrote.

And the autograder for THIS question just did something clever: it swapped in broken versions of your functions to see if your tests would catch the bugs. That's called mutation testing - it's how you know your tests are actually good, not just passing by luck.


Summary

Concept Pattern Example from This Lab
Define a function def name(params): def scale_ingredient_amount(base_amount, scale_factor):
Return a value return expression return math.ceil(base_amount * scale_factor)
Default parameters param=default def get_ingredient_cost(qty, price, bulk_threshold=10, bulk_discount=0.15):
Conditional logic if condition: ... Bulk discount applied when quantity >= threshold
Call another function result = func(args) cost = get_ingredient_cost(scaled_amount, price)
Import a module import module import math, import random
Local scope Variables inside a function are local total_cost in calculate_recipe_cost
Global constants Constants defined outside functions NAME, AMOUNT, RECIPE_NAME
Composition Functions calling functions calculate_recipe_cost -> scale_ingredient_amount + get_ingredient_cost
Writing tests Call, compare, raise if wrong test_cookout_functions()

Submitting to Gradescope

This file is saved on your computer - you do not need to download it from Jupyter.

  1. Find the file on your computer:

    • Mac: Open Finder -> Documents/CSC115/lab_notebooks/07_lab_functions/07_lab_functions.ipynb
    • Windows: Open File Explorer -> Documents\CSC115\lab_notebooks\07_lab_functions\07_lab_functions.ipynb
  2. Upload to Gradescope:

    • Go to gradescope.com and open this assignment
    • Click "Submit" and upload the .ipynb file
    • The filename must be exactly 07_lab_functions.ipynb

Do NOT use File > Download in Jupyter - this can rename the file and cause submission errors.


You have completed the Functions in Python lab.


To double-check your work, the cell below will rerun all of the autograder tests.

In [ ]:
grader.check_all()