[Tutor] while loop

Alan Gauld alan.gauld at btinternet.com
Sun Mar 30 13:17:13 CEST 2014


On 30/03/14 02:36, Scott Dunning wrote:

>> Your while loop doesn't quit after 10 times, it keeps going.  Can
>> you figure out why?
>
> This works without a break.
 > Is this more a long the line of what the excercise was
 > looking for you think?

Yes.

>      while n <= 10:
>          print s
>          n = n + 1

Python while loops effectively come in two patterns:

1) while some condition
       do stuff
       modify the test condition

2) while True:
       if some condition:
          break
       else
          do stuff


The first version is actually the intended use of while from a computing 
science point of view.

The second one, which creates an infinite loop and then breaks
out of it is a bit of a kluge which pure structured programming
theory says is bad practice. It has become idiomatic in Python
however, because it often avoids another bad practice, namely
repeating yourself.

For example if we only used the first pattern we often
need to do this:

display_menu()
choice = input('pick a choice: ')
while choice != 'quit':
     if choice == 'save':
        do_save()
     elif choice == ...
     display_menu()
     choice = input('pick a choice: ')

Notice how we have to have the menu/input pair
both before and inside the loop.

We can avoid that using the infinite loop version:

while True:
     display_menu()
     choice = input('pick a choice: ')
     if choice == 'quit'
        break
     elif choice == 'save':
        do_save()
     elif choice == ...

So we have effectively chosen the lesser of two evils.
Compromising on computer science purity is not unusual
in the real world of programming.

In your example there was no need to repeat code so
you could use the uncompromised, pure while loop with
an effective test condition. In that case you can and
should modify the test condition variables inside
the loop, which is what you did with the n = n+1 line.


-- 
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