用eval进行数学运算

2024-06-11 10:09:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在代码下面的代码行prod = eval("beg1" "operation" "beg2")不起作用!如果有人能给我一些帮助,我将不胜感激!你知道吗

def quiz():

    global tally

    tally = 0
    questions = 10

    name = input("What is your surname name")

    form = input("What is your form")




    for i in range(questions):
            ops = ['+', '-', '*', '/']
            operation = random.choice(ops)
            beg1 = random.randint(1, 10)
            beg2 = random.randint(1, 10)
            prod = eval("beg1" "operation" "beg2")
            print (prod)

            begAns = input("What is " + str(beg1)+ operation + str(beg2) + "? ")

            if int(begAns) == prod:
                print("That's right -- well done.\n")
                tally += 1
            else:
                print("No, I'm afraid the answer is ",prod)



    print ("Your score was", tally, "out of 10")

Tags: 代码nameinputyourisevalrandomprod
1条回答
网友
1楼 · 发布于 2024-06-11 10:09:31

如前所述,使用带+的字符串连接将operation变量的值放入eval的字符串中:

prod = eval(str(beg1) + operation + str(beg2))

否则,程序将尝试eval文本字符串"operation"(就像在python解释器中键入1operation4)。你知道吗

但是,我建议您不要使用eval。相反,创建一个操作符函数列表(来自^{}模块),然后将其应用于两个随机整数:

import operator
op_names = {operator.add:'+', operator.sub:'-', operator.mul:'*',
            operator.floordiv:'/'}
ops = list(op_names.keys())
operation = random.choice(ops)
beg1 = random.randint(1, 10)
beg2 = random.randint(1, 10)
prod = operation(beg1, beg2)
print('What is {0} {1} {2}?'.format(beg1, op_names[operation], beg2))

相关问题 更多 >