Python 如何对测验中提出的每个问题设置计时器?

Python 如何对测验中提出的每个问题设置计时器?,python,Python,我试图创建一个测验,其中一个标准是限制测验中每个问题的可用时间。我查阅了一些教程,但有些教程需要输入x秒,计时器才能启动,而另一些教程看起来更像秒表 我想知道我该怎么做,就像一个后台计时器,当问题打印出来时,它会滴答作响,如果30秒的时间已经结束,它会跳转到下一个问题?我对计时器功能一无所知,甚至在尝试将它们实现到代码中时都遇到了问题。有人能给我一些建议,这样我就可以在实现一个工作计时器方面取得进一步的进展吗 谢谢大家! 以下编辑部分: 我要在编码中实现的计时器: import time imp

我试图创建一个测验,其中一个标准是限制测验中每个问题的可用时间。我查阅了一些教程,但有些教程需要输入x秒,计时器才能启动,而另一些教程看起来更像秒表

我想知道我该怎么做,就像一个后台计时器,当问题打印出来时,它会滴答作响,如果30秒的时间已经结束,它会跳转到下一个问题?我对计时器功能一无所知,甚至在尝试将它们实现到代码中时都遇到了问题。有人能给我一些建议,这样我就可以在实现一个工作计时器方面取得进一步的进展吗

谢谢大家!

以下编辑部分: 我要在编码中实现的计时器:

import time
import threading

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

a_timer = threading.Timer(10.0, atimer)
a_timer.start()
print("")
这就是我试图实现计时器的全部代码。 我注意到,当我试图定义qtimer以仅打印1或2行语句时,计时器工作,但我希望计时器停止并转到第二个问题或停止,让用户再次尝试重试该问题,因此我尝试在定义后附加一组代码,但它不起作用。我知道我很可能在这里做错了什么,因为我不太熟悉时间或线程函数。有解决办法吗

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) + ".")
def qtimer():
打印(“很抱歉,这个问题你的时间到了。”)
打印(“如果愿意,您可以进行另一次尝试,并分配减少的分数。”)
response1=input(“键入‘Yes’进行另一次尝试,其他任何要跳过的内容:”)
如果响应1==“是”:
Answ=input(“这次您选择哪个选项?:”)
Answ=int(Answ)
如果可能[Answ-1]==qaItem.corrAnsw:
打印(“你的答案是正确的。”)
corr+=1
标记+=0.5*qaItem.diff
其他:
打印(“你的答案错了。”)
打印(“正确答案是:”+qaItem.corrAnsw)
打印(“说明:+qaItem.expl”)
打印(“”)
其他:
打印(“正确答案是:”+qaItem.corrAnsw)
打印(“说明:+qaItem.expl”)
打印(“”)
A类:
定义初始(自我、问题、正确答案、其他答案、难度、解释):
self.question=问题
self.corrAnsw=正确答案
self.otherAnsw=其他答案
self.diff=困难
self.expl=解释
qaList=[A(“什么是新冠病毒-19?”,“2019年冠状病毒病”[“武汉病毒”,“我不明白…”,““冠状病毒病v19”]”,1,“解释1”),
A(“什么描述了新冠病毒-19?”、“一种疾病”[“一种病毒”、“一种寄生虫”、“一种噬菌体”]、1、“解释2”),
A(“是什么导致了新冠病毒-19?”,“SARS-CoV-2”,[“冠状病毒”、“拟态病毒”、“Rubeola病毒”],“解释3”),
A(“以下哪项用于新冠病毒-19治疗?”、“洛匹那韦/利托那韦”、“咪达唑仑/三唑仑”、“胺碘酮”、“苯妥英钠”]、2、“解释4”),
A(“以下哪种受体被冠状病毒-19用于感染人类细胞?”,“ACE-2受体”,[“ApoE4受体”;“TCR受体”;“CD28受体”],“解释5”)]
corr=0
分数=0
随机洗牌(qaList)
对于qaList中的qaItem:
q_timer=threading.timer(5.0,qtimer)
q_timer.start()
打印(项目.问题)
打印(“可能的答案是:”)
可能=qaItem.otherAnsw+[qaItem.corrAnsw]
随机。随机(可能)
计数=0
当计数4或Answ<1时:
打印(“该数字与任何答案都不对应。请输入答案的数字:”)
Answ=输入()
Answ=int(Answ)
如果可能[Answ-1]==qaItem.corrAnsw:
打印(“你的答案是正确的。”)
corr+=1
标记+=1*qaItem.diff
其他:
打印(“你的答案错了。”)
response=input(“您想再试一次吗?如果是,输入‘Yes’再试一次,如果不只是输入任何内容!”)
如果响应=“是”:
Answ=input(“这次您选择哪个选项?:”)
Answ=int(Answ)
如果可能[Answ-1]==qaItem.corrAnsw:
打印(“你的答案是正确的。”)
corr+=1
标记+=0.5*qaItem.diff
其他:
打印(“你的答案错了。”)
打印(“正确答案是:”+qaItem.corrAnsw)
打印(“说明:+qaItem.expl”)
打印(“”)
其他:
打印(“正确答案是:”+qaItem.corrAnsw)
打印(“说明:+qaItem.expl”)
打印(“”)
打印(“您正确回答了”+str(corr)+“+str(len(qaList))+“问题”。)
打印(“您的总分为“+str(分数)+”)

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

print("Please enter the number of your answer:")
Answ = input() 
计时器线程可以设置一个全局标志,告诉主线程在计时器代码中将接收到的输入视为
response1
,还可以设置一个标志,告诉计时器收到了应答,以此类推,这很快就会变得相当复杂

因此,不要试图通过计时器和主线程之间的通信来绕过对
input
的阻塞调用,而是以非阻塞输入为例,如果时间到了,就提前停止循环

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')
def timed_输入(消息,超时=10):
kb=KBHit()
打印(msg)
结束时间=time.time()+超时
警告时间=5
重新