Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python Program for word Guessing Game
Next article icon

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:

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:

Total Guesses: 6

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

Algorithm

Implementation

Below is the Implementation of the Algorithm:

C
#include<math.h>#include<stdio.h>#include<stdlib.h>#include<time.h>intmain(){intlower,upper,x,guess,count=0,flag=0;inttotal_chances;// Taking Inputsprintf("Enter Lower bound: ");scanf("%d",&lower);// Taking Inputsprintf("Enter Upper bound: ");scanf("%d",&upper);// Seed the random number generatorsrand(time(0));// Generating random number between the lower and upperx=(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 rangewhile(count<total_chances){count++;// Taking guessing number as inputprintf("Guess a number: ");scanf("%d",&guess);// Condition testingif(x==guess){printf("Congratulations you did it in %d try!\n",count);// Once guessed, loop will breakflag=1;break;}elseif(x>guess){printf("You guessed too small!\n");}elseif(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");}return0;}
Python
importrandomprint("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 chancesgc=0# Guess counterwhilegc<ch:gc+=1guess=int(input('Enter your guess: '))ifguess==num:print(f'Correct! The number is{num}. You guessed it in{gc} attempts.')breakelifgc>=chandguess!=num:print(f'orry! The number was{num}. Better luck next time.')elifguess>num:print('Too high! Try a lower number.')elifguess<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.


Number guessing game in Python 3 and C

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp