[Tutor] Else vs. Continue

Alan Gauld alan.gauld at btinternet.com
Sun Nov 24 23:38:44 CET 2013


On 24/11/13 21:32, Rafael Knuth wrote:

> I stumbled upon the "continue" statement and to me it looks like it
> does exactly the same as else. I tested both else and continue in a
> little program and I don't see any differences between both.

> for num in range(2,10):
>     if num % 2 == 0:
>         print("Found an even number", num)
>         continue
>     print("Found a number", num)
>
> Same program with else:
>
> for num in range(2,10):
>     if num % 2 == 0:
>         print("Found an even number", num)
>     else:
>         print("Found a number", num)

It's certainly possible to use an if/else to mimic the behaviour of a 
continue, and in languages without continue that's exactly what you'd 
do. But consider this example which puts the continue inside the else 
clause:

for num in range(7):
    if num%2 == 0:
       print 'its even'
    else:
       print 'its odd'
       continue
    evens.append(num)

It's easy enough to do that without using continue but its not as
simple as saying its the same as the else clause.

The other difference is the amount of processing done. Let's assume we 
have a complex function that takes a long time to execute that we need 
to use in a secondary if test. Using continue can avoid that overhead.
Lets say we have one that checks if a number is prime because we only 
want to collect prime numbers:

primes = []
for n in range(1000)
    if n%2 == 0: even numbers aren't prime
       continue
    else:
       if isPrime(n):
          primes.append(n)

Now the continue means the isPrime test never gets executed,
saving a lot of processing. Without continue you would need
to execute the test and the only way to save the time would
be to move the n%2 test inside the isPrime() function - which
you may not always be able to do easily - or wrap the isPrime
like so:

def myPrime(n):
    if n%2 == 0:
       return False
    else:
       return isPrime(n)

and make the loop do this:

primes = []
for n in range(1000):
    if myPrime(n):
       primes.append(n)

But that still incurs a little bit extra cost in calling
myPrime().

So in general, yes, you can always replace continue with
an if/else but it often results in less efficient code,
or code that's less readable (more indentation levels etc).

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list