🕯️ Magic Note
The time.sleep() function suspends execution of the current thread for the specified number of seconds. It accepts a float, so you can sleep for fractions of a second like 0.5 or 0.1. During the sleep, the program does nothing. It waits. It breathes. Then it continues.
- time.sleep() takes a float argument, seconds with decimal precision
- The loop has no exit condition, it runs until interrupted
- Press Ctrl+C to break the loop and stop execution
- Sleep can be combined with a condition to create timed checks
| Sleep Duration | Use Case |
|---|---|
| time.sleep(0.001) | Very high frequency polling, 1000 times per second |
| time.sleep(0.1) | UI refresh or sensor reading, 10 times per second |
| time.sleep(1) | One second heartbeat, clock ticks |
| time.sleep(60) | Check for updates every minute |
| time.sleep(3600) | Hourly backup or log rotation |
Python
# A simple heartbeat that ticks every second
import time
print(“Heartbeat started. Press Ctrl+C to stop.”)
count = 0
while True:
count += 1
print(f”tick… {count}”)
time.sleep(1)
# Output: tick… 1 (after 1 second) tick… 2 (after 2 seconds) …
Python
# Sleeping for fractions of a second
import time
print(“Counting tenths of seconds:”)
for i in range(5):
print(f”Step {i + 1}”)
time.sleep(0.3)
# Output: Step 1 (0.3s pause) Step 2 (0.3s pause) Step 3 …
Python
# Periodic check with a break condition
import time
elapsed = 0
print(“Waiting for 5 seconds…”)
while elapsed < 5:
print(f”Waiting… {elapsed}s passed”)
time.sleep(1)
elapsed += 1
print(“Done waiting!”)
# Output: Waiting… 0s passed (1s pause) Waiting… 1s passed … until 5
- Forgetting to import the time module, causing a NameError
- Creating an infinite loop without any way to break, making the program unresponsive to normal termination
- Assuming time.sleep() is perfectly precise, operating system scheduling can cause small delays
⚡ Whisper
No hands. No ticks. No visible movement. Yet the pulse continues. One second. Then another. Then another. The clock without hands measures the invisible. Time flows whether you watch it or not. Breath in the rhythm. Stay present.