continue vs. pass in this IO reading and writing

Terry Reedy tjreedy at udel.edu
Thu Sep 3 18:05:28 CEST 2015


On 9/3/2015 11:05 AM, kbtyo wrote:

> I am experimenting with many exception handling and utilizing continue vs pass.

'pass' is a do-nothing place holder.  'continue' and 'break' are jump 
statements

[snip]

> However, I am uncertain as to how this executes in a context like this:
>
> import glob
> import csv
> from collections import OrderedDict
>
> interesting_files = glob.glob("*.csv")
>
> header_saved = False
> with open('merged_output_mod.csv','w') as fout:
>
>      for filename in interesting_files:
>          print("execution here again")
>          with open(filename) as fin:
>              try:
>                  header = next(fin)
>                  print("Entering Try and Except")
>              except:
>                  StopIteration
>                  continue
>              else:
>                  if not header_saved:
>                      fout.write(header)
>                      header_saved = True
>                      print("We got here")
>                  for line in fin:
>                      fout.write(line)
>
> My questions are (for some reason my interpreter does not print out any readout):
>
> 1. after the exception is raised does the continue return back up to the beginning of the for loop (and the "else" conditional is not even encountered)?
>
> 2. How would a pass behave in this situation?

Try it for yourself.  Copy the following into a python shell or editor 
(and run) see what you get.

for i in [-1, 0, 1]:
     try:
         j = 2//i
     except ZeroDivisionError:
         print('infinity')
         continue
     else:
         print(j)

Change 'continue' to 'pass' and run again.

-- 
Terry Jan Reedy



More information about the Python-list mailing list