0

No matter if I enter the correct number, it still returns “Try again”. How can I rectify this?

import random
from random import randint
num = randint(1000, 9999) 

print (num)

while True:
    guess = input ("Please guess a four digit number. ")
    print (guess)

if guess == num:
    print ("Well Done!")
else:
    print ("Try again")

3 Answers 3

5

Your num is an int while the inputted guess is a string, so they can never be equal. If you wish to compare them, you should make sure they're both from the same type

E.g., use only strings:

num = str(randint(1000, 9999))

or convert the user's guess to an int:

guess = int(input("Please guess a four digit number. "))
Sign up to request clarification or add additional context in comments.

Comments

0

Mureinik is correct about the fact that strings cannot be compared with integers, but I'd like to clarify that int() can explode on you (figuratively) if the function does not receive numbers.

To remedy this, put the contents of the while loop into a try statement:

import random
num = random.randint(1000, 9999)

print (num)

while True:
    try: 
        guess = input("Please guess a four digit number.")
        print(guess)
        if int(guess) == num:
            print ("Well Done!")
        else:
            print ("Try again")
    except ValueError:
        print ("Input is not an integer. Redo!")

2 Comments

Do not use bare except clauses.
Thx, I’ll try that.
0

You didn't convert the user input into an integer. You're comparing an integer and a string.

from random import randint as rn

while 1:
 print ('Well Done!' if int(input('Please guess a four digit number. ')) is rn(1000, 9999) else 'Try again')

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.