如何使用随机运算符对Python进行计算

时间:2015-06-18 21:44:03

标签: python random

我正在进行数学测试,其中每个问题将是添加,乘以或减去随机选择的数字。我的操作员将随机选择,但我无法确定如何与操作员一起计算。我的问题在这里:

answer = input()
if answer ==(number1,operator,number2):
    print('Correct')

如何使其成为运算符用于计算。例如,如果随机数是2和5,并且随机运算符是' +',我将如何对我的程序进行编码,以便最终实际进行计算并得到答案,所以在这种情况将是:

answer =input()
if answer == 10:
    print('Correct')

基本上,我如何进行计算以检查答案是否真的正确? 我的完整代码如下。

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")

很抱歉,如果我不清楚,请提前致谢

5 个答案:

答案 0 :(得分:3)

使用字典中的函数:

operator_functions = {
    '+': lambda a, b: a + b, 
    '-': lambda a, b: a - b,
    '*': lambda a, b: a * b, 
    '/': lambda a, b: a / b,
}

现在,您可以将字符串中的运算符映射到函数:

operator_functions[operator](number1, number2)

甚至还有现成的功能operator module

import operator

operator_functions = {
    '+': operator.add, 
    '-': operator.sub,
    '*': operator.mul,
    '/': operator.truediv,
}

请注意,您需要小心关于使用变量名称!您首先使用operator创建运算符列表,然后使用它来存储您使用random.choice()选择的一个运算符,替换列表:

operator = random.choice(operator)

在此处使用单独的名称

operators = ["+","-","*"]

# ...

picked_operator = random.choice(operators)

答案 1 :(得分:0)

使用operator lib,创建一个以操作符为键,方法为值的dict。

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")

你需要将answer转换为int,字符串永远不能等于int。 在代码中random.choice(keys)将选择三个词组* - or +中的一个,我们使用operators[operator]对词典进行查找,即operators["*"]返回mul我们可以在这两个随机数字上打mul(n1,n2)

您还需要在while循环中移动number1 = random.randint(1, 20) ..或者您最终会询问相同的问题,并且您可以将字符串传递给输入,您无需打印。

答案 2 :(得分:0)

您正在寻找eval功能。 eval将使用数学运算符的字符串并计算答案。在你的最终if语句中检查它是这样的......

if answer == eval(question):

答案 3 :(得分:0)

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 :(得分:0)

对于您的特定情况,我只是创建一个元组列表,而不是制作字典,其中包含运算符字符串表示和运算符内置函数:

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将返回一个元组,您可以将其解压缩到运算符str表示和您可以调用的函数中。

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