Python乘法程序游戏,再试一次选项

时间:2016-03-23 16:10:46

标签: python multiplication

我试图做一个乘法程序,在一个错误的答案后,它将有机会再次尝试。

这是我的代码:

from random import randint

wrong_answers = 0

for turn in range(100):

    # Choose two random integers for the question to the player
    factor_1 = randint(2,12)
    factor_2 = randint(2,12)

    # Precompute the correct answer to be able to check the player's answer
    correct_answer = factor_1*factor_2

    # As the question and get the player's response
    question = 'What is ' + str(factor_1) + ' times ' + str(factor_2) + ' times ' + '?'
    answer_string = raw_input(question)

    #Convert the player's response to a number (raw_input yields a string)
    answer_int = int(answer_string)

    # See if the player's answer is correct or not, and proceed accordingly
    if (answer_int == correct_answer):
        print 'Correct!'
    else:
        print 'Wrong! Try Again!'
        raw_input(question)
        answer_int = int(answer_string)
    if raw_input() == correct_answer:
            print 'Correct'
    else:
            wrong_answers = wrong_answers + 1
    if wrong_answers == 2:
            print 'Game Over Thanks for playing!!!'
            exit()

问题是当再次提出问题时,它没有计算出正确的答案..它会忽略它并算作错误的答案。在第二个错误答案之后,程序结束。

有没有办法再次提出问题,计算正确的答案,如果该人再次提出错误答案,则视为错误,程序会继续?

2 个答案:

答案 0 :(得分:1)

没有必要重新询问答案。事实上,你不应该这样做,因为此时程序尚未处理答案。我会在第一个“else”中增加 wrong_answers 变量,所以代码看起来像这样:

# See if the player's answer is correct or not, and proceed accordingly
if (answer_int == correct_answer):
    print 'Correct!'
else:
    if wrong_answers < 1:
        print 'Wrong! Try Again!'
    else:
        print 'Wrong!'
    wrong_answers = wrong_answers + 1

请注意,输出将是“错误!再试一次!”当答案没有产生游戏结束时。如果游戏结束,它将是“错误!游戏结束,感谢您玩!!!”。

我在这里留下了演示:https://repl.it/ByyD/0

我希望它可以帮到你。

答案 1 :(得分:0)

当您重新询问答案时,您不会将用户输入的内容分配给answer_string,因此它会使用原始值来计算answer_int。但我想这并不重要,因为您使用raw_input()代替answer_int来查看条目是否正确。