简体   繁体   中英

Is there a Pythonic way of activating 'else' in a 'for' loop, when a continue has hit?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM