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')
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
解决方案
Use functions in a dictionary:
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)
There are even ready-made functions for this is the operator module:
import operator
operator_functions = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
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)
Use separate names here:
operators = ["+","-","*"]
# ...
picked_operator = random.choice(operators)