带有变量运算符的 eval()

eval() with a variable operator

我正在使用 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)

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

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

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

import operator

operators = {
    "+": operator.add
} 

num1 = 4
num2 = 5

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

资源输出:

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)

您正在混合 intnum1num2 以及 strcurrentop。将它们投射到 str 就可以了:

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

PS:您应该 avoid 使用 eval()

需要转成字符串,另外"Incorrect"需要加引号:

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。

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

  1. eval 与字符串一起使用 variables.You 应该转换 num1num2 为:str(num1)str(num2).
  2. 引用incorrect
  3. 你的变量 answer 包含字符串类型的值作为 input returns 一个字符串所以你应该将 input 转换为 int.

所以在更正所有这些之后,以下代码应该可以工作:

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