← Back

Home › Code Lab › Guess the Number Game in Python

Guess the Number game in Python — code, logic and play

Run a free Python Guess the Number game in your browser, copy or download the code, and understand the logic line by line. · Level: Beginner · इसे Hindi में पढ़ें

Run the Python code

Output

    
  

How the logic works (free)

  1. random.randint(1, 100) picks a secret number. The game does not know it in advance, so every round is different.
  2. attempts = 0 keeps count of how many guesses the player has made.
  3. while True: repeats the guessing until the player wins. The loop ends only with break.
  4. input() waits for the player to type. The text is checked with isdigit() before int() converts it, so letters do not crash the game.
  5. The if / elif / else chain compares the guess with the secret: too low, too high, or correct.
  6. break leaves the loop after a correct guess, and the f-string shows the number of attempts.

Concepts you practise

Full code (plain text)
import random

def play_guess_the_number():
    secret = random.randint(1, 100)
    attempts = 0
    print("I have picked a number between 1 and 100.")
    while True:
        guess_text = input("Your guess: ")
        if not guess_text.isdigit():
            print("Please type a whole number.")
            continue
        guess = int(guess_text)
        attempts += 1
        if guess < secret:
            print("Too low! Try a bigger number.")
        elif guess > secret:
            print("Too high! Try a smaller number.")
        else:
            print(f"Correct! You won in {attempts} attempt(s).")
            break

play_guess_the_number()

Extra tools

Step through every line of the code, or load the Level 2 version of this game with new rules and challenges. Both tools are free.

Practice on PyDebug

After playing, turn the idea into a debugging habit with these free exercises: