Input Multiple Lines in Python

Input Multiple Lines in Python

  1. Using the raw_input() Function to Get Multi-Line Input From a User in Python
  2. Using sys.stdin.read() Function to Get Multiline Input From a User in Python

The program sometimes may require an input that is vastly longer than the default single line input. This tutorial demonstrates the various ways available to get multi-line input from a user in Python.

Using the raw_input() Function to Get Multi-Line Input From a User in Python

The raw_input() function can be utilized to take in user input from the user in Python 2. However, the use of this function alone does not implement the task at hand. Let us move on to show how to implement this function in the correct way in Python.

The following code uses the raw_input() function to get multi-line input from a user in Python.

x = '' # The string is declared
for line in iter(raw_input, x):
    pass

Further, after the introduction of Python 3, the raw_input() function became obsolete and was replaced by the new input() function.

Therefore, if using Python 3 or higher, we can utilize the input() function instead of the raw_input() function.

The above code can be simply tweaked in order to make it usable in Python 3.

x = '' # The string is declared
for line in iter(input, x):
    pass

Using sys.stdin.read() Function to Get Multiline Input From a User in Python

The sys module can be imported to the Python code and is mainly utilized for maintaining and manipulating the Python runtime environment.

The sys.stdin.read() function is one such function that is a part of the sys module and can be utilized to take multi-line input from the user in both Python 2 and Python 3.

import sys
s = sys.stdin.read()
print(s)

The Python console can be cleared after taking the input and displayed on the screen using the print command.

Related Article - Python Input

  • Read User Input as Integers in Python
  • Detect Keypress in Python
  • Python Get User Input With Timeout
  • Take Input of Unspecified Length in Python
  • Simulate Keyboard Inputs in Python