1

Hi I was working on a python guessing game where the computer chooses a number and the user tries to guess the number. Now I want to add a feature to count the number of guesses a user made before getting the correct number. I think for that we need to count the number of inputs. What should I add to reach that goal?Here is my code so far:


print("Welcome to the Guessing Game. In this game, I will choose a random number between 1 and 100 and your goal will be to guess the number I choose. I will tell you if the number you guess is higher or lower than my choice. Lets Start.")

a = random.randint(0, 100)

print("I have chosen my number. Lets start !")

b = int(input("Enter guess"))  

while b != a:  
    if a < b:
        print("LOWER")
    if a > b:
        print("HIGHER")
    b = int(input("Enter guess"))

print("You WIN")

2 Answers 2

1

You just need to add a counter and increment it every time the user guesses.

print("Welcome to the Guessing Game. In this game, I will choose a random number between 1 and 100 and your goal will be to guess the number I choose. I will tell you if the number you guess is higher or lower than my choice. Lets Start.")

a = random.randint(0, 100)

print("I have chosen my number. Lets start !")

b = int(input("Enter guess"))  

numGuesses = 1
while b != a:  
    if a < b:
        print("LOWER")
    if a > b:
        print("HIGHER")
    b = int(input("Enter guess"))
    numGuesses += 1

print("You WIN")
print(f"It took you {numGuesses} guesses to get it right!")
Sign up to request clarification or add additional context in comments.

Comments

1

This can be done relatively simply by declaring a guesses variable outside the while loop. You can also get rid of the first input question by shifting it from the bottom of the while loop to the top. We then just need to declare b as None and you're good to go!

import random
a = random.randint(0, 3)

print("I have chosen my number. Lets start!")

guesses = 0
b = None

while b != a:
    b = int(input("Enter guess: ")) 
    if a < b:
        print("LOWER")
    if a > b:
        print("HIGHER")
    guesses += 1

print(f'You WIN after {guesses} guesses!')

And then we just add an f string at the end to tell us how many guesses you made!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.