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))

1 answer

You can make the code more efficient by using a loop that iterates through the countdown instead of repeating the same lines for each second. Here's a more concise 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 takes care of iterating from 5 to 0, reducing the redundancy in your code significantly. Each iteration prints the remaining time and then sleeps for 1 second before the next iteration.