嗨,我刚刚开始使用Python,我想创建一个功能类似于考勤的程序。当输入收到“礼物”时,它会将值添加到列表中,但是当用户在一段时间内未能输入任何内容时,不会向列表中添加任何内容,然后将再次进行另一个输入。
这就是我现在所在的地方。我不知道为什么计时器在满足条件后不会停止,也不知道为什么最终打印总是具有所有 3 个值。
from threading import Timer
print(f"Class Attendance")
Class = ["Student 1 ", "Student 2 ", "Student 3 "]
Attendance = []
for s in Class:
timeout = 5
t = Timer(timeout, print, [f'Absent'])
t.start()
q = str(input(s))
if q == "present" or "present po":
Attendance.append(s)
t.cancel
print(f"Present Students: {Attendance}")
这可能不一定是您想要的答案,但是很难用计时器实现
input()
,因为它是一个阻塞函数。这意味着在程序继续之前需要输入。但是,其他库提供非阻塞替代方案。
如果您拥有一台 Windows 计算机,此解决方案应该可以为您提供所需的结果。
首先,
pip install msvcrt
msvcrt 库检测键盘输入。虽然
msvcrt.kbhit()
只需按一次键,但它是非阻塞的,因此下面的代码将按预期工作。
import msvcrt
import time
if __name__ == "__main__":
print("Class Attendance")
students = ["Student 1", "Student 2", "Student 3"]
attendance = []
for stu in students:
print(f"{stu}:", end=" ", flush=True)
timeout = 5
start_time = time.time()
while time.time() - start_time < timeout: # timer
if msvcrt.kbhit(): # non blocking
if ord(msvcrt.getch()) == 112: # p ascii value
attendance.append(stu)
print("present")
break
else: # any other keystroke
print("absent")
break
else: # if keyboard not hit
print("absent")
print(f"Present Students: {attendance}")
代码将检测字符p(当前)是否被按下。如果按下 p,则学生在场。同样,如果未按下小写 p 或按下除小写 p 之外的其他键,则该学生将被计为缺勤。我希望这对您有帮助。