The Wayback Machine - https://web.archive.org/web/20240921213457/https://www.geeksforgeeks.org/number-guessing-game-in-python/
Open In App

Number guessing game in Python 3 and C

Last Updated : 05 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Most of the geeks from a CS (Computer Science) background, think of their very first project after doing a Programming Language. Here, you will get your very first project and the basic one, in this article.

Task: Below are the steps:

  • Build a Number guessing game, in which the user selects a range.
  • Let’s say User selected a range, i.e., from A to B, where A and B belong to Integer.
  • Some random integer will be selected by the system and the user has to guess that integer in the minimum number of guesses

Analysis:

       Explanation 1: If the User inputs range, let’s say from 1 to 100. And compiler randomly selected 42 as the integer. And now the guessing game started, so the user entered 50 as his/her first guess. The compiler shows “Try Again! You guessed too high”. That’s mean the random number (i.e., 42) doesn’t fall in the range from 50 to 100. That’s the importance of guessing half of the range. And again, the user guesses half of 50 (Could you tell me why?). So the half of 50 is 25. The user enters 25 as his/her second guess. This time compiler will show, “Try Again! You guessed too small”. That’s mean the integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user guessing is shorter, i.e., from 25 to 50. Intelligently! The user guessed half of this range, so that, user guessed 37 as his/her third guess.  This time again the compiler shows the output, “Try Again! You guessed too small”. For the user, the guessing range is getting smaller by each guess. Now, the guessing range for user is from 37 to 50, for which the user guessed 43 as his/her fourth guess. This time the compiler will show an output “Try Again! You guessed too high”. So, the new guessing range for users will be from 37 to 43, again for which the user guessed the half of this range, that is, 40 as his/her fifth guess.  This time the compiler shows the output, “Try Again! You guessed too small”. Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as his/her sixth guess. Which is wrong and shows output “Try Again! You guessed too small”. And finally, the User Guessed the right number which is 42 as his/her seventh guess.

          Total Number of Guesses = 7

    Explanation 2: If the User inputs range, let’s say from 1 to 50. And compiler randomly selected 42 as the integer. And now the guessing game started. So the half of 50 is 25. The user enters 25 as his/her First guess. This time compiler will show, “Try Again! You guessed too small”. That’s mean the integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user guessing is shorter, i.e., from 25 to 50. Intelligently! User guessed half of this range, so that, user guessed 37 as his/her second guess.  This time again the compiler shows the output, “Try Again! You guessed too small”. For the user, the guessing range is getting smaller by each guess. Now, the guessing range for user is from 37 to 50, for which the user guessed 43 as his/her third guess. This time the compiler will show an output “Try Again! You guessed too high”. So, the new guessing range for users will be from 37 to 43, again for which the user guessed the half of this range, that is, 40 as his/her fourth guess.  This time the compiler shows the output, “Try Again! You guessed too small”. Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as his/her fifth guess. Which is wrong and shows output “Try Again! You guessed too small”. And finally, the User Guessed the right number which is 42 as his/her sixth guess.

         Total Number of Guesses = 6

So, the minimum number of guesses depends upon range. And the compiler must calculate the minimum number of guessing depends upon the range, on its own. For this, we have a formula:-

 Minimum number of guessing = log2(Upper bound – lower bound + 1)

Step-by-step algorithm:

  • User inputs the lower bound and upper bound of the range.
  • The compiler generates a random integer between the range and store it in a variable for future references.
  • For repetitive guessing, a while loop will be initialized.
  • If the user guessed a number which is greater than a randomly selected number, the user gets an output “Try Again! You guessed too high“
  • Else If the user guessed a number which is smaller than a randomly selected number, the user gets an output “Try Again! You guessed too small”
  • And if the user guessed in a minimum number of guesses, the user gets a “Congratulations! ” Output.
  • Else if the user didn’t guess the integer in the minimum number of guesses, he/she will get “Better Luck Next Time!” output.

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 game, This is a number guessing game.\nYou got 7 chances to guess the number. Let's start the game")

number_to_guess = random.randrange(100)

chances = 7

guess_counter = 0

while guess_counter < chances:

    guess_counter += 1
    my_guess = int(input('Please Enter your Guess : '))

    if my_guess == number_to_guess:
        print(f'The number is {number_to_guess} and you found it right !! in the {guess_counter} attempt')
        break

    elif guess_counter >= chances and my_guess != number_to_guess:
        print(f'Oops sorry, The number is {number_to_guess} better luck next time')

    elif my_guess > number_to_guess:
        print('Your guess is higher ')

    elif my_guess < number_to_guess:
        print('Your guess is lesser')

OUTPUT: Below is the output of the above Program

OUTPUT FOR THE GUESSING GAME


Time Complexity: 
The time complexity of this code is O(log2n) where n is the difference between lower and upper bound of the range.

Space Complexity: 
The space complexity of this code is O(1) as all the variables used in this code are of the same size and no extra space is required to store the values.



Previous Article
Next Article

Similar Reads

Number Guessing Game Using Python Tkinter Module
Number Guessing Game using the Python Tkinter module is a simple game that involves guessing a randomly generated number. The game is developed using the Tkinter module, which provides a graphical user interface for the game. The game has a start button that starts the game and a text entry field where the user can enter their guess. The game also
5 min read
Number Guessing Game Using Python Streamlit Library
The game will pick a number randomly from 1 to 100 and the player needs to guess the exact number guessed by calculating the hint. The player will get 7 chances to guess the number and for every wrong guess game will tell you if the number is more or less or you can take a random hint to guess the number like (2+2=?, 3*3=?) to guess the number. In
5 min read
PyQt5 - Number Guessing Game
In this article we will see how we can create a number guessing name using PyQt5. The Number guessing game is all about guessing the number randomly chosen by the computer in the given number of chances. Below is how game will look like GUI implementation steps 1. Create a head label to show the game name, set its alignment font and color 2. Create
4 min read
Quote Guessing Game using Web Scraping in Python
Prerequisite: BeautifulSoup Installation In this article, we will scrape a quote and details of the author from this site http//quotes.toscrape.com using python framework called BeautifulSoup and develop a guessing game using different data structures and algorithm. The user will be given 4 chances to guess the author of a famous quote, In every ch
3 min read
Python implementation of automatic Tic Tac Toe game using random number
Tic-tac-toe is a very popular game, so let's implement an automatic Tic-tac-toe game using Python. The game is automatically played by the program and hence, no user input is needed. Still, developing an automatic game will be lots of fun. Let's see how to do this. NumPy and random Python libraries are used to build this game. Instead of asking the
5 min read
21 Number game in Python
21, Bagram, or Twenty plus one is a game which progresses by counting up 1 to 21, with the player who calls "21" is eliminated. It can be played between any number of players. Implementation This is a simple 21 number game using Python programming language. The game illustrated here is between the player and the computer. There can be many variatio
11 min read
Snake Water Gun game using Python and C
Snake Water Gun is one of the famous two-player game played by many people. It is a hand game in which the player randomly chooses any of the three forms i.e. snake, water, and gun. Here, we are going to implement this game using python. This python project is to build a game for a single player that plays with the computer Following are the rules
8 min read
Python - Cows and Bulls game
Cows and Bulls is a pen and paper code-breaking game usually played between 2 players. In this, a player tries to guess a secret code number chosen by the second player. The rules are as follows: A player will create a secret code, usually a 4-digit number. This number should have no repeated digits.Another player makes a guess (4 digit number) to
3 min read
Create a 2D Game with Python and the Arcade Library
We have a task to create a 2D game with Python and the Arcade library. In this article, we will demonstrate how to create a 2D game using Python and the Arcade library. What is Arcade Library?The Arcade library in Python is a modern framework designed for creating 2D games and graphical applications. It provides a user-friendly and intuitive interf
7 min read
Color game using Tkinter in Python
TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let's try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to play this game is 30 seconds. Colors used in this
4 min read
Rock, Paper, Scissor game - Python Project
In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of the three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”. Game Winner Conditions Let there be a Player w
15+ min read
Python | Program to implement simple FLAMES game
Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple FLAMES game without using any external game libraries like PyGame. FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately
6 min read
Python | Simple FLAMES game using Tkinter
Prerequisites: Introduction to TkinterProgram to implement simple FLAMES game Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and e
5 min read
Python | Pokémon Training Game
Problem : You are a Pokémon trainer. Each Pokémon has its own power, described by a positive integer value. As you travel, you watch Pokémon and you catch each of them. After each catch, you have to display maximum and minimum powers of Pokémon caught so far. You must have linear time complexity. So sorting won't help here. Try having minimum extra
1 min read
Mastermind Game using Python
Given the present generation's acquaintance with gaming and its highly demanded technology, many aspire to pursue the idea of developing and advancing it further. Eventually, everyone starts at the beginning. Mastermind is an old code-breaking game played by two players. The game goes back to the 19th century and can be played with paper and pencil
8 min read
Introduction to pyglet library for game development in Python
Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc on Windows, Mac OS and Linux. This library is created purely in Python and it supports many features like windowing, user interface event handling, Joysticks, OpenGL graphics, loading images, and videos, and playing sounds and music.
2 min read
Tic Tac Toe Game using PyQt5 in Python
In this article , we will see how we can create a Tic Tac Toe game using PyQt5. Tic-tac-toe, noughts, and crosses, or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. Below
5 min read
Create a Simple Two Player Game using Turtle in Python
Prerequisites: Turtle Programming in Python TurtleMove game is basically a luck-based game. In this game two-players (Red &amp; Blue), using their own turtle (object) play the game. How to play The game is played in the predefined grid having some boundaries. Both players move the turtle for a unit distance.Now both players flip the coin:if HEAD, t
4 min read
Tic Tac Toe game with GUI using tkinter in Python
Tic-tac-toe (American English), noughts and crosses (British English), or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. tkinter Python library is used to create the GUI.
15+ min read
Game of Craps in Python
In this article, we are going to discuss how to create the Game of Craps using Python. Rules of the game: Two dices are required to play and a player rolls two six-sided dice and adds the numbers rolled together.If on the first roll a player encounters a total of 7 or 11 the player automatically wins, and if the player rolls a total of 2, 3, or 12
5 min read
Python - MCQ Quiz Game using Tkinter
Prerequisite: Python GUI – tkinter Python provides a standard GUI framework Tkinter which is used to develop fast and easy GUI applications. Here we will be developing a simple multiple-choice quiz in python with GUI. We will be creating a multiple choice quiz in Python with Tkinter. First, we will create a library named Quiz in the directory of yo
6 min read
KBC game using Python
In this article, we will make a KBC game with almost all the features in CLI(Command Line Interface) mode using Python. Features of the game:Random questions every timeFour lifelinesAudience Poll50:50Double dipFlip the questionMade with the help of Matplotlib and NumPy libraries of python.Bar graph for audience poll lifelineRules to play the game:T
15 min read
Python Arcade - Adding Bullets in Game
In this article, we will learn how to add bullets to a game in Arcade using Python. Adding Bullet In this example, we are going to add bullets to the screen. For this, we will use some functions: draw_text(): This function is used to draw text to the screen using Pyglet’s label. Syntax: arcade.draw_text(text, x, y, color, size, width, align, font_n
4 min read
Higher-Lower Game with Python
In this article, we will be looking at the way to design a game in which the user has to guess which has a higher number of followers and it displays the scores. Game Play:The name of some Instagram accounts will be displayed, you have to guess which has a higher number of followers by typing in the name of that account. Make sure you type the name
8 min read
Snake Game Using Tkinter - Python
For many years, players all across the world have cherished the iconic video game Snake. The player controls a snake that crawls around the screen while attempting to consume food, avoiding obstacles or running into its own tail. It is a straightforward but addictive game. The snake lengthens each time it consumes food, and the player must control
12 min read
Brick Breaker Game In Python using Pygame
Brick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by the number of blocks broken and each time the player
14 min read
Dice game using Turtle in Python
Dice Roll Game using python turtleThe simple python program implements the rolling of dice using the turtle library and random module of python. The turtle library is used to draw graphics and animations on the screen, while the random library is used to generate random numbers and random selections that can be used to control the behavior of the t
3 min read
Automate Chrome Dino Game using Python
For this article, we will be building a Python bot that can play the "Chrome Dino Offline Game". Chrome dino is a dinosaur game that launches itself on your web browser when there is no internet connection. For the introduction of the game, the dinosaur has to jump to avoid the approaching cactus or duck to avoid the bird. The first fundamental ste
7 min read
Blackjack console game using Python
Blackjack is a popular two-player card game that is played with a deck of standard playing cards around the world in casinos. The main criteria for winning this game are chance and strategy. The challenge of this game is to get as close to 21 points as possible without exceeding them. That is why it is also known as Twenty-One. In this article, we
6 min read
Create Bingo Game Using Python
A card with a grid of numbers on it is used to play the popular dice game of bingo. Players check off numbers on their cards when they are selected at random by a caller, competing to be the first to mark off all of their numbers in a particular order. We'll examine how to utilise Python to create a simple bingo game in this lesson. The following i
9 min read
Practice Tags :