While loops explained
Count from 0 to 3.
Congrats, you just accomplished the core functionality of a while loop.
First, we set a starting value of 0.
Then, we counted 1 by 1 until we reached 3.
Once we reached 3, we stopped counting.
So, how does this relate to while loops?
While loops, when given a starting value, continue looping while a certain condition is met.
You might be confused how this relates to while loops right now, so let's dive into an example so you can see.
Don't be tempted to do this!
With your current Python experience, I'd expect you to hear "Make a Python program that counts from 0 to 3" and code the following:
While this would work, it's bad practice. What if I asked you to make a Python program that counts from 0 to 10 instead?
Ugh. Talk about a headache to type out! Not only is it annoying to type, but what if you mess up one of the numbers? I’m sure you didn’t even notice that I forgot to type a 6…
This can be cleaned up with a while loop. Let's learn how to write one!
Coding a while loop
To teach you how to code while loops, I'm actually going to first reveal the answer to you, and then we'll break it down step-by-step.
Here's the answer to coding a while loop that counts from 0 to 3!