On how to use “while” loops in Python
I like the language of the “while” loop because it verges on real-life, commonsense English. After all, we run these kind of loops all the time in our daily lives. For example, while my neighbor’s tree is producing lychee nuts and I’m allowed to pick them, I’m damn well going to pick some. Once it stops producing good fruit (or once my neighbors tell me to take a hike), I’ll cease picking them.
“While loops” work the same way in Python. While a condition is True (or False), the code will do something. After that, it’ll stop.
Take the following example:
numbers = list() i = 0
while (i <= 20): numbers.append(i) i = i+2 print(numbers)
This almost reads like regular English. Here’s how to parse it: while the numbers in a list are equal to or less than 20, we keep adding the number 2 to them and sticking them in a list. The “numbers.append(i)” line is what “appends” the numbers into the list. Once the numbers go over 20, the conditions have changed and we stop running the loop. We wind up with a list full of even numbers like so:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
But if you screw up, you can send your computer into a spasm of infinite loops. I’ve unintentionally done it before. I was fortunate that someone had told me that that I could press Ctrl-C to stop the script and get out of the loop.
Let’s take a simple example of a ‘while’ loop::
loopy = 1 while loopy < 4: print (loopy) loopy = loopy + 1
This loops a few times and prints out the following:
BUT, if we had left out the last line of code, we’d be stuck in an infinite loop because 1 is always less than 4. So, the computer simply would not know when to stop. Keep in mind that computers can do things very quickly, including things that you don’t want them to do (but unintentionally commanded them to do). An infinite loop is out-of-control code that can crash your computer. But, on the brighter side, at least you gain a deeper appreciation for that loopy symbol for infinity.
Featured image is Symbol used by Euler to denote infinity. Leonhard Euler - Variae observationes circa series infinitas. Commentarii academiae scientiarum Petropolitanae 9, 1744, pp. 160-188.