Reputation: 143
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.')
Upvotes: 0
Views: 52
Reputation: 77
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):
Upvotes: 1
Reputation: 194
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.
Upvotes: 1