Checking if two variables are equal

1k views Asked by At

In my code I'm making a basic multiplying game.

But in my game,

When you get the answer right, it says you got it wrong

Here's my whole code:

import random

score = 0
while True:
    num1 = random.choice(range(1,12))
    num2 = random.choice(range(1,12))
    answer = num1 * num2
    a = input("Solve for " + str(num1) + "x" + str(num2))
    if a == answer:
        print("congrats you got it right")
        score += 1
    else:
        print("Wrong sorry play again")
        print("Score was: " + str(score))
        break

When I get the right answer I get

Solve for 7x10 70
Wrong sorry play again
Score was: 0
3

There are 3 answers

2
gilch On BEST ANSWER

Other languages might let you get away with this, but Python is strongly typed. The input function gets a string, not a number. Numbers can't be equal to strings. Either convert the number to a string or the string to a number before you compare them. You can use str or int to convert.

2
grovina On

Function input returns what was typed as a string... in order to compare it with the answer, you need to either convert it to int:

if int(a) == answer:

or the other way around (convert answer to str):

if a == str(answer):

The first one may raise an exception if a is not parseable to an int. Here the docs.

PS: I really wonder how ur random library picked a 1070 sampling from 0 to 11...

0
U13-Forward On

Or use int(input()):

import random

score = 0
while True:
    num1 = random.choice(range(1,12))
    num2 = random.choice(range(1,12))
    answer = num1 * num2
    a = int(input("Solve for " + str(num1) + "x" + str(num2)))
    if a == answer:
        print("congrats you got it right")
        score += 1
    else:
        print("Wrong sorry play again")
        print("Score was: " + str(score))
        break