eval() with a variable operator

社会主义新天地 提交于 2019-12-12 03:23:23

问题


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

when trying to execute this code

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


回答1:


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)

Output of res:

9

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)



回答2:


You are mixing int, num1 and num2 and str, currentop. Cast them to str and it would work:

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

PS: You should avoid using eval().




回答3:


You need to convert it to a string, also "Incorrect" needs to be quoted:

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

And as others have pointed out, unless for testing purposes, don't use eval.




回答4:


Following are the list of problems in your code:

  1. eval is used with string variables.You should convert num1 and num2 as: str(num1) and str(num2).
  2. quote incorrect
  3. also your variable answer contains string type of value as input returns a string so u should cast input to int.

So after correcting all these the following code should work:

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


来源:https://stackoverflow.com/questions/33673116/eval-with-a-variable-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!