python
Add delay in code execution python
To add some delay in python code execution, you can use the sleep() function of the time module.
import time
print("Print without delay: ", end="")
print(time.ctime())
time.sleep(4)
print("Print after 4 seconds: ", end="")
print(time.ctime())
To use the sleep() method, we need to import the time python module. We can use time.sleep() after that. As a parameter, it takes the time delay in seconds. In the above code, we are passing 4 seconds as a delay in further program execution.
Use case of adding delay in program execution
There are a lot of python applications that requires some delays in program execution. For example, if you want to run a thread continuously with some delay between each thread execution. Then you can use the sleep() function. Or if you have some heavy tasks performed by the system and you want to delay the next process then you can also use it.
import time
student = {
'name': 'Harold',
'branch': 'IT',
'code': 'p2001'
}
time.sleep(2)
print('Student name is : ', end='')
print(student['name'])
time.sleep(3)
print('Student branch is : ', end='')
print(student['branch'])
time.sleep(2)
print('Student code is : ', end='')
print(student['code'])
Here, We are printing dictionary(student) items with some delay in each of the item prints.
import time
time.sleep(5)
my_list = [10, 20, 30, 40, 50]
print(my_list)
We are adding a delay of 5 seconds before executing the program that prints a python list.
import time
# A list contains multiple names
names = ['John', 'Rick', 'Sara', 'Aarya']
for name in names:
# Add 2 seconds delay
time.sleep(2)
# Print a name every two seconds
print(name)
Here, we have defined a list(names) that contains multiple names. We applying For Loop on it to access its items. Each iteration of for loop will print a name with 2 seconds delay.
Was this helpful?
Similar Posts
- Python Measure the execution time of small bits of Python code with the timeit module
- first python code
- Python code to validate email address using regex
- Calculate the factorial of a number using python code
- Python code examples to flatten a nested dictionary
- Python code to remove falsy values(None, False, [], {}, etc)
- One line code to get the sum of a list in python