
👉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.