I am trying to generate a guessing game, but after the first guess my program returns a response infinitely. I’ve tried to add in continue and break but these aren’t working. What am I missing? Where is my logical error?
Code is below:
Thanks in advance
#Generate a random number between 1 and 9 (including 1 and 9). Ask the user
#to guess the number, then tell them whether they guessed too low, too high, or exactly right.
# Keep the game going until the user types “exit”
#Keep track of how many guesses the user has taken, and when the game ends, print this out.
count = 0
num = random.randint(0, 10)
user = input("Guess a number: ")
while user != num and user != "exit":
if user.lower() == "exit":
elif user == int(user):
elif int(user) > num:
print("You guessed too high!")
elif int(user) < num:
print("You guessed too low")
elif int(user) == num:
print("You are exactly right")
print("It took you ", count, "tries")
So your user enters a number
Then you enter a loop
The first elif checks if the user entered an int if so it increments count and then the continue causes it it to go back to the start of the loop.
The user never gets to input another number so the same thing happens every time through the loop unless the user types exit or gets the number on his first guess.
You could add a statement after the while
If count >0 : user = input (“try again”)
Also input always returns a string so you need to test for exit first then do
Because of the continue statements none of the other code will ever execute.
Remove the first if condition and put the
User.lower() in the while statement.
You then need to do
user = int (user)
At the moment you do not convert the input into a int at all the double equall is a comparison that returns true or false
You dont need any of the continue statements delete them
You need to get another guess from the user with an input statement somewhere in the loop. If you dont and the user does not guess right on the first attempt then the value never changes. Try covering everything above the while statement then think what happens if user inputs 2 and the random number if 7.
Another issue is the condition used in the while loop: when
user != num and user != “exit”
is set as the condition, the codes inside the while loop only execute if the user entered incorrect number or string other than “exit”. But if the user entered the correct number or “exit”, it will not get into the loop and bypass all codes within the loop, so the codes for breaking the loop if the decapitalized input string is “exit”, and the codes for the response if the correct number were entered will not execute at all. And since there is no more code below the while loop, nothing will happen…