Open In App

Number guessing game in Python 3 and C

Last Updated : 13 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The objective of this project is to build a simple number guessing game that challenges the user to identify a randomly selected number within a specified range. The game begins by allowing the user to define a range by entering a lower and an upper bound (for example, from A to B). Once the range is set, the system randomly selects an integer that falls within this user-defined interval. The user's task is then to guess the chosen number using as few attempts as possible. The game provides feedback after each guess, helping the user refine their next guess based on whether their previous attempt was too high or too low.

How the Game Works

To understand how the number guessing game functions, let’s walk through two practical scenarios. These examples demonstrate how narrowing down the range intelligently—similar to a binary search—can help guess the number efficiently.

Example 1: Guessing in a Range from 1 to 100

Suppose the user defines the range from 1 to 100, and the system randomly selects 42 as the target number. The guessing process might look like this:

  • Guess 1: 50 → Too high
  • Guess 2: 25 → Too low
  • Guess 3: 37 → Too low
  • Guess 4: 43 → Too high
  • Guess 5: 40 → Too low
  • Guess 6: 41 → Too low
  • Guess 7: 42 → Correct!

Total Guesses: 7

Example 2: Guessing in a Range from 1 to 50

Now consider a smaller range, from 1 to 50, with the same target number 42. Here's how the guesses might proceed:

  • Guess 1: 25 → Too low
  • Guess 2: 37 → Too low
  • Guess 3: 43 → Too high
  • Guess 4: 40 → Too low
  • Guess 5: 41 → Too low
  • Guess 6: 42 → Correct!

Total Guesses: 6

Note: In both examples, the user intelligently uses the binary search strategy, halving the guessing range with each attempt.

Algorithm

  • Accept lower and upper bounds from the user.
  • Generate a random number in the selected range.
  • Calculate the maximum allowed guesses using the binary search formula.
  • Run a loop to take user guesses:
    • If the guess is too high, print: "Try Again! You guessed too high."
    • If the guess is too low, print: "Try Again! You guessed too small."
    • If the guess is correct, print: "Congratulations!" and exit the loop.
  • If the user runs out of chances, display the correct number and a message: "Better Luck Next Time!"

Implementation

Below is the Implementation of the Algorithm:

C
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int lower, upper, x, guess, count = 0, flag = 0;
    int total_chances;

    // Taking Inputs
    printf("Enter Lower bound: ");
    scanf("%d", &lower);

    // Taking Inputs
    printf("Enter Upper bound: ");
    scanf("%d", &upper);

    // Seed the random number generator
    srand(time(0));

    // Generating random number between the lower and upper
    x = (rand() % (upper - lower + 1)) + lower;
    total_chances
        = (int)ceil(log(upper - lower + 1) / log(2));

    printf("\n\tYou've only %d chances to guess the "
           "integer!\n\n",
           total_chances);

    // for calculation of minimum number of guesses depends
    // upon range
    while (count < total_chances) {
        count++;

        // Taking guessing number as input
        printf("Guess a number: ");
        scanf("%d", &guess);

        // Condition testing
        if (x == guess) {
            printf(
                "Congratulations you did it in %d try!\n",
                count);
            // Once guessed, loop will break
            flag = 1;
            break;
        }
        else if (x > guess) {
            printf("You guessed too small!\n");
        }
        else if (x < guess) {
            printf("You guessed too high!\n");
        }
    }

    // If Guessing is more than required guesses, shows this
    // output.
    if (!flag) {
        printf("\nThe number is %d\n", x);
        printf("\tBetter Luck Next time!\n");
    }

    return 0;
}
Python
import random

print("Hi! Welcome to the Number Guessing Game.\nYou have 7 chances to guess the number. Let's start!")

low = int(input("Enter the Lower Bound: "))
high = int(input("Enter the Upper Bound: "))

print(f"\nYou have 7 chances to guess the number between {low} and {high}. Let's start!")

num = random.randint(low, high) 
ch = 7                        # Total allowed chances
gc = 0                        # Guess counter

while gc < ch:
    gc += 1
    guess = int(input('Enter your guess: '))

    if guess == num:
        print(f'Correct! The number is {num}. You guessed it in {gc} attempts.')
        break

    elif gc >= ch and guess != num:
        print(f'orry! The number was {num}. Better luck next time.')

    elif guess > num:
        print('Too high! Try a lower number.')

    elif guess < num:
        print('Too low! Try a higher number.')

Output

Outputsforguessinggame
Number guessing game

Explanation: This Python script implements a number guessing game using basic control structures. It uses random.randrange(100) to generate a target number between 0 and 99. The user is given 7 attempts to guess the number. A while loop handles repeated input, and conditional statements (if-elif) evaluate each guess—providing feedback on whether it's too high, too low, or correct. If the guess matches, the loop breaks; otherwise, the game ends after 7 tries, displaying the correct number.


Next Article
Practice Tags :

Similar Reads