简体   繁体   中英

Why and how multiple lines input works in Python

Before you report me for duplicate let me link similar topics which say how to write the code, but don't say how it works:

Now the code to read multiple lines:

'''
input data:
line 1
line 2
line 3
'''

line_holder = []

while True:
    line = input("\nPlease paste here lines :\n")
    if line:
        line_holder.append(line)
    else:
        break
for line in line_holder:
    print(line)

How I understand it:

  • loop will repeat until "break" statement
  • in input we paste multiple lines which are stored in some kind of queue
  • if there is anything in the input queue to work with
  • add first value from this queue to list
  • if there is nothing, kill the loop with "break"
  • finally, print what we added from queue input to list

So if there is a queue of inputs, how else can I reach it? How is it stored on the computer and why do I need to build list, to see it?

So if there is a queue of inputs, how else can I reach it?
As written your loop does not access a queue - input takes input from stdin ... typically data entered from the keyboard by the user.

How is it stored on the computer ...?
Assume you are referring to the non-existent queue (see above) but when you append line to the list, you are storing that line in the list.

... and why do I need to build list, to see it?
You don't - you could just print the line to see it, but if you want to use that data later you have to put it in some kind of container and a list is convenient.

Here's the rundown of it all The first line (starting from line_holder = []) declares line_holder as an array, for when you need to add lines.

Then the while True makes it an infinite loop(unless instructed otherwise inside of the loop)

Inside the loop is an input, which is assigned to the variable 'line'

Then it checks if line has anything in it (if line), if it does, it adds the contents of 'line' to the array which was declared already as line_holder.

However if there is nothing in line(else) then it breaks the loop, which then starts a for loop being for line in line_holder, which just assigns the first, then second, etc line to the variable line, and then prints it, until line_holder doesn't have any places left in it.

Hope this cleared it up for you, any questions just add a comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM