Python Program to find secret Number Guessing Game

Python Program to find secret Number Guessing Game

In this section, you are going to play the "Guess the Number" game. In the first step you have think about a random number from 1 to 100  and the computer will tell you if each estimate is too high or too low. If you can beat the number of attempts you win.

It's a good game to code because it uses random numbers, loops and input from the user in a small program. Since this program is a game, we call the user player. But the "user" is also correct.

So let's understand this concept how it works. 

Steps:

1. Choose a Number between 0 to 100. It means you choose that number in your mind and run the program.

2. Computer ask to you number is 50?

3. If the number you think is less than 50 then type l for low and if the number is greater than 50 then type h for high. 

4. Repeat the step. when you find correct number type c. It shows invalid output if you entered any wrong input.

Let's take a look at code how to play number guessing game in Python Programming.


Python Code:

low = 0
high = 100
guess = (high+low)/2
print("choose a number between 0 and 100")
guessing = True
while guessing:
print("Is your number= " + str(guess) + '?')
pointer = input("enter h when guess is too high, l when guess is too low, c when guessed correctly")
if pointer=='h':
high = guess
guess=(low+high)/2
elif pointer=='l':
low = guess
guess = (high+low)/2
else:
if(pointer=='c'):
guessing=False
print("your number is approximate to", guess)
else:
print("invalid input")

Output:
choose a number between 0 and 100
Is your number= 50.0?
enter h for guess is too high, l for guess is too low, c for guessed correctlyh
Is your number= 25.0?
enter h for guess is too high, l for guess is too low, c for guessed correctlyl
Is your number= 37.5?
enter h for guess is too high, l for guess is too low, c for guessed correctlyl
Is your number= 43.75?
enter h for guess is too high, l for guess is too low, c for guessed correctlyl
Is your number= 46.875?
enter h for guess is too high, l for guess is too low, c for guessed correctlyc
your number is approximate to 46.875