1

Reading this post didn't really answer my question.

I have a

reader = csv.reader(source)
for row in reader:
    if len(row[0]) > 23:
        # Do stuff
        continue
    if low > float(row[1]) > high:
        # Do stuff
        continue
    if low > float(row[2]) > high:
        # Do stuff
        continue
else:
    print('All', reader.line_num, 'read successfully.')

setup, but the else is executed despite me skipping in the for loop.

I'd rather that the else was only called if no continue was hit.

In order to clarify, the purpose of the code is to drop bad/malformed data rows in the CSV file. As such, malformed lines have individual error handling. Using 'else' as final notifier would, if possible be much more beautiful than working with flags.

3
  • 2
    You should explain with example input what you are expecting as output. Commented Oct 14, 2015 at 4:39
  • 1
    else is called if the for loop exits due to exhausting the iterator, you would need a break to avoid the else being called. Commented Oct 14, 2015 at 4:43
  • I think using a flag variable like continued = True, while not particularly pythonic, is the best option. Commented Oct 14, 2015 at 4:45

1 Answer 1

4

The only thing that matters to else is whether or not the loop terminated because you reached the end of the iterable; it doesn't care what happens inside the loop.

If you want to have different behavior depending on if continue was ever called, then you have to keep track of that yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

Fair enough. I'll have to keep track of rows skipped manually then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.