Timer in Python

Asked

Viewed 34,998 times

5

I’m trying to make a timer that, after 10 seconds, prints a string.

I tried to use the time.sleep() and it didn’t work.

Example:

def tempo():
    #passados 10 segundos
    print "olá"
  • I did a much better way: from time import Leep def espera(tempo): Leep(tempo)

  • And how does this help to solve the problem that is in the question? Where does the print("olá") would be used with this? What is the reason that would lead someone to use their function espere instead of using sleep directly?

3 answers

7


Use the method time.sleep().

import time

def tempo():
    time.sleep(10)    
    print "Ola"

To make a stopwatch and print the number on the same line:

import time, sys

for i in range(0, 10):
    sys.stdout.write("\r{}".format(i))
    sys.stdout.flush()
    time.sleep(1)

print ("\nFim")

See demonstração

  • Thank you ;) I probably forgot to import time.

  • And it is possible to make a stopwatch, that is, to count the time in a single line?

  • but that the count should replace the number that is there before:

  • But keep adding numbers to the count

-2

I think a smaller form would be:

from  time import sleep 

for contagem in range(0,10):
    sleep(1)

print('Olá!')
  • 3

    I don’t understand why sleep 10x would be more "reduced" than calling just one.

-4

From time import Sleep

Msg = str(imput("type a sentence:")) Times = int(imput("how often do you want to execute that sentence:")

While Vezes:

Print(Msg)

Sleep(10)

print("end of execution")

  • 4

    Caution. The function imput does not exist in Python, the correct is input; her return is always a string, so call str is to insert redundancy into the code; as you do not modify the value of Vezes, if any value other than 0 is entered it will cause an infinite loop; From should be from; While should be while, Print should be print; Sleep should be sleep

Browser other questions tagged

You are not signed in. Login or sign up in order to post.