jibran magala
jibran magala

Reputation: 23

Python not reading all comparison operators in my while loop and if statement

I'm using the random module so Python can generate two random numbers that are given to the user to quiz their times tables up to 26. The only problem I'm having with this code is that Python is only obeying the != operand.

The code under "elif answer != win_number:" prints out what the user will get if the answer is incorrect, but even in times where the answer is correct, Python still prints that code, and skips the other comparison operators.

import random

while True:
    num1 = random.choice(range(0, 26))
    num2 = random.choice(range(0, 26))
    win_number = num1 * num2
    answer = input("What is " + str(num1) + " * " + str(num2) + "?: ")
    if answer == win_number:
        print("Correct! " + str(win_number) + " was the right answer!")
    elif answer == "?":
        print(win_number)
    elif answer != win_number:
        print("Incorrect! " + str(win_number) + " is the correct answer!")

If the user types 100 when Python asks what 10 * 10 is, I expect Python to go to the "if answer == win_number:" option and print out:

("Correct! " + str(win_number) + " was the right answer!")

Instead, it completely overrides this and goes straight to the "incorrect" string.

What am I doing wrong here?

Upvotes: 2

Views: 35

Answers (1)

Netwave
Netwave

Reputation: 42716

input function returns a string, so:

>>> "100" == 100
False

That is why the condition is not fulfilled. In order to fix your code you can cast the answer:

if int(answer) == win_number:

Upvotes: 1

Related Questions