Skipping Parts of a For Loop

Michael Chermside mcherm at destiny.com
Mon Sep 16 18:22:13 CEST 2002


> Thomas Guettler wrote:
>>Is there a way to skip some parts in a for loop?
>>   [...]
>>"continue" skipps one element. But how can
>>I skip several?

Andrew Henshaw wrote:
> While not really answering your question... In my opinion, it would be 
> better to use a while loop for that purpose.  The code would be much 
> clearer.

I agree with Andrew. I think the cleanest and most readable way to do it 
would be as follows:


i = 0
while i < UPPER_BOUND:
    do_some_processing()
    if condition:
        i += AMOUNT_TO_SKIP
    do_more_processing()
    i += 1

It makes it very explicit that you are skipping several values of i, and 
any programmer could read this code and understand what it's doing. It 
would be even BETTER if you used a meaningful name for i (perhaps 
"line_number", or "record_id"... use something appropriate to what 
you're doing).

-- Michael Chermside







More information about the Python-list mailing list