How to Pause in Python

In Python programming language, there may be situations when your program needs to wait for some time before it proceeds further.

This could be to simulate a delay in execution or to allow the program to wait until a certain condition is met. Python provides several ways to pause, or sleep, code execution, and in this tutorial we will show you different ways to achieve this.

Using the Sleep Function

The simplest way to pause your Python script is by using time.sleep() function, which is a part of the time module. This function causes your program to sleep, or delay its execution, for a specified number of seconds. Here’s how it works:

The time.sleep() function can accept any floating-point number as its argument, which means you can specify delays as low as a millisecond.

Using a Timer Object

Another way to pause a Python script is to use a timer object in the threading module, the threading.Timer() Class. This class is used to create a countdown timer that starts after an interval and executes a function once finished. Below is an example:

Be aware that unlike time.sleep(), threading.Timer() doesn’t block the program execution. It simply starts the timer and then allows program execution to continue.

Scheduling a Function

You can also pause the program execution by scheduling a function to be called after a certain interval. You can achieve this using the sched module in Python.

The sched.scheduler class can process events not only in real-time but in virtual time too!

Here’s The Full Code


Pausing a Python script is a useful tool that can be implemented in a variety of ways. Whether using the time.sleep() function, the threading.Timer() class, or the sched.scheduler() class, each method offers unique benefits and use-cases. Remember to always choose the technique that best fits the needs of your project and makes your code run smoothly.