Reputation: 714
This nested loop works fine when reading lists:
list = [1,2,3,4,5]
num = 0
while num < 5:
for i in list:
print(i)
num += 1
This loop will print all elements in the list. The problem is that it doesn't work at all when reading textfiles. Instead of printing the first 5 lines of text it will read through all and print them.
f = open(r'C:\Users\Me\Python\bible.txt')
num = 0
while num < 50:
for line in f:
print(line)
num += 1
I can only assume that the num variable doesn't increase after each iteration, is there a reason for this, and is there a solution?
Upvotes: 0
Views: 1598
Reputation: 17670
the code
for line in f:
print line
num += 1
is looping over all the lines in your file. At the same time it increase num
by one. So at the end of the for-loop num
will be equal to the number of lines in the files, probably larger than 50, so it will exit from the while-loop.
Using your style you should write:
for line in f:
print line
num += 1
if num > 50: break
Also the first code has the same problem. Why do you need two loops if you want to loop over one structure in one dimension? Your codes are not very pythonic, for example you should rewrite them as:
list = [1,2,3,4,5]
for i in list:
print i
for i,line in enumerate(f):
print line
if i > 50: break
Upvotes: 2
Reputation: 5333
I would not believe your code works, even in the first example. Since you code two nested loops, the inner loop wil always complete, before the termination of the outer loop is checked. I would suggest to drop the outer looper and insert something like
if num > 50: break
into the inner loop.
Upvotes: 1