Python简单测验程序-如何解决问题循环

时间:2019-02-13 05:17:10

标签: python

Python学习者(版本2.7.5)。

当前,我正在研究一个简单的测验脚本,该脚本允许用户重新回答问题,并限制用户错误回答问题的机会。

因此将总限制设置为5,并且当达到限制时,将向用户显示一条消息(例如“ END!”)。该限制在所有问题之间共享。

当我测试下面提到的脚本时,我发现了几个问题。

1)即使问题1被错误回答了5次,问题2仍会显示,如果已经达到限制,如何防止下一个问题出现?

2)我想问如果达到限制,应该在哪里插入结束消息的代码(“ END!”)?

非常感谢!

def quiz():
score = 0
counter = 0
print "Please answer the following questions:"
print "Question 1 - ?"
print "a."
print "b."
print "c."
while counter <5:
    answer = raw_input("Make your choice:")
    if answer == "c":
        print("Correct!")
        score = score +1
    else:
        print("Incorrect!")
        counter = counter +1
print "Question 2 - ?"
print "a."
print "b."
print "c."
while counter <5:
    answer2 = raw_input("Make your choice:")
    if answer2 == "a":
        print("Correct!")
        score = score +1
    else:
        print("Incorrect!")
        counter = counter +1
    print
    print ("Your score is ") + str(score)

p.s。该代码似乎与复制和粘贴功能不相称。很抱歉给您带来不便

2 个答案:

答案 0 :(得分:0)

您应该真正重构它,以减少重复。因此,我将问答逻辑放入自己的函数中,并传递问题文本和正确答案。但是,按原样使用代码,每次增加计数器时,都需要检查其是否大于5,并仅使用while True进行循环。所以对于每个问题:

correct = "a"
while True:
    answer = raw_input("Make your choice:")
    if answer == correct:
        print("Correct!")
        score = score +1
        break
    else:
        print("Incorrect!")
        counter = counter +1
        if counter == 5:
            print "END!"
            return
        break

答案 1 :(得分:0)

您始终在打印第二个问题,而不检查是否已达到错误回答的限制。在打印第二个问题之前,您可以做类似的事情

if counter >= 5:
    print "END!"
    return

如果已达到限制,则条件内的return语句将终止quiz函数。这需要在打印任何问题之前完成。

此外,您可以使用带有答案的问题列表和简单的for循环来迭代所有问题,并避免每次重复相同的逻辑来改进代码。