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:
Now you can map an operator in a string to a function:
There are even ready-made functions for this is the
operator
module: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 withrandom.choice()
, replacing the list:Use separate names here:
Use the operator lib, creating a dict with operators as keys and the methods as values.
You need to cast
answer
to int a string could never be equal to an int. In the coderandom.choice(keys)
will pick one of the three dicts keys* - or +
, we do a lookup on the dict withoperators[operator]
i.eoperators["*"]
returnsmul
we can then callmul(n1,n2)
on the two random numbers.You also need to move the
number1 = random.randint(1, 20)
.. inside the while loop or you will end up asking the same questions and you can pass the string to input, you don't need to print.You are looking for the eval function.
eval
will take a string with math operators and compute the answer. In your final if statement check it like this...For your specific case, instead of making the dictionary, I would just create a list of tuples with the operator string representation and the operator builtin function:
Random.choice
on your list will return a tuple that you can unpack into the operator str representation and the function that you can call.