带变量op的eval()

2024-09-27 00:20:31 发布

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

我使用的是python3.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()

尝试执行此代码时

^{pr2}$

我要做的是对照随机生成的变量来检查答案


Tags: pymost错误linescriptcallfilegrading
3条回答

使用eval是一种很糟糕的做法,应该避免。对于您正在尝试的操作,您应该使用operator。在

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

import operator

operators = {
    "+": operator.add
} 

num1 = 4
num2 = 5

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

res输出:

^{pr2}$

要在中应用随机实现,请使用字典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)

你在混合intnum1和{}和{},currentop。把它们投射到str上,就可以了:

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

PS:您应该使用eval()avoid。在

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

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。在

相关问题 更多 >

    热门问题