Python请告诉我我的数学答案是否正确

时间:2014-12-10 18:58:37

标签: python

我希望添加一个功能,告诉用户他/她何时正确回答了随机数学问题。

import random

def answers():
    correct_answer_P_ = ((str(difficulty_one + difficulty_one))) #P = PLUS, ADDITION +  

    correct_answer_M_ = ((str(difficulty_one * difficulty_one))) #M = MULTIPLY *

    correct_answer_T_ = ((str(difficulty_one - difficulty_one))) #T = TAKE AWAY, MINUS -

def random_symbols():
    symbols = random.choice (["+","-","*"])
    return symbols

def difficulty_one():
    dif_one = random.randrange (1,10,1)
    return dif_one

def questions():
    question = (str(difficulty_one())) + random_symbols() + (str(difficulty_one())) + " = "
    return question


start = input("press start to begin!: ")


if (start == "start"):
    print ("here's ten questions, good luck!")
    for questions_num in range(1,11):
        print ("Question ",questions_num)
        input(questions())
        if (random_symbols == "+"):
            if (dif_one == correct_answer_P_):
                            print("correct!")

        elif(random_symbols == "-"):
            if (dif_one == correct_answer_T_):
                            print("correct!")

        elif(random_symbols == "*"):
            if (dif_one == correct_answer_M_):
                            print("correct!")
        else:
            print("incorrect!")

我试图从朋友那里得到一些建议说我需要为每个随机插入的符号创建变量;变量应该比较用户的回答并说出正确但是它会跳过所有的if语句并直接说出错误。

有什么建议吗?如果我正在做一些愚蠢的事情,请不要苛刻,因为我刚刚开始使用python。

请注意,此代码中的部分已从我的原始部分中删除,以便人们可以轻松查看我正在尝试执行的操作。

1 个答案:

答案 0 :(得分:0)

有一种更简单的方法来实现这一点。试试这个:

import operator

questions = [(1,2), (4,2), (8,1), (10,100)] # operands for your questions
operators = {"+" : operator.add,
             "-" : operator.sub,
             "*" : operator.mul}
# a dictionary containing each operator's symbol and the resulting function
# (operator.add(x,y) is equivalent to x+y)

for num, operands in enumerate(questions,start=1):
    # iterate through each set of operands, enumerating starting at 1 
    operator = random.choice(operators)
    # return a random symbol from operators
    answer = operators[operator](*operands)
    # operators[operator] is the function, which we then call with the operands
    q_text = "{} {} {} = ?".format(str(operands[0]), operator, str(operands[1]))
    print("Question {}".format(str(num)))
    print(q_text)
    user_answer = input(">>")
    if float(user_answer) == answer:
        # correct!
    else:
        # fail!