python


Python sleep() function


The sleep() function is used to suspend the current process for a given number of seconds.
Python consist of many useful module in which one of them is time and the function sleep() lie under this module.

Syntax:
import time
time.sleep(no.of seconds)
Example:

how time.sleep() works

As you can see in above code, firstly we imported module time and then we printed the statement "Hello World!" by using print statement. After that we used function time.sleep(5) to delay the execution of next statement for 5 seconds and after 5 seconds.

Creating Clock by sleep() function

We can also create a digital clock by using sleep() function.

Example:
import time

while True:
  local_time = time.localtime()
  time_result = time.strftime("%I:%M:%S %p %a", local_time)
  print(time_result, end="", flush=True)
  print("\r", end="", flush=True)
  time.sleep(1)

In the above code, we created a digital clock which shows us time and week-day as well. We used an infinite while loop in above code and for creating a clock we used time.strftime() function in which we gave the argument for time and day as well.After this we used time.sleep() for 1 second to show the clock.