首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我如何在一个小测验中对每一个问题实现一个定时器?

我如何在一个小测验中对每一个问题实现一个定时器?
EN

Stack Overflow用户
提问于 2020-03-07 10:55:49
回答 1查看 211关注 0票数 1

我试着做一个小测验,其中一个标准是限制测验中每一个问题的解决时间。我查阅了一些教程,但有些需要输入x秒才能使计时器停止,而另一些则更像是秒表.

我想知道,如果30秒的周期已经结束,那么当问题被打印出来,跳到下一个问题时,我该怎么做呢?我对计时器功能一无所知,甚至无法将它们实现到我的代码中。有人能给我一些提示吗?这样我就可以在实现一个工作计时器方面取得更大的进步了吗?

谢谢!

编辑部分如下:我想在编码上实现的计时器:

代码语言:javascript
复制
import time
import threading

def atimer():
    print("Time's up.")

a_timer = threading.Timer(10.0, atimer)
a_timer.start()
print("")

这就是我试图将计时器实现到的全部编码。我注意到,当我试图定义qtimer以只打印1到2行语句时,计时器可以工作,但我希望计时器停止,转到第二个问题,或者停止,让用户再次尝试重试这个问题,所以我尝试在定义之后附加一堆代码,但它没有工作。我知道我在这里很可能做错了什么,因为我对时间或线程函数不太熟悉。有解决办法吗?

代码语言:javascript
复制
def qtimer():
    print("I'm sorry but your time is up for this question.")
    print("You may have another attempt if you wish to, with reduced marks allocated.")
    response1 = input("Type 'Yes' for another attempt, anything else to skip: ")
    if response1 == "Yes":
        Answ = input("Which option would you go for this time?: ")
        Answ = int(Answ)
        if possible[Answ - 1] == qaItem.corrAnsw:
            print("Your answer was correct.")
            corr += 1
            marks += 0.5 * qaItem.diff
        else:
            print("Your answer was wrong.")
            print("Correct answer was: " + qaItem.corrAnsw)
            print("Explanation: " + qaItem.expl)
            print("")
    else:
        print("Correct answer was: " + qaItem.corrAnsw)
        print("Explanation: " + qaItem.expl)
        print("")

class A:
  def __init__(self, question, correctAnswer, otherAnswers, difficulty, explanation):
    self.question = question
    self.corrAnsw = correctAnswer
    self.otherAnsw = otherAnswers
    self.diff = difficulty
    self.expl = explanation

qaList = [A("What is COVID-19?", "Coronavirus Disease 2019", ["Wuhan virus", "I don't understand...", "Coronavirus Disease v19"], 1, "Explanation 1"),
A("What describes COVID-19?", "A disease", ["A virus", "A parasite", "A bacteriophage"], 1, "Explanation 2"),
A("What causes COVID-19?", "SARS-CoV-2", ["Coronavirus", "Mimivirus", "Rubeola Virus"], 1, "Explanation 3"),
A("Which of the following is used in COVID-19 treatment?", "Lopinavir / Ritonavir ", ["Midazolam / Triazolam", "Amiodarone", "Phenytoin"], 2, "Explanation 4"),
A("Which of the following receptors is used by COVID-19 to infect human cells?", "ACE-2 Receptors", ["ApoE4 Receptors", "TCR Receptors", "CD28 Receptors"], 3, "Explanation 5")]

corr = 0
marks = 0
random.shuffle(qaList)
for qaItem in qaList:
    q_timer = threading.Timer(5.0, qtimer)
    q_timer.start()
    print(qaItem.question)
    print("Possible answers are:")
    possible = qaItem.otherAnsw + [qaItem.corrAnsw]
    random.shuffle(possible)
    count = 0
    while count < len(possible):
        print(str(count+1) + ": " + possible[count])
        count += 1
    print("Please enter the number of your answer:")
    Answ = input()
    Answ = str(Answ)
    while not Answ.isdigit():
        print("That was not a number. Please enter the number of your answer:")
        Answ = input()
        Answ = int(Answ)
    Answ = int(Answ)
    while Answ > 4 or Answ < 1:
        print("That number doesn't correspond to any answer. Please enter the number of your answer:")
        Answ = input()
        Answ = int(Answ)
    if possible[Answ-1] == qaItem.corrAnsw:
        print("Your answer was correct.")
        corr += 1
        marks += 1 * qaItem.diff
    else:
        print("Your answer was wrong.")
        response = input("Would you want to try again? If so, input 'Yes' to attempt it again, if not just input whatever!")
        if response == "Yes":
            Answ = input("Which option would you go for this time?: ")
            Answ = int(Answ)
            if possible[Answ - 1] == qaItem.corrAnsw:
                print("Your answer was correct.")
                corr += 1
                marks += 0.5 * qaItem.diff
            else:
                print("Your answer was wrong.")
                print("Correct answer was: " + qaItem.corrAnsw)
                print("Explanation: " + qaItem.expl)
                print("")
        else:
            print("Correct answer was: " + qaItem.corrAnsw)
            print("Explanation: " + qaItem.expl)
            print("")

print("You answered " + str(corr) + " of " + str(len(qaList)) + " questions correctly.")
print("You have achieved a total score of " + str(marks) + ".")
EN

回答 1

Stack Overflow用户

发布于 2020-03-07 11:27:35

即使有计时器,主线程也不能继续等待用户输入一个数字;因此,如果用户什么也不做,计时器函数就会运行,一旦完成,主线程仍在等待输入

代码语言:javascript
复制
print("Please enter the number of your answer:")
Answ = input() 

您可以有一个定时器线程设置的全局标志,告诉主线程在计时器代码中将接收到的输入作为response1来处理,还可以有一个标志告诉计时器收到了答案,等等,这样很快就变得相当复杂。

因此,不要试图通过计时器和主线程之间的通信来绕过对input的阻塞调用,而是从https://stackoverflow.com/a/22085679/1527中选择非阻塞输入示例,并在时间成熟时尽早停止循环。

代码语言:javascript
复制
def timed_input(msg, timeout=10):
    kb = KBHit()

    print(msg)

    end_time = time.time() + timeout
    warn_time = 5

    result = None

    while True:

        if kb.kbhit():
            c = kb.getch()
            if '0' <= c <= '9':
                result = int(c)
                break                
            print(c)

        if time.time() > end_time:
            print('time is up')
            break

        if time.time() > end_time - warn_time:
            print(f'{warn_time}s left')
            warn_time = warn_time - 1

    kb.set_normal_term()

    return result


# Test    
if __name__ == "__main__":
    result = timed_input('Enter a number between 1 and 4')
    if result is None:
        print('be quicker next time')
    elif 1 <= result <= 4:
        print('ok')
    else: 
        print(f'{result} is not between 1 and 4')

还请注意,将代码分解成更小的函数有助于使代码更容易理解,测试的逻辑不需要知道超时的逻辑。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60576809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档