Student
Student

Reputation: 25

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

Upvotes: 0

Views: 88

Answers (3)

Amin Etesamian
Amin Etesamian

Reputation: 3699

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)

Upvotes: 0

Danielle M.
Danielle M.

Reputation: 3682

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."

Upvotes: 2

Dmitry Torba
Dmitry Torba

Reputation: 3214

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.

Upvotes: 2

Related Questions