[英]How do I run one def function inside of a different def function in python?
I'm trying to run a timer inside of a function of my code. 我正在尝试在代码功能内运行计时器。 I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly.
我需要在用户开始输入之前先启动计时器,然后在用户正确输入字母后停止计时器。 Here is my code:
这是我的代码:
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: ")
The issue is that it will not let me enter the alphabet. 问题是它不会让我输入字母。 In previous attempts of this code (Which I do not have) i have been able to enter the alphabet, but the timer would not work.
在此代码的先前尝试中(我没有),我已经能够输入字母,但是计时器不起作用。 Any help is appreciated
任何帮助表示赞赏
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."
Think carefuly about that you are dong 慎重考虑你是董
timer
equals True
, you sleep for one second and increase the count. timer
等于True
,您睡眠一秒钟并增加计数。 In this loop, you do not change the timer
. timer
。 Obviously, once user stopped entering the alphabet and pressed enter, you start an infinite loop. 显然,一旦用户停止输入字母并按Enter,就开始无限循环。 Thus, nothing seems to happen.
因此,似乎什么也没发生。
As other answers suggested, the best solution would be to save the time right before prompting user to enter the alphabet and compare it to the time after he finished. 正如其他答案所建议的那样,最好的解决方案是在提示用户输入字母之前将时间保存下来,并将其与完成后的时间进行比较。
you could do something like: 您可以执行以下操作:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.