# Initialize Otter
import otter
grader = otter.Notebook("06_lab_for_loops.ipynb")
For Loops Lab - Scouting Report: Miami Hurricanes Basketball¶
Scenario: You're an assistant coach preparing a scouting report on the 2021-22 Miami Hurricanes men's basketball team. This squad went 26-11 and made it to the Elite Eight before falling to Kansas. Your job: analyze the roster data and build a complete scouting report using Python.
Reference: See lecture notebook 05_lecture_for_loops.ipynb for syntax help.
Important: Run cells in order from top to bottom. Each question uses unique variable names.
# 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 = "06_lab_for_loops.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 directory name and 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)}")
The Data: 2021-22 Miami Hurricanes Roster¶
The cell below loads the roster data you'll analyze throughout this lab. Each player is stored as a tuple — a group of values in a fixed order. The index constants (like NAME = 0, PPG = 8) let you access each field by name instead of memorizing numbers.
Run this cell first — every question depends on it.
# Index constants for accessing player data
NAME = 0
JERSEY = 1
POS = 2 # "G" (Guard), "F" (Forward), or "C" (Center)
YEAR = 3 # "Freshman", "Sophomore", "Junior", "Senior"
HEIGHT = 4 # e.g., "6-5"
GAMES = 5
GAMES_STARTED = 6
MPG = 7 # Minutes per game
PPG = 8 # Points per game
RPG = 9 # Rebounds per game
APG = 10 # Assists per game
SPG = 11 # Steals per game
BPG = 12 # Blocks per game
FG_PCT = 13 # Field goal percentage (0.0 to 1.0)
# 2021-22 Miami Hurricanes Men's Basketball
# Season: 26-11 overall, 14-6 ACC, Elite Eight (lost to Kansas)
# Source: Sports Reference (sports-reference.com)
roster = [
("Kameron McGusty", 23, "G", "Senior", "6-5", 37, 37, 34.1, 17.8, 4.9, 2.4, 1.8, 0.3, 0.476),
("Isaiah Wong", 2, "G", "Junior", "6-3", 37, 36, 33.9, 15.3, 4.3, 2.0, 0.9, 0.3, 0.452),
("Charlie Moore", 3, "G", "Senior", "5-11", 37, 37, 32.5, 12.4, 2.6, 4.6, 2.0, 0.1, 0.447),
("Jordan Miller", 11, "G", "Junior", "6-6", 36, 30, 30.8, 10.0, 5.9, 1.1, 1.8, 0.6, 0.561),
("Sam Waardenburg", 21, "F", "Senior", "6-10", 35, 34, 30.3, 8.5, 4.3, 2.1, 0.8, 1.3, 0.528),
("Anthony Walker", 1, "F", "Junior", "6-9", 37, 2, 14.0, 4.9, 2.5, 0.6, 0.8, 0.5, 0.462),
("Bensley Joseph", 4, "G", "Freshman", "6-1", 36, 0, 13.3, 2.3, 1.6, 0.8, 0.4, 0.1, 0.347),
("Wooga Poplar", 55, "G", "Freshman", "6-5", 34, 0, 8.6, 2.3, 1.4, 0.3, 0.3, 0.0, 0.412),
("Rodney Miller Jr.", 14, "C", "Senior", "7-0", 18, 5, 4.2, 1.5, 0.6, 0.1, 0.1, 0.1, 0.625),
("Deng Gak", 22, "F", "Junior", "6-11", 26, 4, 4.9, 0.9, 0.7, 0.2, 0.1, 0.2, 0.533),
("Harlond Beverly", 5, "G", "Junior", "6-5", 4, 0, 9.3, 0.5, 1.8, 1.3, 0.5, 0.0, 0.143),
("Thomas Oosterbroek", 32, "F", "Freshman", "6-7", 4, 0, 1.3, 0.3, 0.0, 0.0, 0.3, 0.0, 0.000),
("Filippos Gkogkos", 10, "G", "Junior", "6-3", 6, 0, 1.0, 0.0, 0.2, 0.0, 0.0, 0.0, 0.000),
]
print(f"Roster loaded: {len(roster)} players")
The Big Picture: A Complete Scouting Report¶
Here's what you're building toward. Run this cell to see a full scouting report generated entirely from the roster data. Don't worry about the code — it uses Python shortcuts (max(), list comprehensions) that you haven't learned yet. Focus on the output. By the end of this lab, you'll build every piece of this report yourself using for loops.
def scout_team(team_roster):
"""Generate a scouting report for an opposing coach.
This uses Python shortcuts you haven't learned yet (max, sum,
list comprehensions). You'll build the same logic with for loops.
"""
# Private helper — you'll write your own version of this in Q4
def _rate(p):
return (p[PPG] * 2) + (p[RPG] * 1.5) + (p[APG] * 1.5)
print("=" * 55)
print(" OPPONENT SCOUTING REPORT")
print(" Miami Hurricanes - 2021-22 Season (26-11)")
print("=" * 55)
top_scorer = max(team_roster, key=lambda p: p[PPG])
print(f"\nPRIMARY THREAT: #{top_scorer[JERSEY]} {top_scorer[NAME]}")
print(f" Leads the team at {top_scorer[PPG]} PPG on {round(top_scorer[FG_PCT] * 100, 1)}% shooting.")
print(f" A {top_scorer[HEIGHT]} {top_scorer[YEAR].lower()} — expect him to be aggressive.")
guards = [p for p in team_roster if p[POS] == "G"]
guard_avg = round(sum(p[PPG] for p in guards) / len(guards), 1)
print(f"\nBACKCOURT: {len(guards)} guards averaging {guard_avg} PPG each.")
print(" This team lives and dies by their perimeter play.")
best_rebounder = max(team_roster, key=lambda p: p[RPG])
print(f"\nINSIDE PRESENCE: #{best_rebounder[JERSEY]} {best_rebounder[NAME]}")
print(f" Leads the boards at {best_rebounder[RPG]} RPG. Box out early.")
top_thief = max(team_roster, key=lambda p: p[SPG])
print(f"\nDEFENSIVE ALERT: #{top_thief[JERSEY]} {top_thief[NAME]}")
print(f" Averages {top_thief[SPG]} steals/game. Protect the ball in transition.")
seniors = sum(1 for p in team_roster if p[YEAR] == "Senior")
print(f"\nEXPERIENCE: {seniors} seniors on the roster.")
print(" This is a veteran squad that won't rattle easily.")
mvp = max(team_roster, key=_rate)
print(f"\nMVP: #{mvp[JERSEY]} {mvp[NAME]} (rating: {round(_rate(mvp), 1)})")
print(" The complete package — scores, rebounds, and distributes.")
print("\n" + "=" * 55)
print(" BOTTOM LINE: Dangerous team. Guard-heavy, experienced,")
print(" and battle-tested. Don't let McGusty get going early.")
print("=" * 55)
scout_team(roster)
The scouting report above finds top scorers, counts positions, computes averages, and rates players — all tasks you'll tackle in this lab. The function uses Python shortcuts like max() and list comprehensions, but you'll build the same logic using for loops — a more fundamental approach that teaches you how these shortcuts work under the hood.
1. Tuples, Index Constants & String Padding¶
Before we start writing loops, let's understand the data structure we're working with.
What is a tuple?¶
A tuple is like a row in a spreadsheet — multiple values grouped together. In lecture, we used separate lists for song names, artists, and play counts. Tuples let us group all the data for one item together.
# A tuple is a row of data — multiple values grouped together
first_player = roster[0]
print(first_player)
print(type(first_player))
# Access individual fields by position (index)
print(f"Name: {first_player[0]}")
print(f"PPG: {first_player[8]}")
Index constants make code readable¶
Remembering that index 8 means "points per game" is hard. Index constants are just regular variables that hold numbers — PPG = 8 means "points per game is at position 8 in the tuple." We'll see better ways to organize data later in the course (dictionaries, classes), but this works well for now.
# Hard to read: what is index 8?
print(roster[0][8])
# Easy to read: PPG is clear
print(roster[0][PPG])
# Access any stat for any player
for player in roster[:3]: # Just first 3 for now
print(f"{player[NAME]} scores {player[PPG]} PPG and grabs {player[RPG]} RPG")
String padding for formatted output¶
When printing tables, you want columns to line up neatly. F-string alignment operators control how wide a value is printed:
| Syntax | Meaning | Example |
|---|---|---|
:<20 |
Left-align in 20 characters | "McGusty " |
:>20 |
Right-align in 20 characters | " McGusty" |
:^20 |
Center in 20 characters | " McGusty " |
The syntax is f"{value:alignment width}". The alignment character goes BEFORE the width number: < for left, > for right, ^ for center.
# String padding: control how wide a value is printed
name = "McGusty"
# Left-align in 20 characters (pad with spaces on the right)
print(f"Left: '{name:<20}'")
# Right-align in 20 characters (pad with spaces on the left)
print(f"Right: '{name:>20}'")
# Center in 20 characters
print(f"Center: '{name:^20}'")
# Works with numbers too — great for jersey numbers
jersey = 2
print(f"\nJersey: #{jersey:>2}") # Right-align in 2 chars: " 2"
print(f"Jersey: #{jersey:<2}") # Left-align in 2 chars: "2 "
This is how we'll make the roster table look professional instead of having ragged columns.
Question 1: Print the Roster (2 points)¶
Print a formatted roster table showing each player's jersey number, name, position, and class year. Use string padding to align the columns neatly. Store the full output string in roster_display.
Your output should look like this:
#23 Kameron McGusty G Senior
# 2 Isaiah Wong G Junior
# 3 Charlie Moore G Senior
...
Hint: Use f"#{player[JERSEY]:>2}" to right-align jersey numbers in 2 characters, and f"{player[NAME]:<22}" to left-align names in 22 characters.
# ✏️ YOUR CODE HERE
roster_display = ...
...
...
print(roster_display)
grader.check("q1_roster_display")
2. Filtering and Counting¶
A common pattern: loop through data, check a condition, and count or sum only the items that match. This is the same counting pattern from earlier lectures — start at 0, add 1 when the condition is true.
# Filtering pattern: combine counting and summing in one loop
guard_total_ppg = 0.0
guard_count = 0
for player in roster:
if player[POS] == "G":
guard_total_ppg += player[PPG]
guard_count += 1
guard_avg = round(guard_total_ppg / guard_count, 2)
print(f"Guards: {guard_count} players, averaging {guard_avg} PPG")
Question 2: Upperclassman Analysis (3 points)¶
An opposing coach wants to know how experienced this Miami team is. Count the number of upperclassmen (Juniors and Seniors) on the roster and calculate their average points per game.
Store the count in upperclass_count and the average in upperclass_avg_ppg. Use round() to round the average to 2 decimal places.
# ✏️ YOUR CODE HERE
upperclass_count = ...
upperclass_total_ppg = ...
...
...
...
...
upperclass_avg_ppg = ...
print(f"Upperclassmen: {upperclass_count} players, averaging {upperclass_avg_ppg} PPG")
grader.check("q2_upperclass")
3. Functions: Filling In the Body¶
A function packages up reusable logic. In the scouting report above, we wrote the same "find the best player" pattern multiple times. A function lets us write it once and reuse it.
In lecture, we SHOWED you generate_wrapped(). Now you're going to BUILD functions like it.
For the next question, you'll see a function with the def line, docstring, and return already written. Your job: fill in the body (the part that does the work).
# A function packages up reusable logic
def count_seniors(team_roster):
"""Count the number of seniors on a roster."""
senior_count = 0
for player in team_roster:
if player[YEAR] == "Senior":
senior_count += 1
return senior_count
# Now we can call it
print(f"Seniors: {count_seniors(roster)}")
Notice the function takes team_roster as a parameter — not roster. This means we could pass in ANY roster, not just Miami's. That's what makes functions reusable.
Question 3: Find the Top Scorer (3 points)¶
Complete the function below that finds the top scorer on a team. The function receives a roster (list of player tuples) and should return the player tuple with the highest points per game.
Remember the max tracking pattern from lecture: assume the first item is the best, then update when you find something better.
def find_top_scorer(team_roster):
"""Find the player with the highest PPG on a roster.
Args:
team_roster: A list of player tuples.
Returns:
The player tuple with the highest PPG.
"""
best_player = ...
...
...
...
# Test it
top = find_top_scorer(roster)
print(f"Top scorer: {top[NAME]} ({top[PPG]} PPG)")
grader.check("q3_top_scorer")
4. Writing Functions from Scratch¶
So far, we gave you the function name, parameters, and docstring. Now YOU decide how to structure the function.
Think about:
- What does this function need to know? (parameters)
- What does it give back? (return value)
- What should it be called? (descriptive name)
# Example: Write a function that calculates a player's total contribution
# (points + rebounds + assists per game)
# Step 1: What should it be called? -> total_contribution
# Step 2: What does it need? -> ppg, rpg, apg
# Step 3: What does it return? -> the sum
def total_contribution(ppg, rpg, apg):
"""Calculate a player's total stat contribution per game."""
return ppg + rpg + apg
# Test it
print(total_contribution(17.8, 4.9, 2.4)) # McGusty: 25.1
Question 4: Player Rating Calculator (3 points)¶
Write a function called calculate_player_rating that computes an overall performance rating for a player. The function should accept three numbers representing a player's scoring average, rebounding average, and assist average.
The rating formula weights scoring most heavily at double value, while rebounding and playmaking each contribute at one-and-a-half times their value. The function should return the calculated rating.
# ✏️ YOUR CODE HERE
...
# Test it
print(f"McGusty rating: {calculate_player_rating(17.8, 4.9, 2.4)}")
print(f"Wong rating: {calculate_player_rating(15.3, 4.3, 2.0)}")
grader.check("q4_player_rating")
5. Function Composition¶
One of the most powerful ideas in programming: one function can call another function. This lets you build complex behavior from simple building blocks.
# Function composition: one function calls another
def is_starter(player):
"""Check if a player started most games they played."""
return player[GAMES_STARTED] > player[GAMES] / 2
def count_starters(team_roster):
"""Count how many players are starters, using is_starter()."""
starter_count = 0
for player in team_roster:
if is_starter(player): # <-- calling the helper function!
starter_count += 1
return starter_count
print(f"Starters: {count_starters(roster)}")
Notice how count_starters calls is_starter inside its loop. This is function composition — building complex behavior from simple building blocks. Your next task uses this exact pattern: you'll write a function that calls calculate_player_rating from Question 4.
Question 5: Find the MVP (3 points)¶
Write a function called find_mvp that finds the most valuable player on a roster based on their overall rating. Your function should use calculate_player_rating from Question 4 to compute each player's rating, then determine which player has the highest rating.
Think about what your function needs to accept and what it should return.
# ✏️ YOUR CODE HERE
...
# Test it
mvp = find_mvp(roster)
print(f"MVP: {mvp[NAME]} (rating: {calculate_player_rating(mvp[PPG], mvp[RPG], mvp[APG])})")
grader.check("q5_find_mvp")
Summary¶
| Concept | Pattern | Scouting Report Example |
|---|---|---|
| Basic for loop | for player in roster: |
Print the roster table |
| Index constants | player[PPG] |
Access any stat by name |
| String padding | f"{name:<22}" |
Aligned roster columns |
| Filtering | if player[POS] == "G": |
Count guards |
| Accumulator | total += player[PPG] |
Average PPG |
| Max tracking | if val > best: best = val |
Find top scorer |
round() |
round(value, 2) |
Clean decimal output |
| Fill in function | Given signature, write body | find_top_scorer() |
| Write function | Design from description | calculate_player_rating() |
| Function composition | Call one function from another | find_mvp() uses calculate_player_rating() |
Key takeaways:
- For loops process each item in a collection one at a time
- Index constants make tuple access readable:
player[PPG]vsplayer[8] - String padding (
:<,:>) creates aligned, professional-looking output - Functions package reusable logic — fill in, then write your own
- Functions can call other functions to build complex behavior from simple pieces
- The same patterns (count, sum, max) work on any data, not just basketball
Submitting to Gradescope¶
This file is saved on your computer — you do not need to download it from Jupyter.
Find the file on your computer:
- Mac: Open Finder →
Documents/CSC115/lab_notebooks/06_lab_for_loops/06_lab_for_loops.ipynb - Windows: Open File Explorer →
Documents\CSC115\lab_notebooks\06_lab_for_loops\06_lab_for_loops.ipynb
- Mac: Open Finder →
Upload to Gradescope:
- Go to gradescope.com and open this assignment
- Click "Submit" and upload the
.ipynbfile - The filename must be exactly
06_lab_for_loops.ipynb
Do NOT use File > Download in Jupyter — this can rename the file and cause submission errors.
You have completed the For Loops Lab. Go Canes!
To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()