Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

python - 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 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 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...