带有变量运算符的eval()

时间:2015-11-12 13:56:51

标签: python python-3.x operators eval

我使用Python 3.4。我收到错误:

Traceback (most recent call last):
  File "H:/GCSE's/Computing/Assesment/1/School Grading Script.py", line 44, in <module>
    if answer== eval(num1<currentop>num2):
TypeError: unorderable types: int() < str()

尝试执行此代码时

operator=["+","-","*"]
num1=random.randint(0,10)
num2=random.randint(0,10)
currentop=random.choice(operator)

answer = input("What is " + str(num1) + str(currentop) + str(num2) + "?\n")
if answer== eval(num1<currentop>num2):
    print("correct")
else:
    print(incorrect)

我想要做的是检查随机生成的变量的答案

4 个答案:

答案 0 :(得分:3)

使用eval是非常糟糕的做法,应该避免使用。对于您要做的事情,您应该使用operator

更改您的数据结构以使用字典,以便您更轻松地执行操作。像这样:

import operator

operators = {
    "+": operator.add
} 

num1 = 4
num2 = 5

res = operators.get("+")(num1, num2)

res的输出:

9

要将随机实施应用于此,您可以使用词典keys()对其执行random.choice

random.choice(list(operators.keys()))

应用随机的简单示例:

import operator
import random

operators = {
    "+": operator.add,
    "-": operator.sub,
    "*": operator.mul
}

num1 = 4
num2 = 5

res = operators.get(random.choice(list(operators.keys())))(num1, num2)

答案 1 :(得分:1)

您正在混合intnum1num2以及strcurrentop。将它们投射到str,它会起作用:

if answer == eval(str(num1)+currentop+str(num2)):

PS:您应avoid使用eval()

答案 2 :(得分:1)

您需要将其转换为字符串,还需要引用“不正确”:

import random
operator=["+","-","*"]
num1=random.randint(0,10)
num2=random.randint(0,10)
currentop=random.choice(operator)

answer = input("What is " + str(num1) + str(currentop) + str(num2) + "?\n")
if answer== eval(str(num1)+str(currentop)+str(num2)):
    print("correct")
else:
    print("incorrect")

正如其他人所指出的那样,除非出于测试目的,否则不要使用eval。

答案 3 :(得分:1)

以下是代码中的问题列表:

  1. eval与字符串变量一起使用。您应该转换num1num2为:str(num1)str(num2)
  2. 引用incorrect
  3. 您的变量answer包含字符串类型的值,因为input会返回一个字符串,因此您应该将input投射到int
  4. 因此,在纠正所有这些后,以下代码应该有效:

    import random
    operator=["+","-","*"]
    num1=random.randint(0,10)
    num2=random.randint(0,10)
    currentop=random.choice(operator)
    
    answer = int(input("What is " + str(num1) + str(currentop) + str(num2) + "?\n"))
    if answer== eval(str(num1)+str(currentop)+str(num2)):
        print("correct")
    else:
        print('incorrect')
    
相关问题