Wait for a Pressed Key using the Input Function

This method is native and does not require the presence of any external or standard library. The input function presenting the standard Python distribution could serve the purpose. But the function is only limited to the Enter key, i.e., It requires the Enter key to be pressed for it to return. The following example demonstrates the working:

Example:

Now the code, upon execution, halts the execution of the program and waits for the Enter keypress. If any other key is pressed, the input function stores it. Only upon the Enter keypress does the function return with the inputted data. If any other key is pressed, such as an alphabet, number, symbol, etc., the function won’t return. The next method of halting the program execution takes care of this drawback.

Python3




# The argument to the function may be any descriptive text
input("Press the Enter key to continue: ")


Output:

 

Make Python Wait For a Pressed Key

Halting the execution until the occurrence of an event is a very common requirement in prompt-based programs. In earlier times, the presence of functions such as getch in C/C++ was almost necessary for the code to make the console stay up to display the output. Now such shortcomings of the compiler have been dealt with, and now such functions serve a specific purpose and are utilized for a specific use case. In this article, we will learn how to make a Python script wait for a pressed key. The methods that will be discussed are as follows:

  • Using input function
  • Using system function

Similar Reads

Wait for a Pressed Key using the Input Function

This method is native and does not require the presence of any external or standard library. The input function presenting the standard Python distribution could serve the purpose. But the function is only limited to the Enter key, i.e., It requires the Enter key to be pressed for it to return. The following example demonstrates the working:...

Wait for a Pressed Key using the System Function

...