Python sleep()
The time.sleep() Python method suspends the execution of the current thread for a specified number of seconds. This function temporarily pauses program execution, allowing other processes to run or creating deliberate delays in code execution.
Syntax of time.sleep()
time.sleep(seconds)
Parameters:
seconds: A positive number (integer or float) representing the number of seconds to pause execution. Float values allow for sub-second precision.
Return value:
The time.sleep() method does not return any value (returns None).
Example 1: Basic Sleep Implementation with the time.sleep() Method
This example demonstrates the fundamental usage of time.sleep() to create a simple delay in program execution:
import time# Print message before delayprint("Starting program...")# Pause execution for 3 secondstime.sleep(3)# Print message after delayprint("Program resumed after 3 seconds")
The output of this code is:
Starting program...Program resumed after 3 seconds
The program first prints “Starting program…”, then pauses for exactly 3 seconds, and finally prints the second message.
Example 2: Creating a Timer With Python’s time.sleep()
This example shows how to use time.sleep() to create a countdown timer, demonstrating a practical, real-world application:
import timedef countdown_timer(seconds):"""Creates a countdown timer that displays remaining time"""for i in range(seconds, 0, -1):print(f"Time remaining: {i} seconds")time.sleep(1) # Wait for 1 secondprint("Timer finished!")# Create a 5-second countdowncountdown_timer(5)
The output of this code is:
Time remaining: 5 secondsTime remaining: 4 secondsTime remaining: 3 secondsTime remaining: 2 secondsTime remaining: 1 secondsTimer finished!
This example creates a countdown that updates every second, showing how time.sleep() can be used to control the timing of repeated operations.
Codebyte Example: Automated Data Processing With Delays
This example demonstrates using time.sleep() in a data processing scenario where you need to respect rate limits or simulate processing time:
This example shows how time.sleep() can be used to create controlled delays in automated processes, which is essential when working with external APIs or systems that have rate limiting.
Frequently Asked Questions
1. Can time.sleep() accept decimal values for sub-second delays?
Yes, time.sleep() accepts both integer and float values. For example, time.sleep(0.5) will pause execution for half a second, and time.sleep(0.1) will pause for 100 milliseconds.
2. Does time.sleep() block the entire program?
Yes, time.sleep() blocks the current thread completely. In single-threaded programs, this means the entire program is paused. For non-blocking delays, consider using asyncio.sleep() in asynchronous programs or threading for concurrent operations.
3. What happens if I pass a negative number to time.sleep()?
Passing a negative number to time.sleep() will raise a ValueError. The function only accepts non-negative values.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours