Number Guessing Game

Question:
Every time I run it, it always outputs “Incorrect!” even though I am inputing the same thing as the targetnumber variable and I don’t know what I’m doing wrong. The “while” is supposed to be there to terminate the loop, but it goes on forever.
My program is also supposed to have this: User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, user will get a “Well guessed!” message, and the program will exit.

Help would be much appreciated!

code snippet

import random
targetnumber = random.randint(1,10)
print (targetnumber)
playerguess = input("Enter a number between 1-10: ")

if targetnumber == playerguess:
  print("Correct!")
while targetnumber != playerguess:
  print("Incorrect!")

Hey @shane010207 welcome to the forums!

I see the problem, you need to put your if statement and the input in the while loop, it should look something like this:

import random
targetnumber = random.randint(1,10)
print (targetnumber)

while targetnumber != playerguess:
  playerguess = input("Enter a number between 1-10: ")
  if targetnumber == playerguess:
    print("Correct!")
  else:
    print("Incorrect!")

If you didn’t have it in the loop that code would never check for it, and the input would never ask the question. Hope this helps!

2 Likes

A good exercise is to go through your code as if you were running it line by line. This helps you understand your code and possibly catch some logic errors.

In this case, you can see that your program only asks for the user’s input once, then reuses that user input forever.

However, there is another more subtle problem. The function input() will always return an string, never an integer. Integers are never equal to strings. A fix is to either have both be strings, or both be integers.

Here’s a refactored version (the strip() method removes leading and trailing whitespace from user input):

import random

targetnumber = str(random.randint(1, 10))
print(targetnumber)

playerguess = input("Enter a number between 1-10: ").strip()
while targetnumber != playerguess:
  print("Incorrect!")
  playerguess = input("Enter a number between 1-10: ").strip()
print("Correct!")
4 Likes