Skip to content Skip to sidebar Skip to footer

For Loop Over List Break And Continue

To specify the problem correctly :i apologize for the confusion Having doubts with breaking early from loop . I have folders - 1995,1996 to 2014 . Each folder has xml files. In so

Solution 1:

This is the way break works. If you want to iterate over the whole list, simply remove the break (or if you want to do something with the value, use pass as a placeholder).

values = [1, 2, 3, 4, 5]
for value in values:
    if value == 3:
        pass
    print(value)

Output:

1
2
3
4
5  

If you just want to a skip a value, use continue keyword.

values = [1, 2, 3, 4, 5]
for value in values:
    if value == 3:
        continue
    print(value)

Output:

1
2
4
5 

Solution 2:

Break automatically exits out of your loop. If you do not want to print the filename when it is 3, use an if statement like this:

files=[1,2,3,4,5]
for filename in files:
  if filename!=3:
     print filename

This is the result:

1
2
4
5

Post a Comment for "For Loop Over List Break And Continue"