我试图在我的代码函数中运行一个计时器。我需要在用户开始输入之前稍微启动计时器,然后在用户正确输入字母表时停止计时器。 这是我的代码:
import time
timec = 0
timer = False
print("Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed")
timer = True
attempt = input("The timer has started!\nType here: ")
while timer == True:
time.sleep(1)
timec = timec +1
if attempt == "abcdefghijklmnopqrstuvwxyz":
timer = False
print("you completed the alphabet correctly in", timec,"seconds!")
else:
print("There was a mistake! \nTry again: ")
问题在于它不会让我输入字母表。在此代码的先前尝试(我没有)我已经能够输入字母表,但计时器将无法工作。任何帮助表示赞赏
答案 0 :(得分:2)
import time
start = time.time()
attempt = input("Start typing now: ")
finish = time.time()
if attempt == "abcdefghijklmnopqrstuvwxyz":
print "Well done, that took you %s seconds.", round(finish-start, 4)
else:
print "Sorry, there where errors."
答案 1 :(得分:2)
仔细想想你是谁
timer
等于True
时,您会睡眠一秒钟并增加计数。在此循环中,您不会更改timer
。显然,一旦用户停止输入字母表并按下回车键,您就会开始无限循环。因此,似乎没有任何事情发生。
正如其他答案所示,最佳解决方案是在提示用户输入字母表之前节省时间,并将其与完成后的时间进行比较。
答案 2 :(得分:0)
import datetime
alphabet = 'abcdefghijklmnopqrstuvwxyz'
print('Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed"')
init_time = datetime.datetime.now()
success_time = None
while True:
user_input = input('The timer has started!\nType here: ')
if user_input == alphabet:
success_time = datetime.datetime.now() - init_time
break
else:
continue
print('you did it in %s' % success_time)