Lesson 18 of 35Python
Python · Lesson 18 · 45 minutes
Project: guessing game with high score
What you'll learn
- Build a game with a
whileloop and break - Save a record in a file and load it again
- Catch a missing file with
try/except
A game that remembers
So far every program forgets everything as soon as it ends. A real game, though, remembers your record – even after a restart. To do that, it saves the record in a file. Here you build a guessing game that does exactly that.
The game loop with break
When guessing, you don’t know in advance how many rounds there will be. That’s why the loop runs “forever” – until break ends it:
secret = 7
guesses = 0
while True:
try:
guess = int(input("Number from 1 to 10: "))
except ValueError:
print("Please type a number.")
continue
guesses += 1
if guess == secret:
word = "guess" if guesses == 1 else "guesses"
print(f"Hit after {guesses} {word}!")
break
print("Not quite.")Saving and loading the record
With open(name, "w") you write to a file, with open(name) you read it. Files always contain text – that’s why you use str() when writing and int() when reading:
with open("record.txt", "w") as file:
file.write(str(5))
with open("record.txt") as file:
record = int(file.read())
print("Saved record:", record)
print("Twice as good would be:", record // 2)Good to know: Here in the browser the file stays until you reload the page. On your own computer it stays forever – so there your record really is saved.
When the file is missing
In the very first game there is no file yet. open() would then stop with a FileNotFoundError. With try/except you catch that:
try:
with open("does_not_exist.txt") as file:
record = int(file.read())
except FileNotFoundError:
record = None
if record is None:
print("No record yet – you're the first!")
else:
print("Record:", record)None means “nothing”. With record is None you check whether there is a record yet.
Real randomness
In the task the secret number is fixed so that the check works. For the real game you use the module random:
import random
secret = random.randint(1, 100)
print("Psst, the number is", secret)Keep building: When your task works, replace
secret = 42withrandom.randint(1, 100). Also save the name of the record holder (for example as a second line in the file) or build difficulty levels with number ranges of different sizes.
Your task
Your turn
Program a guessing game with a record. Ask for a number with input("Your guess: ") until it is right. Answer with Too small! or Too big!, and on a hit with Correct! Guesses: 3. After that, load the record from the file FILE (if it doesn't exist yet, there is no record yet either). If you needed fewer guesses than the record – or there is no record yet – print New record! and save your guesses in the file. Otherwise print Record: 2 guesses (with the real record).
FILE = "highscore.txt"
secret = 42 # later: secret = random.randint(1, 100)
guesses = 0
# 1. Let the player guess until the number is right
# 2. Load the record, compare and maybe save- Something to think about
Use
whileTrueand end the loop withbreakas soon as the guess is right. Add 1 to guesses for every guess. - Which command helps?
Catch the missing file with
try/exceptFileNotFoundErrorand write the record withopen(FILE, "w").Compare with guesses
<record. Only then is the file written again. - Gap code – fill in the ___
FILE = "highscore.txt" secret = 42 # later: secret = random.randint(1, 100) guesses = 0 while ___: guess = ___ guesses += ___ if ___: print(___) elif ___: print(___) else: print(___) break try: with ___ as file: record = ___ except FileNotFoundError: record = ___ if ___: print(___) with ___ as file: file.write(___) else: print(___)
Solve it without hints to earn a ⭐ on your progress page.
Show solution🔒 Unlocks after all hints or 2 checks
Try it yourself first – mistakes teach you the most. Here is one possible solution:
FILE = "highscore.txt"
secret = 42 # later: secret = random.randint(1, 100)
guesses = 0
while True:
guess = int(input("Your guess: "))
guesses += 1
if guess < secret:
print("Too small!")
elif guess > secret:
print("Too big!")
else:
print(f"Correct! Guesses: {guesses}")
break
try:
with open(FILE) as file:
record = int(file.read())
except FileNotFoundError:
record = None
if record is None or guesses < record:
print("New record!")
with open(FILE, "w") as file:
file.write(str(guesses))
else:
print(f"Record: {record} {'guess' if record == 1 else 'guesses'}")