0

When I try to guess the randomly generated number, the correct guess is never correct, and therefore the inner loop never finishes. I have tried debugging with print statements.

from random import randint

print('Welcome to the Number Guessing Game (Numbers 1 - 1000).')

while True:
    tries = 0
    random_num = randint(1, 10)
    print(random_num)
    guess = input('guess my number, human: ')

    while random_num is not guess:
        guess = input('Try again: ')
        print(guess)
        tries += 1

    print('Correct!' + ' It took you' + str(tries) + ' tries.')
Armend Veseli
  • 143
  • 2
  • 9

2 Answers2

1

First of all, you have to convert the guess variable to an integer. Input simply returns strings and a string can't be equal to an integer.


The second problem with your programme is that is and is not keywords check, whether two "variables" (in Python, variables are just references to an object) are/aren't pointing to the same object.

This might not be your case even if your guess was correct (even though they can have the same value they are different objects). Sometimes this is not a problem since Python will point both "variables" to the same object for efficiency. But you can't be sure, can you!

Check this: Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?

Anyways, it's better to use the == and != operator in similar cases and the second problem will disappear.

kmartin
  • 194
  • 3
  • 9
1

Type error...

Add more debug code for the answer

print('random_num',random_num, type(random_num))
print('guess', guess, type(guess))

Output

Welcome to the Number Guessing Game (Numbers 1 - 1000).
random_num 2 <class 'int'>
guess my number, human: 2
guess 2 <class 'str'>

Fix:

while random_num is not int(guess):
  • The `is` will only work for numers in the range [-5, 256]. Python only creates one copy in memory of those numbers which is why `is` works there. For numbers outside this range, `is` will return False. Try `x=300; print(x is 300)`. This outputs False. – SyntaxVoid May 22 '19 at 16:23