In Python, you can create a time delay using the time.sleep() function from the built-in time module. This function pauses the program for a specified number of seconds.
Example:
Python Copy code
import time
print(“Start”)
time.sleep(5) # Pause for 5 seconds
print(“End after 5 seconds”)
Key Points:
Syntax:
python Copy code
time.sleep(seconds)
The seconds parameter can be an integer or a floating-point number for fractional seconds.
Fractional Delays:
python Copy code
time.sleep(0.5) # Pause for half a second
Use Cases:
Delaying execution for a specific amount of time.
Creating pauses between loops or actions in automation scripts.
Simulating real-time events or loading.
Example with a Loop:
python
Copy code
import time
for i in range(5):
print(f”Step {i + 1}”)
time.sleep(2) # Pause for 2 seconds between iterations
Important Notes:
time.sleep() pauses the entire program execution, including all threads, so it’s not suitable for tasks that require responsiveness or concurrency.
If you need non-blocking delays (e.g., in a GUI or asynchronous program), consider using asynchronous libraries like asyncio instead.