基本算术运算程序

时间:2018-10-07 21:42:09

标签: python

Click Here For Question

这是我的编码方式,但是我无法获得想要的结果

def arith():
    import random
    operators = ("+","*")

    for i in range(4):
        x = random.randint(1,10)
        y = random.randint(1,10)

        choose_operators = random.choice(operators)
        print (x,choose_operators,y)
        t1 = int(input("what is the answer:"))
        counter = 0
        if t1 == (x,operators,y):
            counter = counter + 1

            if counter > 3:
                print("Congratulations!")

            else:
                print("Please ask your teacher for help")

我得到的结果是

arith()

7 * 3

答案是什么:21

3 + 2

答案是什么:5

8 * 9

答案是什么:72

3 * 9

答案是什么?2

就是这样!

我如何计算正确答案的数量并打印我编写的命令?

预先感谢

1 个答案:

答案 0 :(得分:0)

if t1 == x,operators,y不在xy上运行。运算符为字符串形式,因此它正在检查t1是否等于例如:(7, '*', 3)。要实际执行此操作,您可以使用eval()。此外,您需要修复代码中的某些内容,以便仅在counter循环完成后才检查for

def arith():
    import random
    operators = ("+","*")
    counter = 0


    for i in range(4):
        x = random.randint(1,10)
        y = random.randint(1,10)

        choose_operators = random.choice(operators)
        print (x,choose_operators,y)
        t1 = int(input("what is the answer:"))
        if t1 == eval(str(x) + choose_operators + str(y)):
            counter = counter + 1

    if counter > 3:
        print("Congratulations!")

    else:
        print("Please ask your teacher for help")