- #1
- 5,199
- 38
My code isn't working, and the reason seems to be because nested for loops in python don't work according to my expectations. If I have some code like this:
My expectation for the output:
The output that I ACTUALLY get:
Huh?
Code:
f1 = open('name_of_file1.txt', 'r')
f2 = open('name_of_file2.txt', 'r')
for line1 in f1:
#stuff at this level should happen once for every line in file1. Right?
print line1
for line2 in f2:
#stuff at this level should happen once for every line in file2. Right?
print line2
My expectation for the output:
Code:
line 1 from file1
.
.
.
(all lines from file2 here)
.
.
.
line 2 from file1
.
.
.
(all lines from file2 here)
.
.
.
line 3 from file1
.
.
.
(all lines from file2 here)
.
.
.
et cetera
The output that I ACTUALLY get:
Code:
line 1 from file1
.
.
.
(all lines from file2 here)
.
.
.
(all remaining lines from file1 in sequence)
Huh?