# Initialize Otter
import otter
grader = otter.Notebook("05_lab_while_loops.ipynb")
While Loops Lab - Wordle¶
Scenario: You're building a Wordle game in Python! You'll write functions that check guesses, generate feedback, score guesses, validate input, filter word lists, and play complete games. The lab ends with two interactive Wordle games: a blind version (just feedback) and a smart version (feedback + dictionary filtering) so you can see how effective your code is at reducing guesses.
Reference: See lecture notebook 04_lecture_while_loops.ipynb for syntax help.
Important: Run cells in order from top to bottom. Each question asks you to write the body of a function.
# Validation: Check Python version and file location
import os
import random
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 = "05_lab_while_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)}")
How Wordle Works¶
Wordle is a word-guessing game where you have 6 attempts to guess a secret 5-letter word.
After each guess, you get feedback on each letter:
- G (Green): The letter is in the correct position
- Y (Yellow): The letter is in the word but in the wrong position
- - (Gray): The letter is not in the word at all
Example: If the secret word is crate and you guess crane:
| Position | Guess | Secret | Feedback | Reason |
|---|---|---|---|---|
| 0 | c | c | G | Same letter, same position |
| 1 | r | r | G | Same letter, same position |
| 2 | a | a | G | Same letter, same position |
| 3 | n | t | - | 'n' is not in "crate" |
| 4 | e | e | G | Same letter, same position |
Result: "GGG-G" (4 greens, 1 gray)
In this lab, you'll build the logic for this game step by step using while loops and functions.
Quick Review: Functions¶
In lecture, you saw functions like find_parking() and check_for_spot(). In this lab, you'll write the body of functions. The def line, docstring, starting variables, and return are already provided. You fill in the while loop logic in the middle.
Example of what you'll see:
def count_something(words):
"""Count how many words have 5 letters."""
count = 0
index = 0
... # <-- You write the while loop here
...
...
return count
Replace the ... lines with your while loop code. The function skeleton tells you what variables to use and what to return.
WORD_LIST = [
"about", "above", "abuse", "actor", "adapt", "admit", "adopt", "adult",
"after", "again", "agent", "agree", "ahead", "alarm", "album", "alert",
"alien", "align", "alive", "allow", "alone", "along", "alter", "amaze",
"among", "ample", "angel", "anger", "angle", "angry", "anime", "ankle",
"apart", "apple", "apply", "arena", "argue", "arise", "armor", "array",
"aside", "asset", "atlas", "audio", "avoid", "awake", "award", "aware",
"badge", "basic", "basin", "batch", "beach", "begin", "being", "bench",
"berry", "birth", "black", "blade", "blame", "bland", "blank", "blast",
"blaze", "bleed", "blend", "bless", "blind", "block", "bloom", "blown",
"board", "bonus", "booth", "bound", "brain", "brand", "brave", "bread",
"break", "breed", "brick", "bride", "brief", "bring", "broad", "broke",
"brook", "brown", "brush", "buddy", "build", "built", "bunch", "burst",
"buyer", "cabin", "cable", "candy", "cargo", "carry", "catch", "cause",
"cedar", "chain", "chair", "chalk", "charm", "chart", "chase", "cheap",
"check", "cheek", "cheer", "chess", "chest", "chief", "child", "chill",
"china", "choir", "chose", "chunk", "civic", "claim", "clash", "class",
"clean", "clear", "clerk", "click", "cliff", "climb", "cling", "clock",
"clone", "close", "cloth", "cloud", "clown", "coach", "coast", "color",
"comet", "comic", "coral", "couch", "could", "count", "court", "cover",
"crack", "craft", "crane", "crash", "crate", "crazy", "cream", "creek",
"crime", "crisp", "cross", "crowd", "crown", "cruel", "crush", "curve",
"cycle", "daily", "dairy", "dance", "death", "debug", "decay", "delay",
"demon", "dense", "depth", "derby", "devil", "diary", "dirty", "ditch",
"doing", "donor", "doubt", "dough", "draft", "drain", "drama", "drawn",
"dream", "dress", "dried", "drift", "drill", "drink", "drive", "drone",
"drown", "drunk", "dryer", "dwell", "dying", "eager", "eagle", "early",
"earth", "eight", "elect", "elite", "email", "ember", "empty", "enemy",
"enjoy", "enter", "equal", "equip", "erase", "error", "essay", "event",
"every", "exact", "exams", "exist", "extra", "fable", "faith", "fancy",
"fatal", "fault", "feast", "fence", "ferry", "fetch", "fever", "fiber",
"field", "fight", "final", "first", "flame", "flash", "fleet", "flesh",
"float", "flock", "flood", "floor", "flour", "fluid", "flush", "flute",
"focus", "force", "forge", "forth", "forum", "found", "frame", "fraud",
"fresh", "front", "frost", "froze", "fruit", "fully", "funny", "ghost",
"giant", "given", "glass", "gleam", "globe", "gloom", "glory", "glove",
"glyph", "going", "grace", "grade", "grain", "grand", "grant", "grape",
"graph", "grasp", "grass", "grave", "great", "greed", "green", "greet",
"grief", "grill", "grind", "groan", "groom", "gross", "group", "grove",
"growl", "grown", "guard", "guess", "guide", "guilt", "habit", "happy",
"harsh", "haste", "hatch", "haunt", "haven", "heart", "heavy", "hedge",
"hello", "hence", "hilly", "hinge", "hobby", "honey", "honor", "horse",
"hotel", "house", "hover", "human", "humor", "hurry", "ideal", "image",
"imply", "index", "inner", "input", "ivory", "jewel", "joint", "joker",
"judge", "juice", "jumbo", "kayak", "knack", "kneel", "knife", "knock",
"known", "label", "labor", "large", "laser", "latch", "later", "laugh",
"layer", "learn", "lease", "leave", "legal", "lemon", "level", "light",
"limit", "linen", "liver", "llama", "local", "lodge", "logic", "loose",
"lover", "lower", "loyal", "lucky", "lunch", "lymph", "lyric", "magic",
"major", "manor", "maple", "march", "match", "mayor", "media", "melon",
"mercy", "merge", "merit", "metal", "meter", "might", "minor", "minus",
"model", "money", "month", "moral", "motor", "mound", "mount", "mouse",
"mouth", "movie", "mural", "music", "naive", "nasty", "naval", "nerve",
"never", "night", "noble", "noise", "north", "notch", "novel", "nurse",
"nymph", "occur", "ocean", "olive", "onset", "opera", "orbit", "order",
"organ", "other", "ought", "outer", "oxide", "ozone", "paint", "panel",
"panic", "paper", "party", "paste", "patch", "pause", "peace", "peach",
"pearl", "pedal", "penny", "perch", "phase", "phone", "photo", "piano",
"piece", "pilot", "pinch", "pitch", "pixel", "pizza", "place", "plaid",
"plain", "plane", "plant", "plate", "plaza", "plead", "plumb", "plume",
"plump", "point", "polar", "porch", "pound", "power", "press", "price",
"pride", "prime", "print", "prior", "prize", "probe", "proof", "proud",
"prove", "prune", "pulse", "punch", "pupil", "purse", "queen", "query",
"quest", "quick", "quiet", "quota", "quote", "radar", "radio", "raise",
"rally", "ranch", "range", "rapid", "ratio", "reach", "ready", "realm",
"rebel", "reign", "relax", "relay", "ridge", "right", "rigid", "risky",
"rival", "river", "roast", "robin", "robot", "rocky", "rogue", "round",
"route", "royal", "rumor", "rural", "saint", "salad", "salon", "sandy",
"sauce", "scale", "scare", "scene", "scope", "score", "scout", "sense",
"serve", "seven", "shade", "shake", "shall", "shame", "shape", "share",
"shark", "sharp", "shave", "sheep", "sheer", "sheet", "shelf", "shell",
"shift", "shine", "shirt", "shock", "shore", "short", "shout", "shove",
"shrub", "sight", "silly", "since", "sixth", "sixty", "skill", "skull",
"slash", "slate", "slave", "sleep", "slice", "slide", "slope", "smart",
"smell", "smile", "smoke", "snack", "snake", "solar", "solid", "solve",
"sorry", "sound", "south", "space", "spare", "spark", "speak", "speed",
"spend", "spice", "spine", "spite", "split", "spoke", "spoon", "sport",
"spray", "squad", "squid", "stack", "staff", "stage", "stain", "stair",
"stake", "stale", "stall", "stamp", "stand", "stare", "start", "state",
"steak", "steal", "steam", "steel", "steep", "steer", "stern", "stick",
"stiff", "still", "sting", "stock", "stomp", "stone", "stood", "stool",
"store", "storm", "story", "stove", "strap", "straw", "stray", "strip",
"stuck", "study", "stuff", "stump", "stung", "stunt", "style", "sugar",
"suite", "super", "surge", "swamp", "swear", "sweat", "sweep", "sweet",
"swept", "swift", "swing", "swirl", "sword", "swore", "table", "taste",
"teach", "tempo", "tense", "theft", "theme", "there", "thick", "thief",
"thing", "think", "third", "thorn", "those", "three", "threw", "throw",
"thumb", "tiger", "tight", "timer", "tired", "title", "toast", "today",
"token", "topic", "torch", "total", "touch", "tough", "towel", "tower",
"toxic", "trace", "track", "trade", "trail", "train", "trait", "trash",
"treat", "trend", "trial", "tribe", "trick", "troop", "truck", "truly",
"trunk", "trust", "truth", "tulip", "tumor", "twice", "twist", "ultra",
"uncle", "under", "union", "unite", "unity", "until", "upper", "upset",
"urban", "usage", "usual", "utter", "valid", "value", "valve", "vapor",
"vault", "venue", "verse", "video", "vigor", "vinyl", "viral", "virus",
"visit", "vital", "vivid", "vocal", "voice", "voter", "wagon", "waist",
"waste", "watch", "water", "weary", "weave", "wedge", "weigh", "weird",
"whale", "wheat", "wheel", "where", "which", "while", "white", "whole",
"whose", "woman", "world", "worry", "worse", "worst", "worth", "would",
"wound", "wrath", "wrist", "write", "wrote", "yacht", "yearn", "yield",
"young", "youth", "zebra",
]
print(f"Word list loaded: {len(WORD_LIST)} words")
Question 1: Count Exact Matches (1 point)¶
Write a function that counts how many positions have the exact same letter in both the guess and the secret word.
Use a while loop to check each position from 0 to 4. Compare guess[position] to secret[position]. If they match, add 1 to the count.
Example: count_exact_matches("crane", "crate") returns 4 (positions 0, 1, 2, and 4 match).
def count_exact_matches(guess, secret):
"""Count positions where guess and secret have the same letter."""
position = 0
matches = 0
...
...
...
return matches
# Test it
print(f'count_exact_matches("crane", "crate") = {count_exact_matches("crane", "crate")}')
grader.check("q1_count_exact_matches")
# Try your function! Enter two 5-letter words to compare.
try_guess = input("Enter a guess (5 letters): ")
try_secret = input("Enter the secret word (5 letters): ")
result = count_exact_matches(try_guess, try_secret)
print(f"Exact matches: {result}")
Question 2: Generate Feedback (2 points)¶
Write the core Wordle feedback function. For each position, check:
- If the letter matches the same position in the secret word, add
"G"(green) - Otherwise, if the letter appears anywhere in the secret word (use the
inoperator), add"Y"(yellow) - Otherwise, add
"-"(gray)
Build the feedback string one character at a time using string concatenation (+=).
Example: generate_feedback("crane", "crate") returns "GGG-G"
def generate_feedback(guess, secret):
"""Generate Wordle feedback: G (green), Y (yellow), or - (gray) for each position."""
feedback = ""
position = 0
...
...
...
...
...
return feedback
# Test it
print(f'generate_feedback("crane", "crate") = "{generate_feedback("crane", "crate")}"')
grader.check("q2_generate_feedback")
# Try your function!
try_guess = input("Enter a guess (5 letters): ")
try_secret = input("Enter the secret word (5 letters): ")
print(f"Feedback: {generate_feedback(try_guess, try_secret)}")
Question 3: Score Guess (1 point)¶
Write a function that scores a single Wordle guess. Check each position:
- Exact match (green): 2 points
- Letter in word but wrong position (yellow): 1 point
- Letter not in word (gray): 0 points
Accumulate the total score using a running total.
Example: score_guess("crane", "crate") returns 8 (c:2 + r:2 + a:2 + n:0 + e:2 = 8)
def score_guess(guess, secret):
"""Score a Wordle guess. Green=2, Yellow=1, Gray=0."""
score = 0
position = 0
...
...
...
...
return score
# Test it
print(f'score_guess("crane", "crate") = {score_guess("crane", "crate")}')
grader.check("q3_score_guess")
# Try your function!
try_guess = input("Enter a guess (5 letters): ")
try_secret = input("Enter the secret word (5 letters): ")
print(f"Score: {score_guess(try_guess, try_secret)} points")
Question 4: Validate Guess (1 point)¶
Write a function that loops through a list of guess strings and finds the first valid one. A guess is valid if it is exactly 5 letters long AND it appears in the word list.
Use continue to skip invalid guesses. When you find a valid guess, return it immediately along with how many guesses you checked.
If no valid guess is found, the function falls through to return ("", index) at the end.
Example: validate_guess(["hi", "ab", "crane"], WORD_LIST) returns ("crane", 3) because "hi" and "ab" are skipped (wrong length) and "crane" is the 3rd guess checked.
def validate_guess(guesses, word_list):
"""Find the first valid guess. Returns (valid_guess, count_checked)."""
index = 0
...
guess = ...
...
...
...
...
return ("", index)
# Test it
print(f'validate_guess(["crane"], WORD_LIST) = {validate_guess(["crane"], WORD_LIST)}')
print(f'validate_guess(["hi", "ab", "crane"], WORD_LIST) = {validate_guess(["hi", "ab", "crane"], WORD_LIST)}')
grader.check("q4_validate_guess")
# Try your function! Enter guesses separated by commas.
raw_input = input("Enter guesses separated by commas (e.g. hi,crane,test): ")
guess_list = [g.strip().lower() for g in raw_input.split(",")]
valid, checked = validate_guess(guess_list, WORD_LIST)
if valid:
print(f'First valid guess: "{valid}" (checked {checked} guesses)')
else:
print(f"No valid guess found after checking {checked} guesses.")
Question 5: Filter Words (2 points)¶
This is the "brain" of Smart Wordle. Write the inner while loop that checks whether a single word matches the feedback from a guess.
The outer while loop (which goes through each word in the list) is already provided. For each word, you need to check each position:
- If feedback is
"G": the word must have the same letter at that position as the guess - If feedback is
"Y": the word must contain the letter somewhere, but not at that position - If feedback is
"-": the word must not contain the letter at all
If any position fails, set is_valid = False and break out of the inner loop.
Example: After guessing "crane" with feedback "GGG-G" against secret "crate", the word "crash" would fail (position 3: feedback is "-" for 'n', but we need position 3 to not be 'n' - it's 's', and 'n' not in "crash", so that's fine. Position 4: feedback is "G" for 'e', but "crash" has 'h' at position 4, so it fails).
def filter_words(words, guess, feedback):
"""Filter word list to only words that match the given feedback."""
matching = []
word_index = 0
while word_index < len(words):
word = words[word_index]
is_valid = True
position = 0
...
...
...
...
...
if is_valid:
matching.append(word)
word_index += 1
return matching
# Test it
q5_result = filter_words(["crate", "crane", "crash", "cream"], "crane", "GGG-G")
print(f'filter_words with "crane"/"GGG-G": {q5_result}')
grader.check("q5_filter_words")
# Try your filter! Enter a guess and feedback to see matching words.
try_guess = input("Enter your guess (5 letters): ")
try_feedback = input("Enter feedback (5 chars, G/Y/-): ").upper()
matches = filter_words(WORD_LIST, try_guess, try_feedback)
print(f"\nMatching words: {len(matches)}")
if len(matches) <= 20:
print(f"Words: {matches}")
else:
print(f"First 20: {matches[:20]}...")
Question 6: Play Round (2 points)¶
Write a function that plays one round of Wordle. The function receives a secret word and a list of guesses. It should:
- Loop through guesses one at a time (max 6 attempts)
- Use
generate_feedback()to get feedback for each guess - If the feedback is
"GGGGG", the player won - setwon = Trueandbreak - Stop after 6 attempts even if there are more guesses available
This function uses your generate_feedback from Question 2.
Example: play_round("crate", ["crane", "stare", "plate", "crate"]) returns (True, 4, "GGGGG")
def play_round(secret, guesses):
"""Play one round of Wordle. Returns (won, attempts, last_feedback)."""
attempts = 0
max_attempts = 6
won = False
last_feedback = ""
...
guess = ...
last_feedback = ...
...
...
return (won, attempts, last_feedback)
# Test it
q6_result = play_round("crate", ["crane", "stare", "plate", "crate"])
print(f"Result: {q6_result}")
grader.check("q6_play_round")
# Try a quick game! Enter guesses one at a time.
secret = random.choice(WORD_LIST)
guesses = []
print("Guess a 5-letter word (up to 6 attempts):")
attempt = 0
while attempt < 6:
g = input(f"Attempt {attempt + 1}/6: ").lower().strip()
if len(g) != 5:
print(" Must be exactly 5 letters.")
continue
guesses.append(g)
fb = generate_feedback(g, secret)
print(f" Feedback: {fb}")
attempt += 1
if fb == "GGGGG":
print(f"\nYou got it in {attempt} attempts!")
break
else:
print(f"\nOut of attempts! The word was: {secret}")
Debugging Infinite Loops¶
Sometimes a while loop runs forever because the condition never becomes False. This is called an infinite loop.
How to recognize it: The cell shows [*] instead of a number. It means the cell is still running.
How to stop it: Go to Kernel > Interrupt (or press I twice in command mode).
Common causes:
- Forgetting to increment the counter
- Incrementing inside an
ifblock that rarely runs - Using the wrong variable in the condition
Debugging strategy: Add print() statements to see what your variables look like each iteration. If a variable never changes, that's your bug!
Question 7: Fix the Broken Game (1 point)¶
The function below has a bug that causes an infinite loop. The attempts += 1 line is inside the if block, so it only runs when the guess is correct. That means the loop never progresses through the guesses!
Instructions:
- Read the broken code below and understand the bug
- In the answer cell, the function is rewritten with one line replaced by
... - Fill in the missing line to fix the bug (move
attempts += 1to the correct location) - Call the fixed function and store the results
# READ THIS CODE - it has a bug! (Do NOT modify this cell)
# Notice: attempts += 1 is INSIDE the if block.
# It only increments when the guess is correct, causing an infinite loop.
def play_broken_round(secret, guesses):
attempts = 0
won = False
last_feedback = ""
while attempts < 6 and not won:
guess = guesses[attempts]
last_feedback = generate_feedback(guess, secret)
if guess == secret:
won = True
attempts += 1 # BUG: only runs when guess is correct!
return (won, attempts, last_feedback)
# WARNING: Uncomment the line below to see the infinite loop, then interrupt the kernel.
# play_broken_round("crate", ["crane", "stare", "plate", "crate"])
print("Read the code above. The bug is that attempts += 1 is inside the if block.")
print("Fix it in the next cell by placing attempts += 1 OUTSIDE the if block.")
# Fix the function by filling in the missing line.
# Move "attempts += 1" to run EVERY iteration, not just on correct guesses.
def play_fixed_round(secret, guesses):
"""Play a round of Wordle (fixed version)."""
attempts = 0
won = False
last_feedback = ""
while attempts < 6 and not won:
guess = guesses[attempts]
last_feedback = generate_feedback(guess, secret)
...
if guess == secret:
won = True
return (won, attempts, last_feedback)
debug_result = play_fixed_round("crate", ["crane", "stare", "plate", "crate", "hello", "audio"])
debug_won = debug_result[0]
debug_attempts = debug_result[1]
print(f"Won: {debug_won}")
print(f"Attempts: {debug_attempts}")
grader.check("q7_debug")
Question 8: Play Tournament (2 points)¶
Write a function that plays multiple Wordle games and tracks statistics. The function receives a list of secret words and a list of guess lists (one per game).
For each game, call play_round() and track:
- Total games played
- Number of wins
- Total attempts across all games
- Best score (fewest attempts in any single winning game)
Example: With 3 games where you win in 4, 2, and 6 attempts, the stats would be: games=3, wins=3, total_attempts=12, best=2.
def play_tournament(secrets, all_guesses):
"""Play multiple Wordle games. Returns (games, wins, total_attempts, best)."""
game_index = 0
games = 0
wins = 0
total_attempts = 0
best = 0
...
won, attempts, feedback = ...
...
...
...
...
...
return (games, wins, total_attempts, best)
# Test it
secrets = ["crate", "hello", "lymph"]
all_guesses = [
["crane", "stare", "plate", "crate"],
["hello"],
["crane", "stare", "plate", "blunt", "grape", "audio"],
]
q8_result = play_tournament(secrets, all_guesses)
print(f"Tournament: {q8_result}")
grader.check("q8_play_tournament")
# Play a mini-tournament! 3 random games.
t_secrets = [random.choice(WORD_LIST) for _ in range(3)]
print("Play 3 Wordle games!")
t_all_guesses = []
for game_num in range(3):
print(f"\n--- Game {game_num + 1} ---")
game_guesses = []
for attempt in range(6):
g = input(f" Attempt {attempt + 1}/6: ").lower().strip()
if len(g) != 5:
print(" Must be 5 letters.")
continue
game_guesses.append(g)
fb = generate_feedback(g, t_secrets[game_num])
print(f" Feedback: {fb}")
if fb == "GGGGG":
print(f" Correct! Found in {attempt + 1} attempts!")
break
else:
print(f" The word was: {t_secrets[game_num]}")
t_all_guesses.append(game_guesses)
result = play_tournament(t_secrets, t_all_guesses)
print(f"\nTournament results: {result[1]}/{result[0]} wins, {result[2]} total attempts, best: {result[3]}")
# BLIND WORDLE - just feedback, no help!
blind_secret = random.choice(WORD_LIST)
blind_attempts = 0
blind_won = False
print("=== BLIND WORDLE ===")
print("Guess the 5-letter word! You have 6 attempts.")
print()
while blind_attempts < 6 and not blind_won:
blind_guess = input(f"Attempt {blind_attempts + 1}/6: ").lower().strip()
if len(blind_guess) != 5:
print(" Must be exactly 5 letters. Try again.")
continue
blind_attempts += 1
blind_fb = generate_feedback(blind_guess, blind_secret)
print(f" Feedback: {blind_fb}")
if blind_fb == "GGGGG":
blind_won = True
print(f"\nYou won in {blind_attempts} attempt(s)!")
print()
if not blind_won:
print(f"Out of attempts! The word was: {blind_secret}")
Smart Wordle¶
Same game, but after each guess your filter_words() function shows how many possible words remain. If 10 or fewer remain, it shows the actual words. See how much faster you can solve it!
# SMART WORDLE - feedback + dictionary filtering!
smart_secret = random.choice(WORD_LIST)
smart_remaining = list(WORD_LIST)
smart_attempts = 0
smart_won = False
print("=== SMART WORDLE ===")
print("Guess the 5-letter word! After each guess, you'll see remaining possible words.")
print(f"Starting with {len(smart_remaining)} possible words.")
print()
while smart_attempts < 6 and not smart_won:
smart_guess = input(f"Attempt {smart_attempts + 1}/6: ").lower().strip()
if len(smart_guess) != 5:
print(" Must be exactly 5 letters. Try again.")
continue
smart_attempts += 1
smart_fb = generate_feedback(smart_guess, smart_secret)
print(f" Feedback: {smart_fb}")
if smart_fb == "GGGGG":
smart_won = True
print(f"\nYou won in {smart_attempts} attempt(s)!")
else:
smart_remaining = filter_words(smart_remaining, smart_guess, smart_fb)
print(f" Possible words remaining: {len(smart_remaining)}")
if len(smart_remaining) <= 10:
print(f" Words: {smart_remaining}")
print()
if not smart_won:
print(f"Out of attempts! The word was: {smart_secret}")
How Did You Do?¶
Run the cell below to compare your blind and smart Wordle performance.
# Compare your results!
print("=== COMPARISON ===")
print(f"Blind Wordle: {'Won' if blind_won else 'Lost'} in {blind_attempts} attempt(s)")
print(f"Smart Wordle: {'Won' if smart_won else 'Lost'} in {smart_attempts} attempt(s)")
print()
if blind_won and smart_won:
diff = blind_attempts - smart_attempts
if diff > 0:
print(f"Smart Wordle saved you {diff} guess{'es' if diff != 1 else ''}!")
print("This is the power of using code to eliminate possibilities.")
elif diff < 0:
print(f"Blind Wordle was actually {-diff} guess{'es' if -diff != 1 else ''} fewer. Lucky guessing!")
else:
print("Same number of guesses! The filtering didn't help this time.")
elif smart_won and not blind_won:
print("Smart Wordle won where Blind Wordle lost. Code made the difference!")
elif blind_won and not smart_won:
print("Blind Wordle won where Smart Wordle lost. Sometimes luck beats logic!")
else:
print("Neither version won. Try again with a new word!")
Summary¶
| Concept | Wordle Application | Question |
|---|---|---|
| Basic while loop | Check each letter position | Q1 |
| While + conditionals | Generate G/Y/- feedback | Q2 |
| Running total | Score a guess (Green=2, Yellow=1) | Q3 |
| Continue | Skip invalid guesses | Q4 |
| Nested while loops | Filter word list by feedback | Q5 |
| Counter + sentinel + break | Game loop with max 6 attempts | Q6 |
| Infinite loop debugging | Fix misplaced increment | Q7 |
| Multi-game loop | Tournament across multiple rounds | Q8 |
Key Takeaways¶
- While loops repeat until a condition changes - perfect for games with unknown iterations
- Functions let you reuse logic -
generate_feedbackis used byplay_round, which is used byplay_tournament continueskips invalid inputs,breakexits on success- Nested while loops let you check every position of every word
- The Smart Wordle comparison shows how effective code can be at narrowing possibilities
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/05_lab_while_loops/05_lab_while_loops.ipynb - Windows: Open File Explorer >
Documents\CSC115\lab_notebooks\05_lab_while_loops\05_lab_while_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
05_lab_while_loops.ipynb
Do NOT use File > Download in Jupyter - this can rename the file and cause submission errors.
To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()