0
0
PythonProgramBeginner · 2 min read

Python Program to Create Number Guessing Game

You can create a number guessing game in Python by using random.randint() to pick a secret number and a while loop to let the user guess until they find it, like this: import random; secret = random.randint(1, 100); guess = None; while guess != secret: guess = int(input('Guess: ')); if guess < secret: print('Too low'); elif guess > secret: print('Too high'); else: print('You guessed it!').
📋

Examples

InputGuess: 50 Guess: 75 Guess: 63 Guess: 68
OutputToo low Too high Too low You guessed it!
InputGuess: 1 Guess: 100 Guess: 50 Guess: 75 Guess: 88
OutputToo low Too high Too low Too high You guessed it!
InputGuess: 42
OutputYou guessed it!
🧠

How to Think About It

Think of the game as the computer picking a secret number and the player trying to find it by guessing. After each guess, the program tells if the guess is too low, too high, or correct. This repeats until the player guesses right.
📐

Algorithm

1
Generate a random secret number within a range.
2
Ask the player to guess the number.
3
Compare the guess with the secret number.
4
If the guess is too low, tell the player to guess higher.
5
If the guess is too high, tell the player to guess lower.
6
Repeat until the player guesses the secret number.
7
Congratulate the player when they guess correctly.
💻

Code

python
import random

secret_number = random.randint(1, 100)
guess = None

while guess != secret_number:
    guess = int(input('Guess a number between 1 and 100: '))
    if guess < secret_number:
        print('Too low, try again.')
    elif guess > secret_number:
        print('Too high, try again.')
    else:
        print('Congratulations! You guessed the number.')
Output
Guess a number between 1 and 100: 50 Too low, try again. Guess a number between 1 and 100: 75 Too high, try again. Guess a number between 1 and 100: 63 Congratulations! You guessed the number.
🔍

Dry Run

Let's trace guessing 63 when the secret number is 63.

1

Generate secret number

secret_number = 63

2

First guess

guess = 50; guess < secret_number → print 'Too low, try again.'

3

Second guess

guess = 75; guess > secret_number → print 'Too high, try again.'

4

Third guess

guess = 63; guess == secret_number → print 'Congratulations! You guessed the number.'; exit loop

GuessComparisonOutput
5050 < 63Too low, try again.
7575 > 63Too high, try again.
6363 == 63Congratulations! You guessed the number.
💡

Why This Works

Step 1: Pick a secret number

The program uses random.randint(1, 100) to choose a secret number between 1 and 100.

Step 2: Get user guesses

It asks the player to enter guesses using input() and converts them to numbers with int().

Step 3: Compare and respond

The program compares each guess to the secret number and tells the player if the guess is too low, too high, or correct.

Step 4: Repeat until correct

The while loop keeps asking for guesses until the player finds the secret number, then congratulates them.

🔄

Alternative Approaches

Limit number of guesses
python
import random

secret_number = random.randint(1, 100)
max_attempts = 5
attempts = 0

while attempts < max_attempts:
    guess = int(input('Guess a number between 1 and 100: '))
    attempts += 1
    if guess < secret_number:
        print('Too low, try again.')
    elif guess > secret_number:
        print('Too high, try again.')
    else:
        print('You guessed it!')
        break
else:
    print(f'Sorry, you ran out of guesses. The number was {secret_number}.')
This version adds a limit on guesses, making the game more challenging but less forgiving.
Use function for guessing game
python
import random

def guessing_game():
    secret = random.randint(1, 100)
    while True:
        guess = int(input('Your guess: '))
        if guess < secret:
            print('Too low')
        elif guess > secret:
            print('Too high')
        else:
            print('Correct!')
            break

guessing_game()
This approach wraps the game logic in a function for better structure and reuse.

Complexity: O(k) time, O(1) space

Time Complexity

The program runs in O(k) time where k is the number of guesses the user makes until they find the secret number. Each guess is processed once.

Space Complexity

The program uses O(1) space because it stores only a few variables regardless of input size.

Which Approach is Fastest?

All approaches have similar time and space complexity; differences lie in user experience like guess limits or code structure.

ApproachTimeSpaceBest For
Basic loopO(k)O(1)Simple, interactive guessing
Limited guessesO(m)O(1)Games with challenge and guess limits
Function-basedO(k)O(1)Reusable and organized code
💡
Always convert user input to an integer with int() before comparing numbers.
⚠️
Forgetting to convert input to an integer causes errors or wrong comparisons.