pythonpython-2.7python-3.xinputraw-input

How to take multiple multiline input variables in Python?


Is it possible to take multiple newline inputs into multiple variables & declare them as int all at once?

To explain further what I am trying to accomplish, I know this is how we take space separated input using map:

>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5

Is there an equivalent for a newline? Something like:

a, b = map(int, input().split("\n"))

Rephrasing: I am trying to take multiple integer inputs, from multiple lines at once.


Solution

  • As others have said it; I don't think you can do it with input().

    But you can do it like this:

    import sys
    numbers = [int(x) for x in sys.stdin.read().split()]
    

    Remeber that you can finish your entry by pressing Ctrl+D, then you have a list of numbers, you can print them like this (just to check if it works):

    for num in numbers:
        print(num)
    

    Edit: for example, you can use an entry like this (one number in each line):

    1
    543
    9583
    0
    3
    

    And the result will be: numbers = [1, 543, 9583, 0, 3]

    Or you can use an entry like this:

    1
    53          3
    3 4 3 
          54
    2
    

    And the result will be: numbers = [1, 53, 3, 4, 3, 54, 2]