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?
the code
is looping over all the lines in your file. At the same time it increase
numby one. So at the end of the for-loopnumwill 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:
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: