Mini-Project: Guessing Game Engine
Time to combine everything: branching, comparisons, a loop, and break. We will build the engine of a number-guessing game.
A normal game would call input() to ask a person for guesses, but our grader has no keyboard. The trick used everywhere in testing is to pass the guesses in as a list. The function then loops over that list as if each item were typed in. Same logic, fully testable.
For each guess you compare against the secret and produce feedback. A classic shape:
def feedback_for(secret, guess):
if guess == secret:
return "correct"
elif guess < secret:
return "too low"
else:
return "too high"
print(feedback_for(50, 30)) # too lowTo find out how many tries it took, loop over the guesses with enumerate (so you know the position) and break as soon as one matches. Use the loop else to handle "never guessed it":
def tries_needed(secret, guesses):
for i, g in enumerate(guesses, start=1):
if g == secret:
return i # i is the count of guesses so far
else:
return -1 # ran out without finding itThis is real control flow doing real work: a loop that walks input, a comparison that decides, and a break/return that exits the moment the job is done.
Build two functions. (1) play(secret, guesses): loop over guesses and return the number of guesses taken to reach secret (1-based, so the first guess being correct returns 1); if secret never appears, return -1. (2) hints(secret, guesses): return a list of feedback strings, one per guess, each being "too low", "too high", or "correct". Use a loop with break in play.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.