Keyboard Input in Python
Attempting to read keyboard input can lead to unexpected behavior, as illustrated by the provided Python code. It appears to wait for user input indefinitely without continuing execution.
The issue stems from the different ways Python handles keyboard input depending on the version used.
Python 2.X and Earlier
In Python 2.X and earlier, use the raw_input() function to read a line of text from the user. To convert the input to a numeric value, use int(), as seen below:
<code class="python">nb = raw_input('Choose a number') nb = int(nb) print('Number: %s' % nb)</code>
Python 3.X
In Python 3.X, use the input() function to read keyboard input. It returns a string, so again, use int() for numeric conversion:
<code class="python">nb = input('Choose a number: ') nb = int(nb) print('Number: %s' % nb)</code>
Alternatively, if you want to capture non-numeric input without handling conversion errors, you can simply use input() without int():
<code class="python">nb = input('Enter any input: ') print('Input: %s' % nb)</code>
By following these guidelines, you can successfully read keyboard input in Python, ensuring your code responds as intended.
The above is the detailed content of How to Handle Keyboard Input in Python to Avoid Indefinite Waiting?. For more information, please follow other related articles on the PHP Chinese website!