以下是我的代码,它有效。它会创建两个随机数,一个随机运算符并将它们组合在一起,但是在执行此操作后它不会对它们求和。我需要的是程序将其识别为方程式,而不是简单地打印出各个变量。
所以,为了避免混淆;我的问题是:如何使用firstNumber
选择secondNumber
和operator
进行求和,而不是简单地将它们一起打印出来?
from random import choice
from random import randint
ranOperator = ["*", "/", "+", "-"]
def askQuestion():
firstNumber = randint(1,10)
secondNumber = randint(1,10)
operator = choice(ranOperator)
generateQuestion = ' '.join((str(firstNumber), operator, str(secondNumber)))
print(generateQuestion)
askQuestion()
当前输出(示例):
4 + 3
使用上面相同的数字,我想要发生的事情:
7
答案 0 :(得分:7)
不依赖eval
的一种方法是使用operator
模块来表示操作。
from random import choice
from random import randint
from operator import add, sub, truediv, mul
ranOperator = [add, sub, truediv, mul]
def askQuestion():
firstNumber = randint(1,10)
secondNumber = randint(1,10)
the_operator = choice(ranOperator)
result = the_operator(firstNumber, secondNumber)
print(result)
答案 1 :(得分:3)
您需要的是eval()
。
eval()
将传递的字符串作为Python表达式计算并返回结果。
from random import choice
from random import randint
ranOperator = ["*", "/", "+", "-"]
def askQuestion():
firstNumber = randint(1,10)
secondNumber = randint(1,10)
operator = choice(ranOperator)
generateQuestion = ' '.join((str(firstNumber), operator, str(secondNumber)))
print(eval(generateQuestion))
askQuestion()
<强>演示:强>
>>> eval('1+1')
2
>>> eval('5-3')
2
>>> eval('2*3')
6
>>> eval('6/3')
2
答案 2 :(得分:3)
扩展dseuss的答案以合并任何函数并通过使用字典将函数映射到其符号来打印类似数学的等式
from random import choice
from random import randint
add = lambda x,y: x+y
substract = lambda x,y: x-y
divide = lambda x,y: x/y
multiply = lambda x,y: x*y
ranOperator = {"*":multiply, "/":divide, "+":add, "-":substract}
def askQuestion():
firstNumber = randint(1,10)
secondNumber = randint(1,10)
operator_key = choice(list(ranOperator.keys()))
answer = ranOperator[operator_key](firstNumber,secondNumber)
print("{} {} {} = {}".format(firstNumber, operator_key, secondNumber, answer))
askQuestion()