Wait a while x after each print in Python 2.7.15

1

so far my code is something like:

print "hola"
time.sleep(1)
print "mundo"
time.sleep(1)
if var == 0:
    print "hola"
    time.sleep(1)
    print "persona"
    time.sleep(1)
else:
    pass

and so after each print. The idea is to achieve a "loading time" (that's not the time I use, it's an example.) But the code is too long and, too lazy, it's annoying to put the time.sleep(x) every time even if it's a def tiempo() . My question is if there was any method of being able to make python do it automatically after a specific variable with a time x determined by me

    
asked by Luca Mendez 30.12.2018 в 06:48
source

3 answers

2

Try to make a function that replaces the print and to this put the timer, something like:

def print_x(x):
    print x
    time.sleep(1)

print_x("hola")
print_x("mundo")
if var == 0:
    print_x("hola")
    print_x("persona")
else:
    pass
    
answered by 30.12.2018 / 07:35
source
1

The pass does nothing but avoid an error when putting else: , then you can simply not put anything of that and leave it more compact like this:

def print_x(x):
    print x
    time.sleep(1)

print_x("hola")
print_x("mundo")
if var == 0:
    print_x("hola")
    print_x("persona")
    
answered by 30.12.2018 в 22:42
0

It's like making your own logging system, you can customize everything you want by using functions or objects. In this case I used the practice of the dictionary.

from time import sleep

def print_delay(message, default_delay=1, message_category=None):

    time_opts = {
        'suspenso': 5, 
        'mucho_suspenso': 10
    }

    delay =  time_opts.get(message_category, default_delay)

    sleep(delay)
    print(message)

def main():
    print_delay('Mensaje 1', message_category='suspenso')        #Estos van a tardar 5
    print_delay('Mensaje 2', message_category='mucho_suspenso')  #y 10 segundos respectivamente
    print_delay('Mensaje 3', default_delay=2)
    print_delay('Mensaje 4')


if __name__ == '__main__':
    main()

Then, your records function can be sent to call with a time related by a name (such as the case of "suspense") or by a number, with a default value, in the default delay

    
answered by 31.12.2018 в 08:32