๐Python time.sleep() Function
Python time.sleep() Function: The Python time.sleep() function is a valuable tool that allows developers to pause code execution for a specified number of seconds. This function is part of the time module and is particularly useful when you need to wait for a process to complete, manage delays in code execution, or simulate waiting periods.
๐What is Python time.sleep()?
Python time.sleep() Function: The time.sleep() function delays the execution of the program by pausing it for the number of seconds specified. This method is essential in scenarios like file uploads, waiting for data to load, or introducing controlled delays in automation scripts.
๐Python time.sleep() Function Syntax
import time
time.sleep(seconds)
๐Python time.sleep() Function Parameters:
- seconds: The number of seconds to pause the code execution.
๐Return Value:
- The function does not return any value but introduces a delay in the program flow.
๐Example 1: Using time.sleep() in Python
import time
print(“Starting process…”)
time.sleep(5)
print(“This message appears after a 5-second delay.”)
๐Output:
Starting process…
(This appears after 5 seconds)
This message appears after a 5-second delay.
๐Example 2: Adding Delay in a Function Execution
To delay the execution of a function, you can call time.sleep() before invoking the function.
import time
def display():
print(“Hello from Python tutorials!”)
time.sleep(3)
display()
๐Output:
(This appears after 3 seconds)
Hello from Python tutorials!
๐Example 3: Adding Delay in a Loop
To introduce a delay between loop iterations:
import time
message = “Python Code”
for char in message:
print(char)
time.sleep(1)
๐Output:
P
y
t
h
o
n
C
o
d
e
๐Other Methods to Add Delay in Python
Besides time.sleep(), Python offers additional methods to introduce delays:
๐1. Using asyncio.sleep() (Python 3.4+ Required)
import asyncio
async def display():
await asyncio.sleep(5)
print(“Hello from Asyncio!”)
asyncio.run(display())
๐Output:
(This appears after 5 seconds)
Hello from Asyncio!
๐2. Using Event().wait() (Threading Module)
from threading import Event
def display():
print(“Message after delay”)
Event().wait(4) # Pause for 4 seconds
display()
๐Output:
(This appears after 4 seconds)
Message after delay
๐3. Using Timer() (Threading Module)
from threading import Timer
def display():
print(“Timer executed this message!”)
t = Timer(5, display) # Delay for 5 seconds
t.start()
๐Output:
(This appears after 5 seconds)
Timer executed this message!
๐Summary
The time.sleep() function is an effective way to introduce delays in Python code. Whether you are handling file uploads, waiting for external processes, or simply adding a pause between actions, time.sleep() is a versatile tool. For advanced delay management, consider using asyncio.sleep(), Event().wait(), or Timer() for optimal performance in your projects.
