The Python Oracle

how to break out of only one nested loop

This video explains
how to break out of only one nested loop

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: RPG Blues Looping

--

Chapters
00:00 Question
01:59 Accepted answer (Score 37)
02:33 Answer 2 (Score 4)
02:56 Thank you

--

Full question
https://stackoverflow.com/questions/1855...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #loops #nested #break

#avk47



ACCEPTED ANSWER

Score 41


break and continue apply to the innermost loop.

The issue is that you open the second file only once, and therefore it's only read once. When you execute for y in file2.readlines(): for the second time, file2.readlines() returns an empty iterable.

Either move file2 = open(filename2, 'r') into the outer loop, or use seek() to rewind to the beginning of file2.




ANSWER 2

Score 4


You need to parse the numeric strings to their corresponding integer values.

You can use int('hoge') as follows.

import sys

filename1 = sys.argv[1]
filename2 = sys.argv[2]

with open(filename1) as file1:
    for x in file1:
        with open(filename2) as file2:
            col = x.strip().split()
            for y in file2:
                col2 = y.strip().split()
                if col[1] == col2[1] and int(col[3]) < int(col2[2]):
                    print x