2016-08-30 351 views
0

我想在我的代码的函数内运行一个计时器。我需要在用户开始键入之前稍微启动计时器,然后在用户正确输入字母时停止计时器。 这里是我的代码:如何在python中的另一个def函数中运行一个def函数?

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

您需要实现多线程。 –

+0

那是什么? def功能? – Student

+3

记录时间可能会更简单,提示用户开始输入,然后当他们按回车键时,“输入”调用返回,记录结束时间。所花费的时间将是结束减去开始。 – FamousJameous

回答

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

这是我的高分: 现在开始输入:abcdefghijklmnopqrstuvwxyz 干得好,那花了你0.3355秒。这就是我可以多快地点击粘贴和输入;) –

+0

啊,你在python2上,我会为你编辑我的代码。 –

+0

我正在使用python 3.5.1,现在就开始工作。感谢您的帮助 – Student

2

想想carefuly有关,你是董

  1. 你问一个用户输入的字符串
  2. 虽然timer等于True,你睡一秒,增加计数。在此循环中,您不会更改timer

显然,一旦用户停止输入字母并按下回车键,就会启动无限循环。因此,似乎没有发生。

正如其他答案建议,最好的解决方案是在提示用户输入字母并将其与完成之后的时间进行比较之前节省时间。

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) 
相关问题