使用eval执行数学运算

时间:2015-04-19 18:05:19

标签: python built-in

在下面的代码中,代码行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")

1 个答案:

答案 0 :(得分:2)

正如所指出的,使用字符串连接与+operation变量的值放入获得eval ed的字符串中:

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

否则程序会尝试eval文字字符串"operation"(就像在python解释器中键入1operation4一样)。

但是,我建议你根本不要使用eval。而是,创建一个运算符函数列表(来自operator模块),然后将其应用于两个随机的int:

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