25  Exercise: Putting it all together

25.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!

Open the exercise in Google Colab: Open In Colab

25.2 Sample Answers

Openthe solution in Google Colab: Open In Colab

25.3 Answer Video

The code for this video is slightly different to the example solution given above.

import random

continue_play = True
high_score = 0

while continue_play == True:

    user_guesses_list = []
    score = 1000
    guessed_correctly = False

    computer_chosen_number = random.randint(1,100)

    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):

        user_guess = int(input("Please enter a number:"))
        user_guesses_list.append(user_guess)

        if user_guess == computer_chosen_number:
            print("Correct! You guessed it.")
            guessed_correctly = True
            break
        elif user_guess < computer_chosen_number:
            print("Too low!")
            score -= 100
        else:
            print("Too high!")
            score -= 100

    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}")
            high_score = score
        else:
            print("You didn't beat the high score!")
            print(f"High score: {high_score}")

    print(f"Your guesses were {user_guesses_list}")

    keep_playing_input = input("Please enter Y to keep playing or N to leave:")

    if keep_playing_input == "N":
        continue_play = False