Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 best way to read unknown multi line input

What is the best way in Python 3 to read in multi-line user input when the amount of input is unknown? The multi-line input will be separated by Enter

when I try using

while True:
    line = input()
    if line:
          print(line)
    else:
          break

I receive an EOFError

Then if I change it to a try-catch block

while True:
    line = input()
    try:
          print(line)
    except EOFError:
          break

I still get the EOFError.

like image 646
Mazzone Avatar asked Oct 05 '17 18:10

Mazzone


People also ask

How do you read multiple lines of input in python?

1st Method: inputlist = [] while True: try: line = input() except EOFError: break inputlist. append(line) 2nd Method import sys inputlist = sys. stdin. readlines() print(inputlist) This will take multi-line input however you need to terminate the input (ctrl+d or ctrl+z).

How do you check for different inputs in Python?

Use string isdigit() method to check user input is number or string. Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work. So, It is better to use the first approach.

How do you print multiple lines in Python?

"\n" can be used for a new line character, or if you are printing the same thing multiple times then a for loop should be used.


1 Answers

The EOFError occurs when you call input(), not when you test it, nor when you print it. So that means you should put input() in a try clause:

try:
    line = input()
    print(line)
except EOFError:
    break

That being said, if input reads from the standard input channel, you can use it as an iterable:

import sys

for line in sys.stdin:
    print(line, end='')

Since every line now ends with the new line character '\n', we can use end='' in the print function, to prevent print a new line twice (once from the string, once from the print function).

I think the last version is more elegant, since it almost syntactically says that you iterate over the stdin and processes the lines individually.

like image 87
Willem Van Onsem Avatar answered Oct 13 '22 00:10

Willem Van Onsem