Lesson 9. Control Flow With while
Lesson 9. Control Flow With while
In your software engineering career, you will have occasion to repeatedly execute a block of code based on some condition. In every programming language, there are a couple of constructs that allow you to do this. In this lesson, I am going to introduce one of the Python looping methods.
The while loop is not the best way to create loops in Python. However, it is a construct that exist that is fundamental to the language, so I am going to explain how it works now. In later lessons, we will learn a more efficient looping tool.
The while loop is aptly named. Do something while some condition exists. The key thing to remember is that the condition is checked at the top of the loop. Not understanding that is how you wind up with code executing outside of the range that you intended.
While loops are a huge source of bugs in your code. If you do not construct your loop properly you can wind up with code that performs outside of the bounds defined by your condition, or, you can wind up with the dreaded infinite loop.
An infinite loop is exactly like it sounds. Your loop will go on forever until you either stop the interpreter, or you eat all the resources on your machine. Neither of these events are desirable. Put another way, you want to avoid those things happening at all cost.
break AND continue
While works with two other constructs: break and continue. You use these constructs when you need to get out of your loop or skip some code in your loop.
break: Breaks you out of the loop. Control returns to the code block after the loop.
continue: Skips the rest of the code in your loop and sends control back to the top of the loop for a condition check.
That continue statement is clearly another opportunity for you to mess up and get fired. Make sure that, wherever you put your continue statement, it does not prevent any incrementors from executing, or, at the least, code for that scenario.
while Syntax
Examples
Incrementing An Index Value
In other languages, you frequently have to loop through a data structure called an array. Array values are referenced by some index value. While loops are usually the construct that you use to increment the index value as you move through the array.
In this example, I am going to introduce the concept of increment and decrement by one. Python does not have an increment/decrement operator, so we have to MacGyver a solution with what we have laying around. Here is how you increment and decrement in Python.
Step 1. Find a paperclip. Step 2. Find some chewing gum. Step 3. Throw the paperclip away. Step 4. Put the chewing gum in your mouth. Step 5. Use the following syntax to increment and decrement values.
Watch what happens when we put the incrementor above the print statement. As you can see, i winds up being a value outside of the condition specified in i < 10. Having your incrementor above your code block is not necessarily wrong or a bad thing. It is merely something to be aware of. The condition defines where you put the incrementor, but the reverse can also be true; the incrementor can help defined your condition.
Since we do not want to process integer values greater than 9, we need to change our condition. This is technically correct, however, as you can see, it does not make a whole lot of sense. That is to say, it is not “readable”. You cannot look at the code and understand what is going on right away.
Readability is a hallmark of Python code. In a later lesson, we are going to get into how to write things so they are considered “Pythonic”. For now, I’m not gonna lie. In the real world, I’ve written complex code blocks where I couldn’t understand why it was processing outside of the bounds of the condition. Instead of doing the hard work and correcting it, I’ll just find a value that for the condition, so the code won’t run out of bounds and leave that garbage for the next guy to deal with. Whatever bro. I get phat paid for code that WORKS, not code that looks pretty.
(Ok, I’m just kidding. I’ll go back and fix it when I have time.)
Most people think in integer terms, but it is possible to increment by other values including real numbers. Obviously, incrementing by irrational numbers would be, uh, irrational and incrementing by imaginary numbers should only happen in your head. Otherwise, you are free to increment however you want.
Using break And continue To Find Prime Numbers
Below is a horribly inefficient algorithm* to find all the prime numbers between 2** and 50. I wrote this garbage for illustration purposes only. Never write anything like this in the real world.
I have set the variable upward_bound to 50. Find a chart of prime numbers and play with the value of upward bound. See what the code produces and see if it matches your prime number chart.
*For those new to computer science, an algorithm is a set of instructions that perform the same task over and over. In data science, you will hear the word algorithm a lot. When I create the course CSCI200 Fundamentals In Computer Science, we will talk more about algorithms. For now, all you need to know is that, contrary to what some folks in the c-suite think, algorithms do not cure cancer.
**Fun math fact. I learned in grade school that a prime number is a number that is only divisible by itself and 1. Despite the fact that 1 seems to fit both of those conditions, 1 is not a prime number. I was today years old when I learned that.
Now you try it!
Don't copy and past. Type the code yourself!
Last updated