Skip to content

While loops gone wild

2010 May 5
by Hélène Martin

I hope that my students know that I too feel programming is hard.  In fact, I hope some of them realize that programming is exciting and meaningful to me in large part because it’s such a challenge.  When students complain about difficulty, I like to remind them that they’re in school to stretch themselves but sadly that
doesn’t tend to resonate much with them.  Go figure.

In Creative Computing, we recently spent time working with indefinite loops.  I think most introductory programming instructors would be shocked and appalled at how long we’ve spent primarily focusing on one
measly construct.  Indeed, while loops are a half-hour lecture in most college-level intro to programming courses.  But here’s the deal – while loops are hard.  What does it take to use a while loop properly? I’ve tried to think of all the little things necessary to know how to interpret and create code using indefinite loops but I’m sure I’ve forgotten bits and pieces! I poked around a little for formal articles with these sorts of breakdowns for various programming constructs but wasn’t very successful. Pointers?

Understanding while loops requires…

  • syntactic knowledge
    • start the statement with while, have some condition in parentheses, end the line with a colon then indent things that need to be repeated
    • valid boolean operators (assignment = vs. equality ==)
    • creating complex boolean expressions with and and or (for example, my students often write things like value == 2 or 3 which won’t work as expected in Python)
    • how to group statements into a block
  • understanding of scope rules
    • if I use a variable in my test, it has to have been initialized
    • if I create a variable in my loop, it won’t be available later
  • understanding of flow of control
    • if I make a method call in my loop body, that method is run then Python keeps executing statements after the call
    • if my condition stops being true somewhere in the loop body, that doesn’t make me magically jump out
    • the test is executed every time around the loop
  • converting between stopping conditions and continuing conditions
    • DeMorgan’s Law is hard

I have a lot of sympathy for students who take more time to synthesize all of this and I think it’s too bad that we don’t have more best practices on breaking concepts down into digestible pieces.  At the same time, I think CS courses are exciting for high-achieving students BECAUSE we haven’t figured out how to break things down into bite-sized chunks, yet!  Certainly, when I was starting my perpetual quest to learn to program, I found something deeply satisfying about looking at several examples of a construct to establish a model of how it works.  For students who are not used to considering an idea from different angles in an attempt to really understand it, it’s a deeply frustrating process.

I feel like this points to a deep need for differentiated instruction to  keep my top end students engaged without overwhelming my bottom end.  I’ve been trying to be more careful about giving students sample code that address sub-concepts one at a time and having different milestones so students at various levels can be successful.  Again, not really finding best practices but that’s probably because computing education is primarily done at the college level where it’s not much of a concern for instructors (or I don’t know where to look?).  Raymond Lister and John Leaney’s First Year Programming: Let All the Flowers Bloom does present some nice work supporting the idea of shifting my goals for weaker students to reading and interpreting code rather than producing entirely novel programs.

Of course, I don’t pretend to know what the right solution is.  One thing I think is underscored by the overwhelming list of concepts needed to understand the humble while loop is the importance of being very deliberate about the order topics are introduced in.  Sometimes I look at introductory programming course syllabi and I feel like concepts are just being thrown haphazardly into a pile instead of aiming to construct knowledge.  Strong students will probably be fine but what about normal people?!

8 Responses leave one →
  1. L bricker permalink
    May 6, 2010

    I think one thing you could do is teach the concept of looping outside of programming first, doing some exercises on repetition UNTIL something happens. That will give them the idea of the “testing”

    A good example is just walking.

    While I am not hitting a wall
    walk forward one step.

    The test is “I am not hitting a wall” (you can discuss boolean logic here, and play with it in terms of or a corner, etc). So you have a lot of ideas there that you can bring in

    With the body of hte loop, you could change the requirements so that each time you are stepping one extra step. How do you keep track of that.

    Maybe have a piece of paper/counter on your body as an internal variable, but instead have a student keep track of the counter for a variable outside the context of the “you” loop.

  2. Hélène Martin permalink*
    May 6, 2010

    L, I think that’s a great idea. Appealing to students’ basic understanding of the world helps a lot. But it’s certainly not enough — students rarely have problems with the IDEA of a while loop… it’s the implementation that baffles them.

    Notice that in your first sentence you suggest doing exercises on repetition UNTIL something happens. This does appeal to our intuition very nicely, but it’s not how while loops work, which is exactly part of the problem! Scratch has repeat until, but Python and most other standard languages only have a “while a certain condition holds true” construct. If we have students think in terms of repeating until, which is quite natural, then we run into DeMorgan’s Law when coding. Heck, that trips me up sometimes, too!

    I do think some kinesthetic activities can help but unfortunately I don’t think they’re the full solution. But what is, right?

  3. May 9, 2010

    I’ve had trouble explaining loops to people as well. Certainly let me know if you figure out the best way to do it.

    I noticed one error in your statements: “if I create a variable in my loop, it won’t be available later”

    In python and PHP, among others, that is not true; both have only one local scope. Ie, this is valid in python

    i = 0
    while i < 5:
      i += 1
      a = i
    print a, i

  4. Hélène Martin permalink*
    May 9, 2010

    Ahh, yes, you’re correct. My Java students suffer from loop confusion as well and I kind of lumped it all together. In Python, the issue is that we often need variables as accumulators, like i in the example you give, and students for whatever reason don’t see that those need to be initialized before. We get a lot of ‘referenced before assignment’ issues that really throw students off.

    Unfortunately, I don’t think there’s any one ‘best way,’ but if I find it I’ll let you know!! =)

  5. May 12, 2010

    I just had a thought… I know, stop the presses, right?

    As an example of why you need to declare the accumulator before the loop, consider a sum accumulator vs a product accumulator:

    def sum(lst):
      for val in lst:
         acc += val
        return acc

    def prod(lst):
        for val in lst:
            acc *= val
        return acc

    So, in braindead languages like PHP (<3 PHP!), you could get away with the sum implementation with just a warning. Maybe it's "obvious" that acc should start out at zero. However, there's no language that I know of where the prod implementation would work: you'd always get "0" out at the end.

    The fix is easy, and it illustrates the importance of defining accumulators beforehand:

    def sum(lst):
        acc = 0
        for val in lst:
            acc += val
        return acc

    def prod(lst):
        acc = 1
        for val in lst:
            acc *= val
        return acc

    Well, that’s my idea.

  6. May 14, 2010

    Another underlying set of concepts that students need to know in order to form a successful mental model of loops and conditionals:

    * The processor can only execute one instruction at a time.
    * There is one and only one program counter.

    I don’t explicitly introduce “program counter” as vocabulary, but the concepts are essential. Without this understanding, jumping out of the middle of a loop seems plausible. This is one situation where the extra punctuation required by the curly-bracket languages is helpful in reinforcing the concept that a loop controls an entire block of code.

    • Hélène Martin permalink*
      May 15, 2010


      Very good point. Sometimes I forget that some apparent misconceptions are really just symptoms of deeper ones. It’s very hard for some students to understand that computers can only do one thing at a time since first of all we multitask all the time and secondly it feels like computers are constantly doing many things. I have students work with Scribbler robots in Python and it seems like that’s when some of them recognize the limitations of having just one instruction done at a time — “what do you mean I can’t have it play a song and move at the same time?!” Other students got the idea long ago and are not surprised at all.

      I disagree that curly braces are a particular advantage in this case — I think it makes just as much sense to say that a block is an indented chunk of code than to say that it’s delineated by curly braces. That being said, it took me a while to accept that!

Trackbacks and Pingbacks

  1. Interesting Links 10 May 2010

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS