Multiple Lines User Input in Python

Multiple Lines User Input in Python

Getting multiple lines of user input in Python is a common task. There are two main ways to do this: using a while loop or using the sys.stdin.read() method. Which method you choose to use depends on your specific needs.

There are two common ways to get multiple lines of user input in Python:

Method 1: Using a while loop

def get_multiline_input():
  lines = []
  while True:
    line = input()
    if line:
      lines.append(line)
    else:
      breakreturn '\n'.join(lines)


# Example usage:

multiline_input = get_multiline_input()

print(multiline_input)

This code will keep prompting the user for input until they press Enter on an empty line. All of the user's input will be stored in a list, and then joined together with newline characters to form a single string.

Method 2: Using the sys.stdin.read() method

import sys


def get_multiline_input():return sys.stdin.read()


# Example usage:

multiline_input = get_multiline_input()

print(multiline_input)

This code will read all of the input from the user until they reach the end of file (EOF). EOF is usually indicated by pressing Ctrl+D.

Which method you choose to use depends on your specific needs. If you need to know when the user has finished entering input, then you should use the first method. If you need to read all of the user's input at once, then you can use the second method.

Example:

The following example shows how to use the first method to get multiple lines of user input and then print it back to the user:

def get_multiline_input():
  lines = []
  while True:
    line = input()
    if line:
      lines.append(line)
    else:
      breakreturn '\n'.join(lines)


def print_multiline_input(multiline_input):
  print(multiline_input)


# Example usage:

multiline_input = get_multiline_input()

print_multiline_input(multiline_input)

Output:

This is a multiline input.
This is the second line.

Conclusion

Getting multiple lines of user input in Python is a common task. There are two main ways to do this: using a while loop or using the sys.stdin.read() method. Which method you choose to use depends on your specific needs.

# Details

Published on January 31, 2024 2 min read

Python