[Tutor] Help with a while or a for loop that only allows three tries

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun Apr 13 21:25:01 2003

On Sun, 13 Apr 2003, R. Alan Monroe wrote:

> > Also some times I see a while loop that starts out like while 1: what
> > does that tiring to say, only go through the loop once. Or is that a I
> > if so what would you use something like that example for?
> "while 1:" means the same thing as "while true:" Bascially it would run
> forever, because 1 is always 1, or true is always true.

So whenever we say say something like:

    while 1:
        ## do something

we are setting up a potential "infinite loop" that will continue to
repeat until we do something spectacular, like 'breaking' out of a loop:

>>> while 1:
...     command = raw_input("enter a value, or type 'quit' to quit: ")
...     if command == 'quit':
...         break
...     print "I don't understand", command
enter a value, or type 'quit' to quit: jump
I don't understand jump
enter a value, or type 'quit' to quit: w
I don't understand w
enter a value, or type 'quit' to quit: e
I don't understand e
enter a value, or type 'quit' to quit: quit

Ok, the code was a little useless there, but I hope it gets the idea
across... *grin* So this 'while 1' set-up is common in situations where we
want to repeat something until some situation changes.

[As a side note, it's actually now possible for us to write:

    while True:
        pass        ## <--- put body of while loop here instead

In Python 2.2, a 'True' boolean value (and, symmetrically, a 'False'
value) is being slowly phased into the Python language.  We might as well
use it.  *grin*

Still, expect to see 'while 1:' a while yet, since us old fogies need some
time to adjust to this traumatic change to the language.]

If you feel uncomfortable about setting up the loop like there, there is a
another way to arrange things to a similar effect:

command = raw_input("enter a value, or type 'quit' to quit: ")
while command != 'break':
    print "I don't understand", command
    command = raw_input("enter a value, or type 'quit' to quit: ")

This is an alternative way to phrase that idea of looping.  The reason we
don't see this approach as much is because there's a little bit of
redundancy in the first and last lines, but it's an equally valid way to
do the looping.

In fact, for your original question about limiting the number of loops to
at most three times, this form may be more convenient for you.

If you have more questions, please feel free to ask!