How to do a calculation on Python with a random op

2019-06-02 04:46发布

问题:

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

回答1:

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)


回答2:

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...

if answer == eval(question):


回答3:

import operator
import random
operators = {
    "+": operator.add,
    "-": operator.sub,
    "/": operator.truediv,
    "*": operator.mul
}


y = float(input("Enter number: "))
z = float(input("Enter number: "))
x = random.choice(operators.keys())

print (operators[x](y, z))


回答4:

Use the operator lib, creating a dict with operators as keys and the methods as values.

from operator import add, mul, sub
import random

score = 0  # score of user
questions = 0  # number of questions asked
operators = {"+": add, "-": sub, "*": mul}
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")
# create list of dict keys to pass to random.choice
keys = list(operators)
# use range 
for _ in range(10):  
    number1 = random.randint(1, 20)
    number2 = random.randint(1, 20)
    operator = random.choice(keys)
    # cast answer to int, operators[operator]will be either add, mul or sub
    # which we then call on number1 and number2
    answer = int(input("What is {} {} {}?".format(number1,operator, number2)))
    if answer == (operators[operator](number1, number2)):
        print("You are correct")
        score += 1
    else:
        print("incorrect")

You need to cast answer to int a string could never be equal to an int. In the code random.choice(keys) will pick one of the three dicts keys * - or +, we do a lookup on the dict with operators[operator] i.e operators["*"] returns mul we can then call mul(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.



回答5:

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:

import operator
import random

operators = [('+', operator.add), ('-', operator.sub), ('*', operator.mul)]

for i in range(10):
    a = random.randint(1, 20)
    b = random.randint(1, 20)
    op, fn = random.choice(operators)
    print("{} {} {} = {}".format(a, op, b, fn(a, b)))

14 * 4 = 56
6 + 12 = 18
11 + 11 = 22
7 - 9 = -2
9 - 4 = 5
17 * 5 = 85
19 - 13 = 6
9 - 4 = 5
20 * 20 = 400
5 * 3 = 15

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.

import operator
import random

score = 0
operators = [('+', operator.add), ('-', operator.sub), ('*', operator.mul)]

for i in range(10):
    a = random.randint(1, 20)
    b = random.randint(1, 20)
    op, fn = random.choice(operators)
    prompt = "What is {} {} {}?\n".format(a, op, b)
    if int(input(prompt)) == fn(a, b):
        score += 1
        print("You are correct")
    else:
        print("incorrect")

print("Score: {}".format(score))


标签: python random