Python Tutorial

Python Project: Guess the Number

A guessing game that picks a secret integer, counts attempts, and gives high/low hints until you win.

What you are building

You build a small game. The program holds a secret integer from 1 to 20. Each guess is compared to that secret. The player hears too high, too low, or correct. When the match happens, the program prints how many attempts it took.

Copy every example into the Python editor at /try and click Run. That editor is Python only. It is not HTML, C, or C++. The complete program uses a list of guesses so it prints a full playthrough without waiting for input().

Skills used

  • if / elif / else to compare a guess to the secret
  • A for loop over a list of demo guesses
  • A counter that goes up on every attempt
  • random.randint when you later want a new secret each run
  • break to stop as soon as the player wins

Compare one guess

Start with three numbers: a low bound, a high bound, and a secret. Then test a single guess. The comparison is the whole game in miniature.

Example

secret = 12
guess = 10

print("Secret is between 1 and 20.")
print("Guess:", guess)
if guess < secret:
    print("Too low.")
elif guess > secret:
    print("Too high.")
else:
    print("Correct.")

Change guess to 15, then to 12. You should see too high, then correct. That is the hint table the rest of the program will print on every attempt.

Guess vs secretMessage
guess is smallerToo low
guess is largerToo high
guess equals secretCorrect

Drive the game from a list

In a terminal you would call input() inside a loop. In the browser editor, a stuck prompt is a bad demo. Put the guesses in a list and loop over them. Count every pass. Stop with break when the secret is found.

Example

secret = 12
guesses = [10, 15, 12]
attempts = 0

for guess in guesses:
    attempts += 1
    print("Attempt", attempts, "->", guess)
    if guess == secret:
        print("Hit.")
        break
    if guess < secret:
        print("Too low.")
    else:
        print("Too high.")

print("Attempts used:", attempts)

Keep the secret in a variable, not copied into every if. Then one change ofsecret updates the whole game. A live version can set that variable withrandom.randint(1, 20) after import random.

Complete program

This is the full game. The secret is 12 so the demo list [10, 15, 12] wins on the third try. Run it at /try. You should see two hints, then a win line with the attempt count.

Example

LOW = 1
HIGH = 20
SECRET = 12
GUESSES = [10, 15, 12]

print("Guess the number.")
print("Range:", LOW, "to", HIGH)

attempts = 0
won = False

for guess in GUESSES:
    attempts += 1
    print()
    print("Attempt", attempts, ":", guess)
    if guess < LOW or guess > HIGH:
        print("Out of range. Stay between", LOW, "and", HIGH, ".")
        continue
    if guess < SECRET:
        print("Too low.")
    elif guess > SECRET:
        print("Too high.")
    else:
        print("Correct! The number was", SECRET)
        won = True
        break

print()
if won:
    print("You won in", attempts, "attempts.")
else:
    print("No more guesses. The number was", SECRET)

The range check is extra, not required for this demo list. It shows how you reject a value without counting it as a win. continue skips the rest of that loop pass and moves to the next guess.

Optional: type guesses with input

After the list version works, you can swap the list for input(). Run this only when you are ready to type. The browser editor will wait until you enter a line.

Example

# Optional interactive variant. The complete program above does not need this.
secret = 12
attempts = 0
while True:
    attempts += 1
    guess = int(input("Guess: "))
    if guess == secret:
        print("Correct in", attempts, "tries.")
        break
    if guess < secret:
        print("Too low.")
    else:
        print("Too high.")

Common mistakes

  • Using input() as the only path, then wondering why Run sits still. Demo with a list first.
  • Comparing strings to integers. input() returns text. Wrap it with int(...) if you switch to typing.
  • Forgetting break. The loop then keeps printing after the player already won.
  • Resetting attempts inside the loop. The counter must live outside so it survives each pass.
  • Calling random.randint without a seed in a tutorial screenshot. The secret then changes every run and the written guesses no longer match. Fix the secret for demos.

How to extend / Practice tasks

Make three concrete changes. Run after each one.

  1. Set SECRET = 7 and change GUESSES to [5, 9, 7]. Confirm the hints flip from too low to too high to correct.
  2. Widen the range to 1 through 50. Add a fourth guess that is 51 and check that the out-of-range branch prints.
  3. Track the best (lowest) attempt count across two playthroughs in the same file: run the loop twice with two different guess lists and print which list won faster.

📘 Real-World Deep Dive

The number-guessing game is the smallest complete program with a real game loop: hidden state, repeated input, a narrowing hint, and a win condition. Every larger game is this skeleton with more flesh.

What to build

The computer picks 1–100; the player guesses; each guess prints higher/lower; the game ends on a correct guess and reports the attempt count.

Real-Life Example

import random

def play(secret: int, guesses: list[int]) -> str:
    for turn, g in enumerate(guesses, 1):
        if g == secret:
            return f"correct in {turn} tries"
        print("higher" if g < secret else "lower")
    return "out of guesses"

# Deterministic for the demo; use random.randint(1, 100) live.
print(play(secret=42, guesses=[50, 25, 37, 43, 42]))

Passing guesses in as a list (instead of calling input()) makes the game logic testable without a keyboard.

Expected Output

lower
higher
higher
lower
correct in 5 tries

Common mistakes

  • input() returns a string — forgetting int(...) makes every comparison wrong. Validate and re-prompt on non-numbers.
  • An unbounded while True with no attempt cap can loop forever in a test. Give the game a max number of tries.
  • Calling random.randint inside the guessing loop re-rolls the secret every turn — set it once before the loop.

🚀 Performance & Best Practices

  • Optimal play is binary search: the answer is always findable in ⌈log₂100⌉ = 7 guesses. Great follow-up discussion.
  • Separate the pure game logic from I/O (as above) so you can unit-test wins, losses, and edge guesses.
  • Seed random.Random(seed) in tests for reproducible runs.

🧪 Try It Yourself

  1. Add difficulty levels that change the range (1–10, 1–100, 1–1000) and the allowed number of guesses.
  2. Track a best score (fewest guesses) across rounds in the same session.
  3. Have the computer guess your number using binary search and count its tries.

FAQ: Python Project: Guess the Number

Common questions about this page.

What is Python Project: Guess the Number?

Python Project: Guess the Number is a Python Projects lesson that explains python guess number project in Python. A guessing game that picks a secret integer, counts attempts, and gives high/low hints until you win. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python guess number project examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python guess number project in this Python Projects Python lesson (Python Project: Guess the Number).

How do I use python guess number project in Python?

To use python guess number project in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python guess number project?

This Python Project: Guess the Number tutorial shows python guess number project syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Project: Guess the Number example for beginners

Yes. This page includes a beginner python guess number project example you can copy and run. It is designed for searches such as "python guess number project for beginners", "python guess number project example", and "how to use python guess number project".

What are common mistakes with python guess number project?

Common python guess number project mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Projects chapter in order, run every example, and check the output before moving on.

Why should I learn python guess number project?

Python Project: Guess the Number is used in real Python work. Learning python guess number project helps you write clearer programs and continue the Python Projects tutorial on StudyGrid.

Is Python Project: Guess the Number free to learn online?

Yes. You can learn python guess number project free on StudyGrid (studygrid.in). This chapter is part of the Python Projects path and includes examples, syntax, and next-step links.