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)
- random.randint(1, 100) picks a secret number. The game does not know it in advance, so every round is different.
- attempts = 0 keeps count of how many guesses the player has made.
- while True: repeats the guessing until the player wins. The loop ends only with break.
- input() waits for the player to type. The text is checked with isdigit() before int() converts it, so letters do not crash the game.
- The if / elif / else chain compares the guess with the secret: too low, too high, or correct.
- break leaves the loop after a correct guess, and the f-string shows the number of attempts.
Concepts you practise
- random module
- while loop with break
- input() and type checking
- if / elif / else
- f-strings
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()
Practice on PyDebug
After playing, turn the idea into a debugging habit with these free exercises: