yego.me
💡 Stop wasting time. Read Youtube instead of watch. Download Chrome Extension

while loops | Intro to CS - Python | Khan Academy


4m read
·Nov 10, 2024

What if you want your program to repeat a block of code? You could copy and paste those lines of code. But what if you wanted to repeat it 100 times or a thousand times? Or maybe you don't even know upfront how many times you need it to repeat. To solve this, we can use a while loop.

A while loop tells the computer to keep executing a block of code as long as a certain condition evaluates to True. We've used Boolean conditions before with conditionals in a basic if statement. The computer evaluates the condition once and if it evaluates to true, it executes any code indented inside of it, and then it moves on to execute the rest of the program.

With a while loop, the computer evaluates the condition, and if it evaluates to true, the computer executes any lines of code indented inside of it. However, now that we're at what we call the bottom of the loop, the computer will go back to the condition and check it again. If it still evaluates to true, the computer will execute the lines of code indented inside the loop again, and so on, and so on, and so on. Until when the computer checks the condition, it finds that it evaluates to False. Only then does the loop terminate for good and the computer moves on to execute the rest of the program.

In Python, the syntax for a while loop is just the keyword while followed by a Boolean condition and then a colon. Any lines of code we want to repeat inside the while loop we indent one tab over. We call this the loop body. Because we want the loop to terminate eventually, we don't want it to repeat forever. We'll want the loop condition to evaluate to false at some point. Typically, that means our loop condition will include a loop variable, which is a variable that gets updated inside the loop body on each trip through the loop, what we call an iteration. The value of the variable will change, which means that when we go to check the loop condition again, there's a chance it might evaluate to false this time.

Let's take a look at our coin flip experiment. Here, we generate a random number between 1 and 2, and if that number is one, we print "heads," and if it's two, we print "tails." Now, what if I want to repeat that experiment to see how often I get tails? I can wrap my experiment in a while loop.

So, the first thing I'm going to want to do is figure out what my loop condition should be. Let's say I want to repeat this experiment five times, so my condition might be something like num_flips less than five. Then any lines of code I want to repeat need to be indented one level in. Well, on each iteration, I want to generate a new random number to simulate a coin flip, and then I still want to check if it's one or two and print heads or tails. So I'm going to tab all of these lines of code over.

If I run this program now, I get a name error because the variable num_flips hasn't been defined. We never assigned it a value. With while loops, we always want to make sure we initialize our loop variable before the loop. Here, we probably want to initialize num_flips to zero because we haven't done any coin flips yet. At this point, we have zero flips.

Now that our name error is fixed, it looks like the computer's printing heads, tails, tails, heads, heads forever. This is what we call an infinite loop. Our loop never terminates because our loop condition never evaluates to false. If you ever see your program hanging like this, you want to press the stop button to recover and terminate the program. Otherwise, it'll keep running forever until the computer runs out of memory.

So why is it infinite looping? Well, we never update the value of the loop variable inside the loop body. So num_flips always contains the value zero, which means every time we go back to the top and check the loop condition, we're checking if 0 is less than 5, which will always be true. What we actually want is to increment num_flips by one every time we flip a coin, so we're essentially counting up the number of flips.

Before the first iteration, num_flips will be zero. Then before the second iteration, it'll be one, two, three, and four until the check becomes five less than five, which evaluates to false, and the loop terminates. By convention, we update the loop variable at the very bottom of the loop so that it changes right before we go back to check the loop condition. Then we can increase our number of repetitions just by modifying this stop value in the loop condition, say to 100 or a thousand.

So when you're writing while loops, make sure you check for all three key components: that you initialize your loop variable before the loop, that you check your loop variable in the loop condition, and that you update the loop variable at the bottom of the loop body.

More Articles

View All
Patterns in hundreds chart
So what we have in this chart is all the numbers from 1 to 100 organized in a fairly neat way. It’s a somewhat intuitive way to organize it where each row you have 10. So you go from 1 to 10, then 11 to 20, then 21 to 30, all the way to 100. And what we’…
Resource | Vocabulary | Khan Academy
Gather your wits about you, word Smiths, because the word we’re talking about today is resource! Food in the pantry, diamonds in the mind, wealth, brain power—resource. It’s a noun; it means wealth, money, minerals, land, or other useful things. We can t…
Crypto Will Be The 12th Sector of The S&P! | Bitcoin 2022
[Music] It’s pretty chaotic here on the first day because nobody knows where to go. There’s 50,000 people showing. The first day probably about 250,000 by the time this is over, and it’s really going to be big this year because there’s so many institution…
Miyamoto Musashi | A Life of Ultimate Focus
Miyamoto Musashi is one of the most legendary samurai and famed as Japan’s greatest swordsman—undefeated in more than sixty duels. After he escaped death during the Battle of Sekigahara, Musashi became a ronin. Aside from being a swordsman, he was also a …
How To Become A MILLIONAIRE - The Truth No One TELLS YOU! | Kevin O'Leary & Barbara Corcoran
Oh, you can’t believe where we are tonight. We’re in Barbara’s home. This place is a very secret penthouse. I’m trying to make it exciting, Barbara, but we have a beautiful view of the park. We’re in the kitchen because Barbara is making me dinner tonight…
ROBINHOOD LOOPHOLE GIVES YOU INFINITE MONEY
Before I start this video, I want to make a very serious disclaimer. The purpose of this video is to describe a newsworthy event, the issues surrounding it, why it’s a bad idea to engage in this type of behavior, and bring to light a very serious issue so…