The computer picks a secret number and you try to guess it, getting “too high” or “too low” hints. It takes about thirty minutes and uses most of what you learn in your first week.
What you will build#
I am thinking of a number between 1 and 100.
Your guess: 50
Too high. 6 guesses left.
Your guess: 25
Too low. 5 guesses left.
Your guess: 37
Correct! You got it in 3 guesses.What you need#
- Python installed — see how to install Python
- A file called
guess.py - Comfort with variables, conditions and loops
Step 1: pick a secret number#
import random
secret = random.randint(1, 100)
print(secret) # temporarily, to check it worksrandom.randint(1, 100) includes both ends, so 1 and 100 are both possible. Run it a few times, then delete that print.
Step 2: get one guess#
guess = int(input("Your guess: "))
if guess == secret:
print("Correct!")
elif guess < secret:
print("Too low.")
else:
print("Too high.")input() always returns text, so int() converts it. Without that, guess == secret compares text to a number and is never true — see Python data types explained.
Step 3: keep asking until they win#
import random
secret = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess == secret:
print(f"Correct! You got it in {attempts} guesses.")
break
elif guess < secret:
print("Too low.")
else:
print("Too high.")while True loops forever, and break is the only way out. That is a normal pattern when you do not know in advance how many rounds there will be.
Step 4: handle bad input#
Right now, typing “abc” crashes the program with a ValueError. Catch it:
while True:
raw = input("Your guess: ")
try:
guess = int(raw)
except ValueError:
print("Please type a whole number.")
continue
attempts += 1
...continue skips back to the top without counting a wasted attempt.
The finished program#
import random
LOW = 1
HIGH = 100
MAX_ATTEMPTS = 7
def play():
secret = random.randint(LOW, HIGH)
attempts = 0
print(f"I am thinking of a number between {LOW} and {HIGH}.")
print(f"You have {MAX_ATTEMPTS} guesses.")
while attempts < MAX_ATTEMPTS:
raw = input("Your guess: ")
try:
guess = int(raw)
except ValueError:
print("Please type a whole number.")
continue
if guess < LOW or guess > HIGH:
print(f"Stay between {LOW} and {HIGH}.")
continue
attempts += 1
left = MAX_ATTEMPTS - attempts
if guess == secret:
print(f"Correct! You got it in {attempts} guesses.")
return True
hint = "Too low." if guess < secret else "Too high."
print(f"{hint} {left} guesses left.")
print(f"Out of guesses. The number was {secret}.")
return False
play()How the code works#
- The constants at the top mean you can change the difficulty in one place.
play()as a function makes it easy to add “play again” later. See Python functions explained.try / exceptcatches onlyValueError, so real bugs still surface.continuebeforeattempts += 1means invalid entries do not cost the player a turn.- The one-line
iffor the hint keeps the ending compact.
Questions people ask#
How do I make the computer guess instead?
Reverse the roles: the computer guesses the middle of the range, you say higher or lower, and it halves the range each time. That is binary search, and it always wins within seven guesses for 1 to 100.
Why use a function at all for something this small?
Because “play again” becomes one extra line instead of a rewrite. Getting into the habit early costs nothing.
Can I add a graphical interface?
Yes — Python’s built-in tkinter can do it. Get the terminal version working first; the logic stays the same and only the input and output change.