基本算术运算程序

2024-06-02 11:36:38 发布

您现在位置: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")

我得到的结果是

算术()

7*3个

什么是答案:21你知道吗

3+2个

什么是答案:5你知道吗

8*9个

什么是答案:72你知道吗

3*9个

什么是答案:2你知道吗

就这样!你知道吗

如何计算正确答案的数量并打印我所写的命令?你知道吗

提前谢谢


Tags: 答案inimport编码forifdefcounter
1条回答
网友
1楼 · 发布于 2024-06-02 11:36:38

if t1 == x,operators,y没有在xy上运行。运算符是字符串的形式,因此它检查t1是否等于,例如:(7, '*', 3)。要真正执行该操作,还可以使用eval(),您需要修复代码中的某些内容,以便它只在for循环完成后检查counter。你知道吗

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")

相关问题 更多 >