Re-write this Python code that counts down from 5 to 0 with 1 second in between each number in a more efficient way:

import time
seconds = 5
print("Remaining time: " + str(seconds))
seconds = seconds - 1
time.sleep(1)
print("Remaining time: " + str(seconds))
seconds = seconds - 1
time.sleep(1)
print("Remaining time: " + str(seconds))
seconds = seconds - 1
time.sleep(1)
print("Remaining time: " + str(seconds))
seconds = seconds - 1
time.sleep(1)
print("Remaining time: " + str(seconds))
seconds = seconds - 1
time.sleep(1)
print("Remaining time: " + str(seconds))

this is not working

for seconds in range(5, -1, -1):
print("Remaining time: " + str(seconds))
time.sleep(1)

1 answer

You can simplify the countdown code using a for loop, which will make it more efficient and concise. Your second attempt is almost correct, but it lacks proper indentation. Here's the corrected and optimized version of your countdown code:

import time

for seconds in range(5, -1, -1):
    print("Remaining time: " + str(seconds))
    time.sleep(1)

In this version:

  • The for loop iterates from 5 down to 0 (inclusive).
  • time.sleep(1) is called after each print statement to create a one-second pause between messages.
  • The code is cleaner and more efficient since it eliminates repetitive code.