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.
Solution
Try the exercise on your own first, then compare with the worked solution below.
# Solutionimport numpy as npdef guessing_game():# Generate a random number between 1 and 9 number = np.random.randint(1, 9) guesses =0whileTrue: 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 +=1if guess < number:print("Too low!")elif guess > number:print("Too high!")else:print("Exactly right!")breakprint(f"Game over. You took {guesses} guesses.")
ModuleNotFoundError: No module named 'numpy'
guessing_game()
NameError: name 'guessing_game' is not defined
Source Code
---title: "Review: Guessing Game"subtitle: "Module 4: IDEs & Tools"format: html---## Guessing GameGenerate 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.::: {.callout-tip collapse="true"}## SolutionTry the exercise on your own first, then compare with the worked solution below.```{python}# Solutionimport numpy as npdef guessing_game():# Generate a random number between 1 and 9 number = np.random.randint(1, 9) guesses =0whileTrue: 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 +=1if guess < number:print("Too low!")elif guess > number:print("Too high!")else:print("Exactly right!")breakprint(f"Game over. You took {guesses} guesses.")``````{python}guessing_game()```:::