The "loop and a half"

ROGER GRAYDON CHRISTMAN dvl at psu.edu
Wed Oct 4 16:17:31 EDT 2017


I teach a course in programming to students who have no plans to be
programmers, scientists, or engineers.    And I deliberately lied today about
the for loop.

In my lecture slide, I said that the for loop could only be used if you had
a collection of values (e.g. list, tuple, dict, string, or range)
where all the data was in hand, and should only be used when 
truly planning to visit the entire collection.

The slide essentially claimed, you could not use the for loop to
input a series of values from the keyboard, until seeing a blank line or zero.
or to search a list until you found the first even value, and stopping when you
get there.
If you want to stop repeating for an arbitrary reason, you must use a while
loop.

Deliberate lie.

Verbally I said it was actually a fib, and that there was a way to
do these cleanly with a for loop, but it's a method that I postpone until
halfway through the second course for students in the major,
not the sort of thing I would teach to this particular audience this early.

But yes, we can use yield, and iter(), and itertools to do both of these
examples very clearly with a for loop (and without an explicit break statement),
but I'd rather keep my course content small and simple.


Roger Christman
Pennsylvania State University
>

>




More information about the Python-list mailing list