如何使用随机运算符在Python上进行计算 [英] How to do a calculation on Python with a random operator
问题描述
我正在做一个数学测试,其中每个问题将是随机选择的数字相加,相乘或相减.我的运算符将被随机选择,但是我无法确定如何与运算符进行计算.我的问题在这里:
I am making a maths test where each question will be either adding, multiplying or subtracting randomly chosen numbers. My operator will be chosen at random, however I cannot work out how to calculate with the operator. My problem is here:
answer = input()
if answer ==(number1,operator,number2):
print('Correct')
如何进行计算,以便在计算中使用运算符.例如,如果随机数是2和5,并且随机运算符是'+',那么我将如何编码我的程序,使其最终实际进行计算并得到答案,因此在这种情况下为:
How can I make it so the operator is used in a calculation. For example, if the random numbers were two and five, and the random operator was '+', how would I code my program so that it would end up actually doing the calculation and getting an answer, so in this case it would be:
answer =input()
if answer == 10:
print('Correct')
基本上,如何进行计算以检查答案是否正确? 我的完整代码如下.
Basically, how can I do a calculation to check to see if the answer is actually correct? My full code is below.
import random
score = 0 #score of user
questions = 0 #number of questions asked
operator = ["+","-","*"]
number1 = random.randint(1,20)
number2 = random.randint(1,20)
print("You have now reached the next level!This is a test of your addition and subtraction")
print("You will now be asked ten random questions")
while questions<10: #while I have asked less than ten questions
operator = random.choice(operator)
question = '{} {} {}'.format(number1, operator, number2)
print("What is " + str(number1) +str(operator) +str(number2), "?")
answer = input()
if answer ==(number1,operator,number2):
print("You are correct")
score =score+1
else:
print("incorrect")
对不起,如果我不清楚,请提前感谢
Sorry if I have been unclear, thanks in advance
推荐答案
在字典中使用函数:
operator_functions = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b,
}
现在您可以将字符串中的运算符映射到函数:
Now you can map an operator in a string to a function:
operator_functions[operator](number1, number2)
为此甚至还有现成的功能是 operator
模块:
There are even ready-made functions for this is the operator
module:
import operator
operator_functions = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
请注意,您在使用变量名时必须小心!您首先使用operator
创建了一个运算符列表,然后还使用它来存储您用random.choice()
选择的一个运算符,替换该列表:
Note that you need to be careful about using variable names! You used operator
first to create a list of operators, then also use it to store the one operator you picked with random.choice()
, replacing the list:
operator = random.choice(operator)
在此处使用单独的名称:
operators = ["+","-","*"]
# ...
picked_operator = random.choice(operators)
这篇关于如何使用随机运算符在Python上进行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!