Review: Guessing Game

Module 4: IDEs & Tools

Guessing Game

Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. - Keep the game going until the user types ÔÇ£exitÔÇØ - Keep track of how many guesses the user has taken, and when the game ends, print this out.

Try the exercise on your own first, then compare with the worked solution below.

# Solution

import numpy as np

def guessing_game():
  # Generate a random number between 1 and 9
  number = np.random.randint(1, 9)
  guesses = 0

  while True:
    guess = input("Guess a number between 1 and 9, or type 'exit' to end the game: ")

    if guess.lower() == 'exit':
      break

    guess = int(guess)
    guesses += 1

    if guess < number:
      print("Too low!")
    elif guess > number:
      print("Too high!")
    else:
      print("Exactly right!")
      break

  print(f"Game over. You took {guesses} guesses.")
guessing_game()