带变量运算符的eval() [英] eval() with a variable operator
问题描述
我正在使用Python 3.4.我收到错误消息:
I'm Using Python 3.4. I receive the error:
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)
我要做的是对照随机生成的变量检查答案
What I want to do is to check the answer against the randomly generated variables
推荐答案
使用eval
确实是不好的做法,应避免使用.对于您要尝试执行的操作,您应该使用运算符.
Using eval
is really bad practice, and should be avoided. For what you are trying to do, you should be making use of operator.
更改数据结构以使用字典,以使您更轻松地执行操作.像这样:
Change your data structure to use a dictionary to make it easier on you to perform your operations. Something like this:
import operator
operators = {
"+": operator.add
}
num1 = 4
num2 = 5
res = operators.get("+")(num1, num2)
res的输出:
9
要对此应用随机实现,请使用字典keys()
在该字典上执行random.choice
:
To apply your random implementation in to this, you make use of the dictionaries keys()
to do a random.choice
on that:
random.choice(list(operators.keys()))
应用随机的简单示例:
Simple example applying random:
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)
这篇关于带变量运算符的eval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!