Home > Backend Development > Python Tutorial > How to Capture Multiline User Input in Python?

How to Capture Multiline User Input in Python?

Barbara Streisand
Release: 2024-11-19 14:34:02
Original
818 people have browsed it

How to Capture Multiline User Input in Python?

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template