How to get multiline input from user with Python?

Sometimes, we want to get multiline input from user with Python

In this article, we’ll look at how to get multiline input from user with Python.

How to get multiline input from user with Python?

To get multiline input from user with Python, we can call input in an infinite loop.

For instance, we write

contents = []
while True:
    try:
        line = input()
    except EOFError:
        break
    contents.append(line)

to call input in the infinite while loop to get its input value.

Then we catch the EOFError and stop the look with break if there’s an EOFError raised.

The error will be raised if Ctrl-D or Ctrl-Z is pressed.

Outside the try-except statement, we call contents.append to append the entered line into the contents list.

Conclusion

To get multiline input from user with Python, we can call input in an infinite loop.