While loops in Python!

by look i have opinions

This is not an opinion, just some student notes. (If you’re a student too, don’t take my word for anything. I’ve just barely scratched the surface of programming so far. This tool is pretty helpful though.)

It took me some time to figure out when while loops kept going and when they stopped. The existence of the break command puzzled me because it seemed to me that every while loop already had a built-in break point: the point at which the while conditions were no longer fulfilled. (In other words, I thought that the compiler/computer would check the while conditions after each line of code.) If the loop could stop at that point automatically, then break would be redundant and ugly.

Now I think I understand. A while loop keeps going until the end of the loop. At that point, and only at that point, it returns to the beginning and checks whether the conditions are still fulfilled. It’s possible that, after the first command following the while line, the conditions are no longer fulfilled; but there’s no way it’s going to stop in mid-loop, unless break or some similar command interrupts the process. I’m now picturing the compiler running its finger under each line of code, like a child learning to read (we all did that, right?), going only where the code tells it to go.

~~~

One other thing it took me a while to grasp. If you have nested while loops, a break in the deepest loop only breaks the immediate loop it’s in, not all of them. So I don’t need to superstitiously avoid burying my breaks. (Any time I notice myself behaving superstitiously, it means I don’t understand the code well enough. A computer is a truth machine.)

Advertisements