如何在python中的不同def函数内运行一个def函数?

时间:2016-08-30 15:24:31

标签: python function time timer

我试图在我的代码函数中运行一个计时器。我需要在用户开始输入之前稍微启动计时器,然后在用户正确输入字母表时停止计时器。 这是我的代码:

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: ")

问题在于它不会让我输入字母表。在此代码的先前尝试(我没有)我已经能够输入字母表,但计时器将无法工作。任何帮助表示赞赏

3 个答案:

答案 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)

仔细想想你是谁

  1. 您要求输入用户输入的字符串
  2. timer等于True时,您会睡眠一秒钟并增加计数。在此循环中,您不会更改timer
  3. 显然,一旦用户停止输入字母表并按下回车键,您就会开始无限循环。因此,似乎没有任何事情发生。

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

答案 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)