How to Add Delay in Python: Simple Guide with Examples
To add a delay in Python, use the
time.sleep(seconds) function from the time module, where seconds is the number of seconds to pause. This stops the program for the specified time before continuing.Syntax
The basic syntax to add delay in Python is:
import time: Imports the time module which contains the sleep function.time.sleep(seconds): Pauses the program for the given number of seconds (can be a float for fractions of a second).
python
import time time.sleep(2) # pauses the program for 2 seconds
Example
This example shows how to print messages with a 1-second delay between them using time.sleep().
python
import time print("Start") time.sleep(1) # wait 1 second print("1 second later") time.sleep(2) # wait 2 seconds print("3 seconds later")
Output
Start
1 second later
3 seconds later
Common Pitfalls
Common mistakes when adding delay include:
- Forgetting to import the
timemodule before usingsleep(). - Using
sleepwithout parentheses, which does nothing. - Passing a negative number to
sleep(), which raises an error.
python
import time # Wrong: missing parentheses # time.sleep # does nothing # Correct: time.sleep(1) # pauses for 1 second # Wrong: negative delay # time.sleep(-1) # raises ValueError
Quick Reference
Remember these tips when adding delay in Python:
- Use
time.sleep(seconds)with seconds as a float or int. - Import
timemodule first. - Delays can be fractional, e.g.,
time.sleep(0.5)for half a second. - Delays pause the whole program execution.
Key Takeaways
Use time.sleep(seconds) to pause Python program execution for a set time.
Always import the time module before calling sleep().
Seconds can be a decimal for fractional delays.
Avoid negative values in sleep() to prevent errors.
Sleep pauses the entire program, so use it wisely.