Why do the right answers come out wrong?

from random import randint 

correct = 0

for i in range(10):
    n1 = randint(1, 10)
    n2 = randint(1, 10)
    prod = n1 * n2

    ans = input("What %d times %d? " % (n1, n2))
    if ans == prod:
        print ("That right -- well done.\n")
        correct = correct + 1
    else:
        print ("No, I'm afraid the answer is %d.\n" % prod)

print ("\nI asked you 10 questions.  You got %d of them right." % correct)
print ("Well done!")

      

What is 1 time 5? 5 No, I'm afraid the answer will be 5.

What's 9 times 3? 27 No, I'm afraid the answer will be 27.

What is 4 times 1? 4 No, I'm afraid the answer will be 4.

+3


source to share


2 answers


You need to convert your input string to a number:



for i in range(10):
    n1 = randint(1, 10)
    n2 = randint(1, 10)
    prod = n1 * n2

    ans = int(input("What %d times %d? " % (n1, n2)))
    if ans == prod:
        print("That right -- well done.\n")
        correct += 1
    else:
        print("No, I'm afraid the answer is %d.\n" % prod)
print("\nI asked you 10 questions. You got %d of them right." % correct)
print("Well done!") 

      

+2


source


in your case ans

, a string. therefore, you must cast like:



ans = int(input("What %d times %d? " % (n1, n2)))

      

0


source







All Articles