Home > Software engineering >  How to print the number of inputs entered in python?
How to print the number of inputs entered in python?

Time:05-18

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")

CodePudding user response:

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!")

CodePudding user response:

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!

  • Related