2016-08-30 111 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)