Accessing Multiline User Input in Python
In Python, the input() function reads only the first line of input, precluding the collection of multiline input. This post addresses this limitation, offering an approach to capture multiple lines from user input.
Utilizing an Input Loop
The key to handling multiline input is to utilize a loop that reads input line by line until an end-of-file (EOF) character is encountered. The following code accomplishes this in both Python 3 and 2:
Python 3:
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.") contents = [] while True: try: line = input() except EOFError: break contents.append(line)
Python 2:
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.") contents = [] while True: try: line = raw_input("") except EOFError: break contents.append(line)
In these loops, line represents the input on each line, and it is appended to the contents list. The loop continues until an EOF character is entered (Ctrl-D for Unix-based systems and Ctrl-Z for Windows). The resulting contents list contains all the lines entered by the user.
The above is the detailed content of How to Capture Multiline User Input in Python?. For more information, please follow other related articles on the PHP Chinese website!