简体   繁体   中英

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

  1. You ask for a user-entered string
  2. While timer equals True , you sleep for one second and increase the count. In this loop, you do not change the timer .

Obviously, once user stopped entering the alphabet and pressed enter, you start an infinite loop. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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