How on Python to process the sequential input of lines, if

  1. the number of these lines is not indicated. That is, you cannot use a for loop,
  2. besides, it is not said how the input will be completed, that is, you cannot use a while loop ?
  • Where did restrictions 1 come from? for in Python easily handles an unknown number of lines, for example, when reading from a file. - insolor
  • Limit 1 came from tasks of the following type: a certain number of lines is supplied to the input, and not in the file. We need to process them and do something. Here is an example of such a task- pythontutor.ru/lessons/dicts/problems/sales - KY1
  • For example: ideone.com/Zwznnu It is clear that you could just do a while loop, but it is often easier to parse the input data first and then go through it with the for loop. The for loop works with any iterated object, not necessarily a specific length. - insolor

2 answers 2

A file in python can be iterated in rows, for example,

 for line in sys.stdin: # делаем что угодно со строкой, например print(len(line)) 

This will work only if the standard input stream is not connected to the terminal, for example, it is redirected from a regular file.


Or you can read the file one by one.

 while True: line = sys.stdin.readline() if line == '': break # обработка print(len(line)) 

Of course, you can’t do without cycles at all.

In order to stop in all these cases when input occurs from the terminal, you need to press CTRL - D (on Linux) or CTRL - Z (on Windows).

  • The while loop is useless here: it's just a verbose way to write the first for-loop (if the bug with the read-ahead buffer on Python 2 is not considered). - jfs

We introduce the restriction that reading is only through input . If the data is completed, a ValueError (as in PythonTutor) or EOFError (as in Ideone) is thrown.

Through while

 while True: try: try: line = input() except (ValueError, EOFError): break # здесь можно как-то строку обработать print(line) 

Through for

We package the while loop into a function, and turn it into an iterator (plus dividing each line by whitespace characters):

 def inputs(): while True: try: line = input() # Здесь может происходить какая-то предварительная обработка данных: data = line.split() yield data except (ValueError, EOFError): return for name, purchase, count in inputs(): # Окончательная обработка данных print(name, purchase, count) 

It is often convenient to do exactly the second option, if the initial processing (parsing) of the text is rather complicated, and you need to separate it from the actual data processing.

  • one
    You can divide input / output and calculations: for line in iter_except(input, (ValueError, EOFError)): words = line.split()... where iter_except() is the itertools recipe . You can just more_itertools module - jfs