Troubleshooting Keyboard Input in Python
When attempting to read user input from the keyboard in Python, users may encounter issues where the program appears to stop after requesting input. This can occur even with basic code.
Original Code:
nb = input('Choose a number') print('Number%s \n' % (nb))
Issue:
Using the code provided, input is halted after the user types a number.
Solution:
The issue lies in the use of input() without any arguments. In Python versions 3 and above, input() accepts a string parameter that prompts the user for input. In the original code, this parameter is omitted, which results in the default prompt ">>>" being used.
In Python 3, the correct usage is:
input('Enter your input:')
Numeric Input Handling:
If you want to obtain a numeric value from the keyboard, consider the following approach:
try: mode = int(input('Input:')) except ValueError: print("Not a number")
This code attempts to convert the user's input to an integer using int(). If the user enters a non-numeric value, a ValueError is raised and the error message "Not a number" is displayed.
Python 2 Considerations:
If using Python version 2, the input() function is not available. Instead, raw_input() should be employed:
raw_input('Enter your input:')
以上是如何解決Python中的鍵盤輸入錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!