Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
The simplest Python guessing game has four parts: choose a secret integer, read and validate a guess, compare the values, and repeat until the player wins or runs out of attempts. The complete program below uses Python’s standard random module, gives “too high” and “too low” hints, rejects invalid entries without wasting a turn, and ends with a clear win or loss message.
What the game needs
A beginner version can be built with four ideas:
- Secret number:
random.randint(1, 20)selects an integer from 1 through 20, including both endpoints. - Input:
input()returns text, so a valid guess must be converted withint(). - Comparison:
if,elif, andelsedecide whether the guess is correct, too small, or too large. - Loop: a
whileloop asks repeatedly until the player wins or reaches the attempt limit.
This is the same core pattern used in the beginner exercises from Microsoft Learn and Harvard CS50P.
Build a bounded game with input validation
Save the following as guessing_game.py. It allows five valid guesses. Non-numeric and out-of-range entries are rejected and do not consume an attempt.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallComplete runnable program
import random
LOW = 1
HIGH = 20
MAX_GUESSES = 5
secret_number = random.randint(LOW, HIGH)
guess_count = 0
print(f"I'm thinking of a number between {LOW} and {HIGH}.")
print(f"You have {MAX_GUESSES} guesses. Good luck!")
while guess_count < MAX_GUESSES:
try:
guess = int(input(f"Guess #{guess_count + 1}: "))
except ValueError:
print("Please enter a whole number.")
continue
if not LOW <= guess <= HIGH:
print(f"Choose a number from {LOW} to {HIGH}.")
continue
guess_count += 1
if guess == secret_number:
print(f"Correct! You got it in {guess_count} guesses.")
break
elif guess < secret_number:
print("Too low.")
else:
print("Too high.")
else:
print(f"Out of guesses! The number was {secret_number}.")
Run it from a terminal with:
python guessing_game.py
On systems where python refers to an older installation, use python3 guessing_game.py instead.
#1 Best Overall
Why the counter is incremented after validation
The counter changes only after int() succeeds and the number lies inside the permitted range. Typing hello, an empty response, or 25 therefore produces a correction rather than silently reducing the player’s chances. This is a policy choice; you can make invalid entries count if you want a stricter game, but the program and its message should agree.
How the loop ends
The condition while guess_count < MAX_GUESSES makes the attempt limit visible. A correct guess executes break, so the loop’s else block is skipped. If every allowed guess is used and no break occurs, Python runs the else block and reveals the answer.
That else belongs to the while, not to the final if. It means “the loop finished normally.” Beginners often mistake it for another comparison branch.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Choose the game rules deliberately
| Design | Stopping rule | Invalid input | Best use |
|---|---|---|---|
| Bounded attempts | Counter reaches a maximum, or the player wins | Usually does not count | A short, score-like challenge |
| Unlimited attempts | Correct guess or an explicit quit command | Usually does not count | Practising loops and comparisons |
| Difficulty levels | Maximum depends on the selected range or attempt limit | Validate against the selected range | Replayable games with easy, medium, and hard modes |
Keep the range used by randint identical to the range accepted by validation. If the secret can be 20 but the input check stops at 19, the player can never legally guess one possible answer.
Rank #2
Add a player-selected level
CS50P’s exercise asks the player for a positive level and then chooses a number from 1 through that level. This version reprompts until the level is a positive integer, then continues until the answer is found.
import random
while True:
try:
level = int(input("Level: "))
if level > 0:
break
except ValueError:
pass
print("Please enter a positive whole number.")
secret = random.randint(1, level)
while True:
try:
guess = int(input("Guess: "))
except ValueError:
print("Please enter a positive whole number.")
continue
if guess <= 0:
print("Please enter a positive whole number.")
elif guess < secret:
print("Too small!")
elif guess > secret:
print("Too large!")
else:
print("Just right!")
break
Unlike the first program, this one has unlimited valid guesses. Its stopping condition is the successful guess, so it needs no attempt counter.
Turn one round into a replayable game
Put one round in a function and wrap it in an outer loop. Returning True for a win lets the caller keep simple statistics without mixing replay logic into the guessing loop.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteimport random
LOW = 1
HIGH = 20
MAX_GUESSES = 5
def play_round():
secret = random.randint(LOW, HIGH)
attempts = 0
while attempts < MAX_GUESSES:
try:
guess = int(input(f"Guess #{attempts + 1}: "))
except ValueError:
print("Please enter a whole number.")
continue
if not LOW <= guess <= HIGH:
print(f"Choose a number from {LOW} to {HIGH}.")
continue
attempts += 1
if guess == secret:
print(f"Correct in {attempts} guesses!")
return True
print("Too low." if guess < secret else "Too high.")
print(f"Out of guesses! The number was {secret}.")
return False
wins = 0
rounds = 0
while True:
rounds += 1
if play_round():
wins += 1
again = input("Play again? (y/n): ").strip().lower()
if again != "y":
break
print(f"You won {wins} of {rounds} rounds.")
The PC-Python examples show the same natural next steps: replay, statistics, and stronger input handling.
Rank #3
Test every path
- Enter the correct number on the first attempt and confirm that the program stops immediately.
- Enter a value below the secret and then one above it; verify that each hint is accurate.
- Enter text such as
abc, an empty line, and a decimal such as3.5. Each should be rejected byint(). - Enter values just outside the range, such as
0and21when the range is 1–20. - Use five valid wrong guesses and confirm that the loss message appears once.
- In the replay version, play both a winning and losing round, then answer
nto verify that the outer loop exits.
Troubleshooting common errors
ValueError: invalid literal for int()
The program attempted to convert non-integer text. Keep the conversion inside try/except ValueError and reprompt instead of calling int(input(...)) without protection.
The player can never guess the secret
Check that the validation bounds match the arguments passed to random.randint. Both endpoints are included, so a 1–20 game must accept 1 and 20.
Invalid guesses consume attempts
Move guess_count += 1 below the conversion and range check. Increment exactly once for each accepted guess.
Recommended Free Tools
The “out of guesses” message appears after a win
Make sure the successful branch uses break. The while else runs only when the loop ends without a break.
Rank #4
The program exits immediately
Run it in a terminal, not by double-clicking a file in a window that closes after an error. Start it with python guessing_game.py, read the traceback, correct the indicated line, and run it again.
Hints are reversed
For a lower guess, print “Too low”; for a higher guess, print “Too high.” Compare the guess to the secret in that order and test both sides deliberately.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Performance, reliability, and safety
This game performs constant-time work for each guess and uses only the Python standard library, so performance is not a practical concern for a single player. Reliability comes from explicit stopping conditions and validation rather than from speed. Keep the secret number in a variable, avoid changing it inside the loop, and keep user input untrusted until conversion and range checks succeed.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →For a classroom exercise, revealing the answer after a loss is useful feedback. For a competitive version, remove that line or show the result only after the round ends. Do not treat the standard random module as a security mechanism for passwords, tokens, or other secrets; this game only needs an unpredictable-enough practice value.
Best Value
- Language: english
- Book - automate the boring stuff with python, 2nd edition: practical programming for total beginners
- It is made up of premium quality material.
Further learning after the first version
Once the basic round works, add a difficulty table, a score based on remaining attempts, a quit command, or a high-score file. Change one rule at a time and retest the paths above. Invent with Python’s Guess the Number chapter is a book-length beginner resource that develops this project alongside broader Python concepts.
Or skip the browser setup
If you need a clean image or PDF of a web page that documents your game, ScreenshotNeo provides a single-call website screenshot API. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers. Its MCP server includes take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
Here is the one-call cURL form; see the ScreenshotNeo API documentation for all parameters.
Free tools Windows power users keep installed
One-click scans. No signup required.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://screenshotneo.com -o shot.webp
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://screenshotneo.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://screenshotneo.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo includes full-page and element captures, dark mode, device presets, custom viewports, retina scale, PDF controls, custom CSS and JavaScript, click and wait actions, request and resource blocking, headers, cookies, user agents, timezone and geolocation, transparent backgrounds, resizing, configurable caching, signed links, asynchronous webhooks, bulk capture, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work for easier migration. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000, and every feature is available on every plan. Create a free ScreenshotNeo account.
Frequently Asked Questions
How can I test the losing path without guessing repeatedly?
Temporarily set MAX_GUESSES = 1 and enter a valid number that is unlikely to match. Restore the original limit after confirming the loss message.
How can I inspect the chosen secret while debugging?
Temporarily add print(secret_number) immediately after the randint call, remove it when testing is complete, and never leave it enabled in a competitive version.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.

