Launch day is coming, and Rocket wants a countdown on the big screen. His first try prints all ten numbers in a flash, and the word Liftoff appears before anyone can blink.
"That was the fastest countdown in history," he says, laughing. "The computer does not know it should wait."
Raven checks her watch. "What do you notice?" she asks. "A real countdown waits one second between numbers. The waiting is part of the job."
Nova taps a small clock icon. "Would you like a hint?" she asks. "Python comes with a module called time. One of its tools pauses your program for as many seconds as you ask."
Rocket adds one new line at the top: import time.
A module is a file of ready-made Python tools. The line import time loads the time module, which comes with Python. After that, time.sleep(1) pauses the program for one second.
Programmers reuse modules all the time instead of writing everything from scratch.
# countdown.py
import time
start = int(input("Countdown from: "))
for n in range(start, 0, -1):
print(n)
time.sleep(1)
print("Liftoff!") With 5, it shows one number each second:
Countdown from: 5 5 4 3 2 1 Liftoff!
Longer countdowns look better as minutes and seconds. This version uses // and % from week 2. The :02d in the f-string shows a whole number with at least two digits, adding a 0 in front if needed.
# launch_clock.py
import time
total = int(input("Countdown seconds: "))
while total > 0:
minutes = total // 60
seconds = total % 60
print(f"{minutes:02d}:{seconds:02d}")
time.sleep(1)
total = total - 1
print("Liftoff!") Countdown seconds: 3 00:03 00:02 00:01 Liftoff!
A loop that grows a string makes a loading bar. Each round prints one more # than the round before, with a short pause.
# loading.py
import time
for step in range(1, 6):
bar = "#" * step + "." * (5 - step)
print(f"[{bar}] {step * 20}%")
time.sleep(0.5)
print("Systems loaded") | Statement | True or false? |
|---|---|
| time.sleep(2) pauses for two seconds. | ? |
| You must import time before using time.sleep. | ? |
| time.sleep(0.5) pauses for five seconds. | ? |
| The time module has to be downloaded from the internet. | ? |
You used your first module and built a real countdown clock. That is a big week of loops. Tomorrow is a Crew Quest.