How to Sleep in Python: Simple Guide with Examples
In Python, you can pause your program using the
sleep function from the time module. Just import time and call time.sleep(seconds) where seconds is the number of seconds to pause.Syntax
The sleep function is part of the time module. You first import the module, then call time.sleep(seconds).
- time: The module that contains the sleep function.
- sleep(seconds): Pauses the program for the given number of seconds. It accepts floats for fractions of a second.
python
import time time.sleep(2) # Pauses the program for 2 seconds
Example
This example shows how to print a message, pause for 3 seconds, then print another message.
python
import time print("Start sleeping...") time.sleep(3) print("3 seconds passed!")
Output
Start sleeping...
3 seconds passed!
Common Pitfalls
One common mistake is forgetting to import the time module before using sleep. Another is passing a negative number or a non-numeric value, which will cause an error.
Also, sleep pauses the entire program, so it should be used carefully in programs that need to stay responsive.
python
import time # Wrong: forgetting to import time # sleep(1) # NameError: name 'sleep' is not defined # Right way: time.sleep(1) # Pauses for 1 second
Quick Reference
Here is a quick summary of how to use sleep in Python:
| Usage | Description |
|---|---|
| import time | Import the time module to access sleep |
| time.sleep(5) | Pause program for 5 seconds |
| time.sleep(0.5) | Pause program for half a second |
| time.sleep(-1) | Raises ValueError (negative time not allowed) |
| sleep(1) | Raises NameError if time module not imported |
Key Takeaways
Use time.sleep(seconds) to pause your Python program.
Always import the time module before calling sleep.
Sleep accepts float values for fractional seconds.
Avoid negative or non-numeric values to prevent errors.
Sleep pauses the whole program, so use it wisely.