import random
= True
continue_play = 0
high_score
while continue_play == True:
= []
user_guesses_list = 1000
score = False
guessed_correctly
= random.randint(1,100)
computer_chosen_number
print("Welcome to the guessing game! I'm thinking of a number.")
#print(f"DEBUG: computer number is {computer_chosen_number}")
for turn in range(10):
= int(input("Please enter a number:"))
user_guess
user_guesses_list.append(user_guess)
if user_guess == computer_chosen_number:
print("Correct! You guessed it.")
= True
guessed_correctly break
elif user_guess < computer_chosen_number:
print("Too low!")
-= 100
score else:
print("Too high!")
-= 100
score
if not guessed_correctly:
print("You lose!")
print(f"The number was {computer_chosen_number}")
else:
print(f"Your score: {score}")
if score > high_score:
print(f"New high score! The previous high score was {high_score}")
= score
high_score else:
print("You didn't beat the high score!")
print(f"High score: {high_score}")
print(f"Your guesses were {user_guesses_list}")
= input("Please enter Y to keep playing or N to leave:")
keep_playing_input
if keep_playing_input == "N":
= False continue_play
26 Exercise: Putting it all together
26.1 Are you Smarter than (Dan as) a 4 year old?
When I was 4 years old, I wrote my very first program in BASIC on my Atari 800XL.
In it, the computer randomly picked a whole number between 1 and 100, and the user had 10 chances to guess the number.
Every time the user guessed a number, they would be told either that the number was “too low”, “too high” or “correct”.
If the user used up all 10 chances without guessing correctly, they were told “you lose”, along with what the number was, and the game would end.
You’ve been taught enough to write this program in Python. You should write the game above along with the following features that 4-year old Dan didn’t implement :
- a score, which starts at 1000 and which reduces by 100 for every unsuccessful guess, and which is displayed if the user wins
- the user’s guesses are stored in a list and printed once the game is over
- the game asks if the player wants to play again after every game ends
- after each game, the player’s score is checked against the current high-score (default is 0) and if the last score is higher than the recorded high score then this replaces the high score.
You could also add some bells and whistles of your choosing!
26.2 Sample Answers
26.3 Answer Video
The code for this video is slightly different to the example solution given above.