[Tutor] Using optional else with for loop

Alan Gauld alan.gauld at yahoo.co.uk
Mon Sep 28 17:50:12 EDT 2020


On 28/09/2020 14:00, Manprit Singh wrote:

> def isprime(x):
>     for i in range(2, int(x**0.5) + 1):
>         if x % i == 0 :
>             return False
>     else:
>         return True
> 
> x % i == 0 inside the for loop will evaluate to True at some point of time.
> 
> Now return False inside if x % i == 0 will break the loop as well as it will
> return False to the function call which will indicate that the number in
> question is not a prime number. At this time else clause  of for loop will
> not work as the loop is broken due to Return False

That is correct

> If the number in question is a prime number, at that time the for loop will
> fully  operate  or either will not even start(at the time when the number in
> question is 2  or 3). In that case the else clause will  work and return
> True will indicate that the number is prime

That's not quite right. The else is only called if the loop
ends successfully.

The main use of a for/else is where a break instruction is
used inside the loop so that the loop exits but the surrounding
function does not exit(as happens with return). Then the else
gets called if the break is not called.

If you use a return to exit the loop you also immediately exit
the function so the else becomes irrelevant and you don't need
the else, you can just write:

def isprime(x):
    for i in range(2, int(x**0.5) + 1):
        if x % i == 0 :
           return False
    return True  # only reached if x is prime

This is because return will always return from the surrounding
function immediately so the else never gets called. Another way
to write your function which would require the else is:

def isprime(x):
    result = False
    for i in range(2, int(x**0.5) + 1):
        if x % i == 0:
           break
    else: result = True
    return result

But that's more complex so the twin return version would be
a more common choice in this case. for/else is a fairly
rare sight.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list