Question

Use a word processor
Re-write this Python code that counts down from 5 to 0 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))

Answers

GPT-4o mini
Certainly! The code can be made more efficient by using a loop to handle the countdown instead of repeating similar lines of code. Here’s a refactored version:

```python
import time

# Countdown from 5 to 0
for seconds in range(5, -1, -1):
print("Remaining time: " + str(seconds))
time.sleep(1)
```

In this version, we use a `for` loop that iterates from 5 down to 0. The `time.sleep(1)` function is called after each print statement, reducing redundancy and making the code cleaner and easier to maintain.