Program to ask multiplication questions

Asked

Viewed 316 times

1

I intend to make a program in Python (2.7.14) that generates two numbers randomly (from 0 to 10), multiply them, ask the result for the user, and display whether the result is correct or wrong, until typed the string "end", my code went like this:

    import random

    m = 0

    while m!="fim" :
        n1=int(random.random()*10)
        n2=int(random.random()*10)

        m = raw_input("{} * {} = ".format(n1,n2))  
        mult = int(n1*n2)

        if m==mult :
            print "correto!"

        else :
            print "errado!!"

However, whenever I type something, the program always prints "wrong!!", What is the error in my code? Is it well written? Is it possible to optimize it more? If yes , as?

2 answers

0

If you do type(m) and type(mult) will see that the first is a str while the second is int.

To solve just modify the if, making a conversion of the variable m for whole:

if int(m)==mult :
    print "correto!"
else :
    print "errado!!"

0


There are some problems, besides being comparing a string with a number, letting you type a text where you expect a number does not seem like a good idea. Of course you can handle the generated exception. It would not be a bad idea since it is a possible error. But to simplify I preferred only to change the entry indicating the end.

The numbers generated were also wrong, generating 0 that I imagine is not what you want, since this seems to be a case of multiplication tables. If you really want 0, you can go back to 10 as it was.

import random
m = 1
while m != 0:
    n1 = int(random.random() * 9) + 1
    n2 = int(random.random() * 9) + 1
    m = int(raw_input("{} * {} = ".format(n1, n2)))
    print ("correto!" if m == n1 * n2 else "errado!!")

See working on ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.