Count down before a restart
easyLoops
Problem statement
Before restarting a service, a script shows a short countdown. Print the numbers 5 down to 1, one per line, then print Restarting now.
Examples
Example 1
Input: No input.
Output: 5
4
3
2
1
Restarting now
Hints
Approach
Optimal
range(start, stop, step) accepts a third value that sets how much to add each time. With a step of -1, the numbers go down: range(5, 0, -1) gives 5, 4, 3, 2, 1, again stopping before the stop value 0. The last print is not indented, so it is outside the loop and runs once after the loop finishes. Indentation is how Python decides what repeats and what does not.
Python
for seconds in range(5, 0, -1): print(seconds) print("Restarting now")Follow-up questions
- Add a real one-second pause between numbers with
time.sleep(1).
Frequently asked questions
The final print is indented, so Python treats it as part of the loop. Remove the indentation so it runs once after the loop ends.
Add import time at the top and call time.sleep(1) inside the loop.