Program to ask multiplication questions

0
I want to make a program in Python (2.7.14) that generates two numbers randomly (from 0 to 10), multiply them, ask the result to the user, and display if the result is correct or wrong, until it is typed the string "end", my code looks 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!!"

But 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 so, how?

    
asked by anonymous 02.12.2017 / 16:20

2 answers

0

Having some problems, besides comparing a string with a number, letting you enter text where you expect a number does not seem like a good idea. Of course you can handle the exception raised. It would not be a bad idea since it is a possible mistake. But for simplicity I prefer to just change the input that indicates the end.

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

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 no Coding Ground . Also I put GitHub for future reference .

    
02.12.2017 / 16:48
0

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

To solve, just modify if , doing a conversion of the variable m to integer:

if int(m)==mult :
    print "correto!"
else :
    print "errado!!"
    
02.12.2017 / 16:34