My backwards logic

Ian Kelly ian.g.kelly at
Fri Sep 5 19:17:40 CEST 2014

On Fri, Sep 5, 2014 at 11:08 AM, Ethan Furman <ethan at> wrote:
> Python's 'for' loop has a handy 'else' extension which is perfect for the
> search-type of 'for' loop:
>    while True:
>         a=random.randrange(1,8)
>         print (a)
>         for x in range(2,a):
>             if a%x==0:
>                 print ("Number is not prime")
>                 break
>         else:
>             print ("Number is prime")
>         wait = input (" "*40  + "Wait")
> Note the two lines I added after the 'break' and before the 'wait'.

Also note that this construct tends to be particularly sensitive to
indentation. If you accidentally indent the else block one level too
many (which your editor may well do for you to "helpfully" match it up
with the if), then you'll get a completely different result.

I would not worry about the else clause as a beginner, as it's
relatively unique to Python and tends to be somewhat confusing. Use a
flag or refactor the function instead.

More information about the Python-list mailing list