user3493677
user3493677

Reputation: 13

Else is being displayed even if correct

I've been having a problem in my multiplication game where else would be displayed even if the answer was correct.

Here is a sample of the code:

for num in range(0,1):
    number1 = random.randint(2,5)
    number2 = random.randint(2,5)
    answer = number1*number2
    guess = input("What is %d x %d? " % (number1, number2))

if guess == answer:
    print('Correct')
else:
    print('Incorrect')

Upvotes: 1

Views: 51

Answers (1)

aruisdante
aruisdante

Reputation: 9075

In Python 3.x, Input returns a str, vs. in Python 2.x where it attempted to evaluate the input as python code. And str == int always returns False, and doesn't throw an exception. You'd need to change your code to:

if guess == str(answer):

if you'd like to avoid throwing exceptions if the input isn't actually a number, or

gess = int(input(...))

if you intend to actually use guess as a number later on, but will then have to handle what happens if the user enters not a number.

Upvotes: 2

Related Questions