user1817310
user1817310

Reputation: 205

can someone explain the code

can someone explain the code How it works: I am not familiar with while loop

 line = file.readline()
 L1=[]
 while line != '' and line != '\n':
    line = line[:-1].split()
    L1.append(line)
    line = file.readline()

 return L1

and can I do it with a for loop? Is it:

     for line in file.readline():
          if line !='' and line !='\n':
             line = line[:-1].split()
             L1.append(line)

     return L1

Upvotes: 0

Views: 112

Answers (3)

Aesthete
Aesthete

Reputation: 18850

Nearly. The first example will stop looping when it reads a line matching '' or '\n'. You could simplify it to this:

from itertools import takewhile
[x.strip() for x in takewhile(lambda x: x not in ['', '\n'], file.readlines())]

This will store every line of the file, until it finds a '' or '\n, in a new array.

Upvotes: 0

xiaofeng.li
xiaofeng.li

Reputation: 8587

  1. read one line from file.
  2. if the line is empty or '\n', stop.
  3. discard the last character (it's usually '\n', strip() is better IMO), split by whitespace, then append list.
  4. goto step 1.

And the problem with your for loop is that it won't stop on empty or '\n'

Upvotes: 4

aw4lly
aw4lly

Reputation: 2155

First read this: http://wiki.python.org/moin/WhileLoop This will explain a while loop to you.

A while loop is a loop which will continue while the conditions are true,

x = 0
while x < 10:
  print(x)
  x = x + 1
print("finished")

will print out 0 1 2 3 4 5 6 7 8 9 finished when x==10 the loop will end and the word 'finished' will be printed.

Upvotes: 1

Related Questions