2016-04-08 105 views
-1

比方說:如何超時等待輸入?

import.time 

print('Make a guess: ') 

time.sleep(0.5) 

guess = input() 

if guess == 45: 
    print('Correct') 

我只是想,如果45是用少於4秒這個工作。我怎麼做?

回答

1

你可以做最簡單的事情就是保持花的時間軌道:

import time 

start = time.time() 
guess = input() 
end = time.time() 

if end-start > 4: 
    print('Sorry, you took too long!') 
elif guess == '45': 
    print("Hooray! You're right!") 
else: 
    print('Nope, sorry.') 

注:我也改變45'45',因爲input返回Python3的字符串。如果您使用的是Python2,則應該使用guess = raw_input()