Waiting for User Input with Python
Often in programming, you may encounter situations where you want your script to pause and wait for the user to press a key before continuing. How can you achieve this in Python?
Python 3: Using input()
In Python 3, you can use the input() function. This function takes a prompt message as an argument and displays it to the user. The script then halts and waits for the user to press any key. To capture the pressed key, you can assign the returned value to a variable. For example:
user_input = input("Press any key to continue...")
Python 2: Using raw_input()
Prior to Python 3, raw_input() was used for this purpose. However, in Python 3, raw_input() is no longer available and has been replaced by input().
Capturing Specific Keys
The methods above only wait for the user to press enter. To capture specific keys, such as arrows or function keys, you can use alternative approaches:
Windows (msvcrt module):
On Windows, you can use the msvcrt module to capture keystrokes. The getch() function waits for a key press without displaying the character.
import msvcrt as m def wait(): m.getch()
Platform-Independent Approach (getch):
You can also use a cross-platform library like getch to capture keystrokes while suppressing their display. Install it using pip install getch.
from getch import getch def wait(): getch()
These methods provide a more comprehensive solution for waiting for user input, including specific keys, across different platforms.
The above is the detailed content of How to Make a Python Script Wait for User Input?. For more information, please follow other related articles on the PHP Chinese website!