Homework lesson code answers

SASS Container Lesson

Challenge

Review how semantic tags provide structure while OCS classes define the role.

Lines: 1 Characters: 0
UI Output

Toggles HW

Challenge

HW Toggles

Lines: 1 Characters: 0
UI Output

Buttons HW (fixing up)

these below are notebook notes from HW lesson:

Random Values Popcorn #1 #2 #3 HW Hacks

Code Runner Challenge

Popcorn Hack 1 Random SFI Record Number

View IPYNB Source
%%python

# CODE_RUNNER: Popcorn Hack 1 Random SFI Record Number

import random

actions = ["GET/search", "POST/create"]
record_numbers = [1, 2, 3, 4]

selected_action = random.choice(actions)
selected_record = random.choice(record_numbers)

if selected_action == "GET/search":
    print(f"QA test: search for an SFI part record #{selected_record}")
else:
    print(f"QA test: validate an SFI part record #{selected_record} before creating it")

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 2 - Random SFI Part Record

View IPYNB Source
%%python

# CODE_RUNNER: Popcorn Hack 2 - Random SFI Part Record

import random

parts = [
    {
        "product_name": "Replacement Flywheels and Clutch Assemblies",
        "category": "Auto Racing",
        "spec_number": "1.1"
    },
    {
        "product_name": "Multiple Disc Clutch Assemblies",
        "category": "Drag Racing",
        "spec_number": "1.2"
    },
    {
        "product_name": "Racing Flywheel Record",
        "category": "Auto Racing",
        "spec_number": "2.1"
    }
]

print("---One Complete Structured Record with random.choice()---")
selected_record = random.choice(parts)
print("Product Name:", selected_record["product_name"])
print("Category:    ", selected_record["category"])
print("Spec Number: ", selected_record["spec_number"])
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 3 - Random SFI API Test

View IPYNB Source
%%python

# CODE_RUNNER: Popcorn Hack 3 - Random SFI API Test

import random

parts = [
    {"product_name": "Replacement Flywheels", "spec_number": "1.1"},
    {"product_name": "Multiple Disc Clutch Assemblies", "spec_number": "1.2"},
    {"product_name": "Racing Flywheel Record", "spec_number": "2.1"}
]

actions = [
    "GET/search",
    "POST/create",
    "PUT/update"
]

selected_part = random.choice(parts)
selected_action = random.choice(actions)

if selected_action == "GET/search":
    print("Searching backend for record for part:", selected_part)
elif selected_action == "POST/create":
    print("Creating record for part:", selected_part)
elif selected_action == "PUT/update":
    print("Updating record for part:", selected_part)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Homework Hack

View IPYNB Source
%%python

# CODE_RUNNER: Homework Hack

# Homework Hack - SFI Backend QA Simulator

import random

parts = [
    {
        "product_name": "Replacement Flywheels",
        "category": "Auto Racing",
        "spec_number": "1.1"
    },
    {
        "product_name": "Multiple Disc Clutch Assemblies",
        "category": "Drag Racing",
        "spec_number": "1.2"
    },
    {
        "product_name": "Racing Flywheel Record",
        "category": "Auto Racing",
        "spec_nu# CODE_RUNNER: Popcorn Hack 1 - changed jersey range and court size

import math
import random

# Read the API before calling a procedure
print("random.randint:", random.randint.__doc__)
print("math.ceil:", math.ceil.__doc__)

points_per_game = [24, 18, 31, 27, 22]

# random.choice picks one item out of a list
print("Random game to review:", random.choice(points_per_game), "points")

# Changed the jersey range from 1-99 to 1-55
jersey = random.randint(1, 55)
print("Random jersey number:", jersey)

# Changed the court size from 144 to 225 square feet
side = math.sqrt(225)
print("Square court side:", side, "feet")

# math.ceil rounds up to the next whole number
average = sum(points_per_game) / len(points_per_game)
rounded_up = math.ceil(average)
print("Points per game:", average, "-> rounded up:", rounded_up)mber": "2.1"
    }
]

actions = [
    "GET/search",
    "POST/create",
    "PUT/update",
    "DELETE/remove"
]

existing_spec_numbers = ["1.1", "2.1"]
test_count = 4

# Build and test your QA simulator below.

def run_qa_test(test_number):
    selected_part = random.choice(parts)
    selected_action = random.choice(actions)
    spec = selected_part["spec_number"]
    name = selected_part["product_name"]

    print(f"--- Test {test_number} ---")
    print(f"Selected Part: {name} (Spec {spec}, {selected_part['category']})")
    print(f"Selected Action: {selected_action}")

    if selected_action == "GET/search":
        print(f"Result: Searching backend for '{name}' (Spec {spec})...")

    elif selected_action == "POST/create":
        duplicate_spec = spec in existing_spec_numbers
        if duplicate_spec:
            print(f"Result: REJECTED — Spec {spec} already exists in backend.")
        else:
            print(f"Result: ACCEPTED — Creating new record for '{name}' (Spec {spec}).")

    elif selected_action == "PUT/update":
        print(f"Result: Updating existing record for '{name}' (Spec {spec})...")

    elif selected_action == "DELETE/remove":
        print(f"Result: Removing record for '{name}' (Spec {spec}) from backend...")

    print()


for i in range(1, test_count + 1):
    run_qa_test(i)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Boolean Expressions Popcorn #1 #2 #3, MCQ and HW Hacks

Code Runner Challenge

Popcorn Hack 1 Random SFI Record Number

View IPYNB Source
%%python

# CODE_RUNNER: Popcorn Hack 1 Random SFI Record Number

import random

actions = ["GET/search", "POST/create"]
record_numbers = [1, 2, 3, 4]

selected_action = random.choice(actions)
selected_record = random.choice(record_numbers)

if selected_action == "GET/search":
    print(f"QA test: search for an SFI part record #{selected_record}")
else:
    print(f"QA test: validate an SFI part record #{selected_record} before creating it")

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 1 Check One SFI Part Record

View IPYNB Source
%%python

# CODE_RUNNER: Popcorn Hack 1 Check One SFI Part Record

part = {
    "product_name": "Replacement Flywheels and Clutch Assemblies",
    "category": "Auto Racing",
    "spec_number": "1.1",
    "effective_date": "Nov. 9, 2001"
}

valid_categories = ["Auto Racing", "Drag Racing"]
existing_spec_numbers = ["1.1", "2.1"]

def evaluate_create_rule(record):
    has_product_name = record["product_name"] != ""
    valid_category = record["category"] in valid_categories
    has_spec_number = record["spec_number"] != ""
    has_effective_date = record["effective_date"] != ""
    duplicate_spec = record["spec_number"] in existing_spec_numbers

    can_create_record = (
        has_product_name
        and valid_category
        and has_spec_number
        and has_effective_date
        and not duplicate_spec
    )

    print(f"Testing Spec {record['spec_number']} ({record['product_name']}):")
    print("  Duplicate Spec:", duplicate_spec)
    print("  Can Create Record:", can_create_record)
    if can_create_record:
        print("  Decision: ACCEPT RECORD (Create in Database)")
    else:
        print("  Decision: REJECT RECORD (Do Not Create)")

print("--- Case 1: Starter Record (Duplicate Spec 1.1) ---")
evaluate_create_rule(part)

# Valid non-duplicate test case
new_valid_part = {
    "product_name": "Bellhousing Safety Shield",
    "category": "Drag Racing",
    "spec_number": "1.5",
    "effective_date": "Sep. 15, 2026"
}

print("\n--- Case 2: New Valid Record (Spec 1.5) ---")
evaluate_create_rule(new_valid_part)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 3 - Random SFI API Test

View IPYNB Source
%%python

# CODE_RUNNER: Popcorn Hack 3 - Random SFI API Test

import random

parts = [
    {"product_name": "Replacement Flywheels", "spec_number": "1.1"},
    {"product_name": "Multiple Disc Clutch Assemblies", "spec_number": "1.2"},
    {"product_name": "Racing Flywheel Record", "spec_number": "2.1"}
]

actions = [
    "GET/search",
    "POST/create",
    "PUT/update"
]

selected_part = random.choice(parts)
selected_action = random.choice(actions)

if selected_action == "GET/search":
    print("Searching backend for record for part:", selected_part)
elif selected_action == "POST/create":
    print("Creating record for part:", selected_part)
elif selected_action == "PUT/update":
    print("Updating record for part:", selected_part)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
MCQ 3.05: 4/4 answers: A,C,A,B

Code Runner Challenge

Homework Hack

View IPYNB Source
%%python

# CODE_RUNNER: Homework Hack

# Homework Hack - SFI Backend QA Simulator

import random

parts = [
    {
        "product_name": "Replacement Flywheels",
        "category": "Auto Racing",
        "spec_number": "1.1"
    },
    {
        "product_name": "Multiple Disc Clutch Assemblies",
        "category": "Drag Racing",
        "spec_number": "1.2"
    },
    {
        "product_name": "Racing Flywheel Record",
        "category": "Auto Racing",
        "spec_number": "2.1"
    }
]

actions = [
    "GET/search",
    "POST/create",
    "PUT/update",
    "DELETE/remove"
]

existing_spec_numbers = ["1.1", "2.1"]
test_count = 4

# Build and test your QA simulator below.

def run_qa_test(test_number):
    selected_part = random.choice(parts)
    selected_action = random.choice(actions)
    spec = selected_part["spec_number"]
    name = selected_part["product_name"]

    print(f"--- Test {test_number} ---")
    print(f"Selected Part: {name} (Spec {spec}, {selected_part['category']})")
    print(f"Selected Action: {selected_action}")

    if selected_action == "GET/search":
        print(f"Result: Searching backend for '{name}' (Spec {spec})...")

    elif selected_action == "POST/create":
        duplicate_spec = spec in existing_spec_numbers
        if duplicate_spec:
            print(f"Result: REJECTED — Spec {spec} already exists in backend.")
        else:
            print(f"Result: ACCEPTED — Creating new record for '{name}' (Spec {spec}).")

    elif selected_action == "PUT/update":
        print(f"Result: Updating existing record for '{name}' (Spec {spec})...")

    elif selected_action == "DELETE/remove":
        print(f"Result: Removing record for '{name}' (Spec {spec}) from backend...")

    print()


for i in range(1, test_count + 1):
    run_qa_test(i)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Inputs Popcorn and HW Hacks

Challenge

Popcorn Hack Challenge - Using SASS Input

Lines: 1 Characters: 0
UI Output

Challenge

Homework Hack - Input Sign Ups

Lines: 1 Characters: 0
UI Output

Nested Conditionals

Code Runner Challenge

Popcorn Hack 1

View IPYNB Source
%% python

# CODE_RUNNER: Popcorn Hack 1

is_weekday = True
homework_finished = False

if is_weekday:
    if homework_finished:
        print("Free time")
    else:
        print("Finish homework")
else:
    print("Weekend plan")

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 1

View IPYNB Source
%% python

# CODE_RUNNER: Popcorn Hack 1

is_weekday = True
homework_finished = True

if is_weekday:
    if homework_finished:
        print("Free time")
    else:
        print("Finish homework")
else:
    print("Weekend plan")

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 1

View IPYNB Source
%% python

# CODE_RUNNER: Popcorn Hack 1

is_weekday = False
homework_finished = False

if is_weekday:
    if homework_finished:
        print("Free time")
    else:
        print("Finish homework")
else:
    print("Weekend plan")

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Outer branch: is_weekday → True Inner branch: homework_finished → False

Code Runner Challenge

Popcorn Hack 2

View IPYNB Source
%% python

# CODE_RUNNER: Popcorn Hack 2

logged_in = True
has_permission = False

if logged_in:
    print("Account found")
    if has_permission:
        print("Page opened")
    else:
        print("Permission needed")
else:
    print("Log in first")
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 2

View IPYNB Source
%% python

# CODE_RUNNER: Popcorn Hack 2

logged_in = False
has_permission = False

if logged_in:
    print("Account found")
    if has_permission:
        print("Page opened")
    else:
        print("Permission needed")
else:
    print("Log in first")
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 2

View IPYNB Source
%% python

# CODE_RUNNER: Popcorn Hack 2

logged_in = True
has_permission = True

if logged_in:
    print("Account found")
    if has_permission:
        print("Page opened")
    else:
        print("Permission needed")
else:
    print("Log in first")
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Popcorn Hack 2

View IPYNB Source
%% python

# CODE_RUNNER: Popcorn Hack 2

logged_in = False
has_permission = True

if logged_in:
    print("Account found")
    if has_permission:
        print("Page opened")
    else:
        print("Permission needed")
else:
    print("Log in first")
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
  1. the second if has_permission: was not indented inside if logged_in

Code Runner Challenge

Popcorn Hack 3

View IPYNB Source
%% python

# CODE_RUNNER: Popcorn Hack 3

lunch_packed = True
practice_after_school = True

if lunch_packed:
    if practice_after_school:
        print("Packed lunch and practice after school")
    else:
        print("Packed lunch and no practice after school")
else:
    if practice_after_school:
        print("Buy lunch and bring an extra snack for practice")
    else:
        print("Buy lunch and no practice after school")
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Lunch Practice Output True True Packed lunch and practice after school True False Packed lunch and no practice after school False True Buy lunch and bring an extra snack for practice False False Buy lunch and no practice after school

Code Runner Challenge

Homework Hack

View IPYNB Source
%% python

# CODE_RUNNER: Homework Hack

student = {
    "logged_in": True,
    "homework_finished": False,
    "lunch_packed": True,
    "practice_today": True
}

if student["logged_in"]:
    if student["homework_finished"]:
        print("Homework is finished.")

        if student["practice_today"]:
            if student["lunch_packed"]:
                print("Go to practice with your packed lunch plan.")
            else:
                print("Go to practice and plan to buy lunch.")
        else:
            print("No practice today. Enjoy your free time.")

    else:
        print("Finish your homework before moving on.")

        if student["practice_today"]:
            print("Finish homework before practice.")
        else:
            print("Finish homework before relaxing.")
else:
    print("Log in first to see your daily schedule.") 
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Test 1

“logged_in”: True “homework_finished”: True “lunch_packed”: True “practice_today”: True

Test 2

“logged_in”: True “homework_finished”: True “lunch_packed”: False “practice_today”: True

Test 3

“logged_in”: True “homework_finished”: True “lunch_packed”: True “practice_today”: False

Test 4

“logged_in”: True “homework_finished”: False “lunch_packed”: True “practice_today”: True

Test 5

“logged_in”: False “homework_finished”: True “lunch_packed”: True “practice_today”: True

Explanation

The outer logged_in condition is checked first because the student must be logged in before the program checks their schedule. The inner conditions depend on the outer decisions, so Python only checks homework, lunch, and practice after the appropriate outer branch is reached.

Libraries HW and Popcorn Hacks (review)

Code Runner Challenge

Libraries HW plus hacks

View IPYNB Source
%%python

# CODE_RUNNER: Libraries HW plus hacks

import math
import random

# Read the API before calling a procedure
print("random.randint:", random.randint.__doc__)
print("math.ceil:", math.ceil.__doc__)

points_per_game = [24, 18, 31, 27, 22]

# random.choice picks one item out of a list
print("Random game to review:", random.choice(points_per_game), "points")

# Changed the jersey range from 1-99 to 1-55
jersey = random.randint(1, 55)
print("Random jersey number:", jersey)

# Changed the court size from 144 to 225 square feet
side = math.sqrt(225)
print("Square court side:", side, "feet")

# math.ceil rounds up to the next whole number
average = sum(points_per_game) / len(points_per_game)
rounded_up = math.ceil(average)
print("Points per game:", average, "-> rounded up:", rounded_up)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Libraries HW plus hacks

View IPYNB Source
%%python

# CODE_RUNNER: Libraries HW plus hacks

from flask import Flask, jsonify

app = Flask(__name__)

# Original score route
@app.route("/score")
def score():
    return jsonify({
        "home": 72,
        "away": 65,
        "quarter": 4
    })

# Changed the roster
@app.route("/roster")
def roster():
    return jsonify({
        "players": ["Mateo", "Alex", "Jordan", "Chris"]
    })

# My extra route
@app.route("/coach")
def coach():
    return jsonify({
        "coach": "Coach Mateo",
        "message": "I wasn't expecting any slackers!"
    })

# Test the routes
client = app.test_client()

print("/score says:", client.get("/score").get_json())
print("/roster says:", client.get("/roster").get_json())
print("/coach says:", client.get("/coach").get_json())

Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Libraries HW plus hacks

View IPYNB Source
%% python

# CODE_RUNNER: Libraries HW plus hacks

import json
import statistics
from datetime import date

# My basketball season
games = [
    {
        "date": "2026-09-14",
        "opponent": "Lincoln",
        "points": 24,
        "minutes": 28
    },
    {
        "date": "2026-09-18",
        "opponent": "Madison",
        "points": 18,
        "minutes": 22
    },
    {
        "date": "2026-09-22",
        "opponent": "Lincoln",
        "points": 31,
        "minutes": 30
    },
    {
        "date": "2026-09-27",
        "opponent": "Roosevelt",
        "points": 27,
        "minutes": 26
    },
    {
        "date": "2026-10-02",
        "opponent": "Madison",
        "points": 22,
        "minutes": 25
    }
]


def summarize_season(season):
    """
    Summarize a list of basketball games.

    Parameters:
        season: list of dictionaries containing date, opponent,
                points, and minutes.

    Returns:
        A dictionary containing total points, average points,
        best game, and points scored against each opponent.
    """

    points = [game["points"] for game in season]

    points_by_opponent = {}

    for game in season:
        opponent = game["opponent"]

        if opponent not in points_by_opponent:
            points_by_opponent[opponent] = 0

        points_by_opponent[opponent] += game["points"]

    return {
        "total_points": sum(points),
        "average_points": round(statistics.mean(points), 1),
        "best_game": max(points),
        "points_by_opponent": points_by_opponent
    }


# Create the season report
report = summarize_season(games)

# My next game is October 15, 2026
next_game = date(2026, 10, 15)

days_until = (next_game - date.today()).days

report["days_until_next_game"] = days_until

# Display the report as JSON
print(json.dumps(report, indent=2))


# requirements.txt
# json, statistics, and datetime are part of Python's
# standard library, so they do not need to be installed.
requirements_txt = """pandas
Flask
"""

print()
print("requirements.txt:")
print(requirements_txt)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Strings HW and Hacks (optional since it’s from other class)


flowchart LR
    Student --> OCS
    OCS --> API
    API --> Database
flowchart LR
    67-kid --> ruined-rep.
    HawkTuahGirl --> ruined-rep.
    HawkTuahGirl --> rich
    67-kid <--> HawkTuahGirl
    ruined-rep. <--> rich
graph LR
    bazinga --> dummy