Search code examples
pythontimerangesleepcountdown

Is there a better way to display a simple countdown or is this good enough?


Today I learned the time.sleep function and tried to create a countdown from it. At first I had made it very complicated (see python comment) and then I found a much better, simpler method. Now I'm thirsty for knowledge and I'm wondering if you can recommend a better method? Maybe my range variant is completely sufficient. Thanks in advance!

import time

def wait_2sec():
    time.sleep(2)

def wait_1sec():
    time.sleep(1)

print("The countdown starts in a few seconds...")
wait_2sec()


# the new method I tried
for i in range(10, -1, -1):
    print(i)
    wait_1sec()
    if i == 0:
        wait_1sec()
        print("--- FINISH ---")


# the first method I tried
# print("---- COUNTDOWN STARTS! ----")
# print("10")
# wait_1sec()
# print("9")
# wait_1sec()
# print("8")
# wait_1sec()
# print("7")
# wait_1sec()
# print("6")
# wait_1sec()
# print("5")
# wait_1sec()
# print("4")
# wait_1sec()
# print("3")
# wait_1sec()
# print("2")
# wait_1sec()
# print("1")
# wait_1sec()
# print("* FINISH *")
# wait_2sec()

Solution

  • The most obvious thing would be to use one function with an argument like this:

    import time
    
    def wait_nsec(n):
        time.sleep(n)
    
    
    print("The countdown starts in a few seconds...")
    wait_nsec(2)
    
    
    # the new method I tried
    for i in range(10, -1, -1):
        print(i)
        wait_nsec(1)
        if i == 0:
            wait_nsec(1)
            print("--- FINISH ---")
    

    or completely remove the function and use a while loop for the countdown.

    import time
    
    print("The countdown starts in a few seconds...")
    time.sleep(1)
    
    i = 10
    while i >= 0:
        print(i)
        time.sleep(1)
        i = i-1
    print('---finish---')