10-Guessing Game Challenge - Solution - Ipynb - Colab
10-Guessing Game Challenge - Solution - Ipynb - Colab
ipynb - Colab
The Challenge:
Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are:
1. If a player's guess is less than 1 or greater than 100, say "OUT OF BOUNDS"
2. On a player's first turn, if their guess is
4. When the player's guess equals the number, tell them they've guessed correctly and how many guesses it took!
keyboard_arrow_down First, pick a random integer from 1 to 100 using the random module and assign it to a variable
Note: random.randint(a,b) returns a random integer in range [a, b] , including both end points.
import random
num = random.randint(1,100)
keyboard_arrow_down Next, print an introduction to the game and explain the rules
Hint: zero is a good placeholder value. It's useful because it evaluates to "False"
guesses = [0]
keyboard_arrow_down Write a while loop that asks for a valid guess. Test it a few times to make sure it works.
while True:
guess = int(input("I'm thinking of a number between 1 and 100.\n What is your guess? "))
break
keyboard_arrow_down Write a while loop that compares the player's guess to our number. If the player guesses correctly, break from the loop.
Otherwise, tell the player if they're warmer or colder, and continue asking for guesses.
Some hints:
while True:
if guesses[-2]:
if abs(num-guess) < abs(num-guesses[-2]):
print('WARMER!')
else:
print('COLDER!')
else:
if abs(num-guess) <= 10:
print('WARM!')
else:
print('COLD!')
In the next section we'll learn how to turn some of these repetitive actions into functions that can be called whenever we need them.
https://colab.research.google.com/drive/10Rw mNhQC-W4yZ-K3zt1YUJfX8xoGecLF 2/3
4/8/25, 11:35 AM 10-Guessing Game Challenge - Solution.ipynb - Colab
Good Job!