繁体   English   中英

如何在python中的另一个def函数中运行一个def函数?

[英]How do I run one def function inside of a different def function in python?

我正在尝试在代码功能内运行计时器。 我需要在用户开始输入之前先启动计时器,然后在用户正确输入字母后停止计时器。 这是我的代码:

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

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

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. timer等于True ,您睡眠一秒钟并增加计数。 在此循环中,您无需更改timer

显然,一旦用户停止输入字母并按Enter,就开始无限循环。 因此,似乎什么也没发生。

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

您可以执行以下操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM