for loop over list break and continue

痴心易碎 提交于 2019-12-13 09:34:45

问题


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 some xml files the entry - MaxAmdLetterDate is None. I want to proceed to the next file in the folder, instead right now with break , the program execution goes to the next folder and skips all files in that folder when it encounters a break This is the code

import xml.etree.ElementTree as ET
import os
for yrcnt in range(1995,2015):
    old= old="./old/"+ str(yrcnt)
    for dirpath, subdirs, files in os.walk(old): #folder name in which subfolder>files are present
        print files
        for filename in files:
            if filename.endswith(".xml") == True:
                fl=filename
                print fl
                print "-----Reading current file -------"  + str(fl)
                flnm=str(dirpath)+"/"+str(filename)
                tree1 = ET.parse(flnm)                        #db on system
                root1 = tree1.getroot()
                for ch1 in root1.findall('Award'):
                    aid1 = ch1.find('AwardID').text
                    maxdate1=ch1.find('MaxAmdLetterDate').text
                    print "Max amd date : "+str(maxdate1)
            if maxdate1==None:
                break

Help is appreciated .

ORIGINAL POST: My for loop gets an early exit on encountering a break . Any remedies ?

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

o/p:

  1
  2
  3

expected O/p

  1
  2
  4
  5

Thanks !

EDIT: With some comments such as this is expected function of break . Let me elucidate: I want the function to be similar to a range(0,5) , Iam using this as a part of nested loop where I want the loop to go on , and not exit out due to one file .


回答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 



回答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


来源:https://stackoverflow.com/questions/30017958/for-loop-over-list-break-and-continue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!