How to Pause Program in Python

Muhammad Waiz Khan Feb 02, 2024
  1. Pause a Program in Python Using the time.sleep() Method
  2. Pause a Program in Python Using the input() Function
  3. Pause a Program in Python Using the os.system("pause") Method
How to Pause Program in Python

This tutorial will demonstrate the various methods to pause a program in Python.

Pausing the program’s execution or application is used in different scenarios, like when a program needs to input the user. We may also need to pause a program for few seconds to let the user read some important message or instruction before the program proceeds. Pausing a program can also be useful where we need to make sure that the user reads the instruction before choosing the actions he/she wants the program to take.

We can pause the program for some specific time duration or for some input using different ways, which are explained below.

Pause a Program in Python Using the time.sleep() Method

The time.sleep(secs) method suspends the given thread’s execution for the number of seconds provided as secs.

Therefore, if we need to pause the program’s execution, we can do so by providing the time duration in seconds to the time.sleep() method. The below example code demonstrates how to use the time.sleep() method to pause a Python program.

import time

time_duration = 3.5
time.sleep(time_duration)

Pause a Program in Python Using the input() Function

The input() function in Python 3 and raw_input() function in older versions, takes input in form of a line from sys.stdin and returns the input after appending \n to it.

If we want to pause a program to get some input from the user, we can do so using the input() or raw_input() function depending upon the Python version.

Example code (Python 3):

name = input("Please enter your name: ")
print("Name:", name)

Example code (Python 2):

name = raw_input("Please enter your name: ")
print("Name:", name)

We can also use this method to pause the program until the Enter key is pressed. The below example codes demonstrate how to use the raw_input() and input() functions to do so.

Example code (Python 3):

input("Please press the Enter key to proceed")

Example code (Older versions):

raw_input("Please press the Enter key to proceed")

Pause a Program in Python Using the os.system("pause") Method

The os.system("pause") method pauses the program’s execution until the user does not press any key. The below example code demonstrates how to use the os.system("pause") method to pause a Python program.

import os

os.system("pause")
Note
This method only works on Windows and will not work on any other Operating Systems.