randominputif chain, and a counter work togetherBefore writing any code, say what the program must do, in plain words:
That is the entire design. Every line of code below exists to do one of those four steps. When a program feels too big, this is the move: describe it in plain words first, then turn each sentence into code.
One tool you have not met yet makes this game possible:
random is a built-in tool for chance. random.randint(1, 10)
picks a whole number from 1 to 10, with each number equally likely.
Like Turtle, it must be loaded first: import random.guess_text = input("Guess a number from 1 to 10: ")
guess = int(guess_text)
print(guess)
If the player types 7, this prints 7 — as a number now, ready for
comparison. (If the player types something that is not a number,
int() complains. Handling that gracefully is a nice second version
of this game, and a good stretch goal once this version works.)
Here it is, complete. Read it top to bottom first, matching each part
to the four design steps above, then type it into a file called
guessing_game.py and run it:
import random
secret = random.randint(1, 10)
tries = 0
print("I am thinking of a number from 1 to 10.")
print("Can you guess it?")
while True:
guess_text = input("Your guess: ")
guess = int(guess_text)
tries = tries + 1
if guess == secret:
print("You got it!")
print("It took you " + str(tries) + " tries.")
break
elif guess < secret:
print("Too low — try higher.")
else:
print("Too high — try lower.")
Play it. A run might look like this (the secret is different every time, so your run will differ):
I am thinking of a number from 1 to 10.
Can you guess it?
Your guess: 3
Too low — try higher.
Your guess: 8
Too high — try lower.
Your guess: 5
You got it!
It took you 3 tries.
while True: means "repeat forever, until something stops the
loop." That something is break, which exits the loop the
moment the player wins. Without break, the game would never end —
the infinite-loop mistake from Lesson 10, used deliberately here as
the design.if/elif/else chain (Lesson 9) gives exactly one
response per guess: equal, too low, or too high. Because == is
checked first, a correct guess never falls through to the hints.tries = tries + 1 (Lesson 4) counts guesses, and str(tries)
(Lesson 6) converts the count to text so it can join the final
message.random.randint(1, 10) picks a fresh secret every run, so the
game is different each time you play — the reason it stays fun
after the first win.Notice what is not here: no new concept except random, input,
and break. Everything else is Lessons 1–15, combined. That is the
real lesson of this project: programs are not built from advanced
magic, but from simple ideas stacked together.
A finished game is a starting point, not an ending. Try one change at a time, and run the game after each change:
int()
complain (hint: check the guess text before converting it, or learn
about try in the main Python 3 course).Each change is small. Each one teaches something. That is how programmers grow: not by memorizing more, but by changing working programs and watching what happens.
guessing_game.py and play it until you
win at least once.random.randint(1, 10) do, and why must import random come first?input() give you, and why is int() needed on its answer?while True: mean, and what stops such a loop?== checked before the too-low and too-high cases?random, input, and break — what does that tell you about building programs?Answer key: 1. It picks a whole number from 1 to 10 at random; import random loads the tool, without which Python does not know it. 2. Text typed by the player; int() converts it to a number so it can be compared with the secret. 3. "Repeat forever"; break exits the loop when the player wins. 4. So a correct guess wins at once instead of falling through to a hint. 5. That programs are simple ideas stacked together, not advanced magic.
random.randint() picks a secret; input() reads the player; int() converts text to a number.while True: plus break repeats until the win condition ends it.if/elif/else chain gives exactly one response per guess.Next lesson: What's Next — Stepping into Python 3 Programming.
Work through the slides with Helio's narration, or download them:
Open the slidesDownload PowerPointDownload PDF
Run the lesson's example with real Python, right in your browser (Python loads from the internet, so you need to be online).
Download lesson16-practice.pyDownload the solution
# Lesson 16: Mini-Project — The Number-Guessing Game
# WHAT TO DO: This is the full guessing game from the lesson. The
# computer picks a secret number from 1 to 10 with random.randint(),
# the player guesses with input(), and the game counts tries. One line
# is unfinished: in the winning branch, fill in line 35 to report how
# many tries it took, for example:
# print("It took you " + str(tries) + " tries.")
# HINT: str(tries) turns the tries number into text so it can join the
# message with +. Only change the placeholder line, inside the win branch.
# Run with F5 in IDLE and type guesses when asked. You are done when a
# win prints "You got it!" plus a sentence with your number of tries.
# NOTE: If you run this where no one can type a guess (an automated
# check, for example), it prints a message and stops cleanly instead
# of crashing. That is expected — play it in IDLE to play for real.
import random
secret = random.randint(1, 10)
tries = 0
print("I am thinking of a number from 1 to 10.")
print("Can you guess it?")
while True:
try:
guess_text = input("Your guess: ")
except EOFError:
print("No guess typed, so the game stops here.")
break
guess = int(guess_text)
tries = tries + 1
if guess == secret:
print("You got it!")
print("TODO - how many tries did it take?") # <-- CHANGE THIS LINE
break
elif guess < secret:
print("Too low - try higher.")
else:
print("Too high - try lower.")
Save the file as lesson16-practice.py and run it with F5 in IDLE. On a Mac, if F5 does nothing, use Run, then Run Module, from the menu.
Five quick questions on this lesson. Take the Lesson 16 quiz
Enroll free in the full course — same 17 lessons, with your progress saved. Free, no payment.