[Tutor] while else, for else

Sean 'Shaleh' Perry shalehperry@attbi.com
Mon, 14 Oct 2002 07:52:03 -0700


On Monday 14 October 2002 06:30, Blake.Garretson@dana.com wrote:
> I have been using Python for 3+ years now, and I have yet to see regula=
r
> use of the "while else" or "for else" constructs.  I personally *never*=
 use
> them, and unless I haven't read enough source code from other people, I
> haven't seen evidence that anybody else uses them very often either.
>
> If you look in books like "Learning Python" or "Programming Python", yo=
u
> can certainly find examples of how they can be used, but they never see=
m
> necessary.  You can always get by with loops and normal if statments (a=
nd
> some flags).
>
> To me, it seems like they make the code more confusing and less readabl=
e,
> so I don't use them.  So my question is, am I missing something?  Are t=
here
> situations that "while/for else" provide the only way to implement an
> algorithm?  In other words, would I ever *have* to use it in order to d=
o
> something?  Moreover, are there common applications that maybe I *shoul=
d*
> be using this construct?  Are there any Python idioms that use loop els=
es?
>

Thney are definately not required because as you say you can always use a=
n if=20
right after the loop.

I believe the biggest reason that this construct is used less often is th=
at it=20
is python specific and many people code in both Python and some other=20
language(s).  These programmers most likely also came to Python as a seco=
nd=20
(or more) language.  So constructs like for..else are less likely to occu=
r to=20
them.  I would expect to see their usage higher from a person who learned=
=20
Python earlier.

As to when to use them think about it like this.  If your code is logical=
ly an=20
if..else statement but the if logic has to occur within a loop, then an e=
lse=20
makes sense.

while (not to end of line):
    if this word is the right one:
        store =3D word
        break
else:
    never found the word so store a backup word in its place

hope that helps.