 # While loops | BUS 104 – Python Exam

Still feeling nervous for your exam? Check out the Python Cram Kit for practice questions that emulate the difficulty that you'll face on your exam. Each question includes a thorough step-by-step explanation where I walk you through the entire problem solving process!

## 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:

print(0)
print(1)
print(2)
print(3)

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?

print(0)
print(1)
print(2)
print(3)
print(4)
print(5)
print(7)
print(8)
print(9)
print(10)

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!

i = 0

while i <= 3:
print(i)
i += 1

Let's go line-by-line and break down what's going on here.

i = 0

while i <= 3:
print(i)
i += 1

The first step to writing a while loop is to declare a counter variable. This is a value that is modified through each iteration of the while loop.

The counter variable enables us to keep track of what loop number, or "lap", we're on of the loop.

When counting from 0 to 3, we must start counting at 0 (with i) and add 1 to it each time.

We must start counting at 0, not any other number. We're counting from 0 to 3.

Therefore, our counter value (i) will be declared as 0 to start.

i = 0

while i <= 3:
print(i)
i += 1

This is the condition of our while loop. Like we explored when learning conditionals, conditions return either true or false.

In the case of loops, whenever the condition returns true, the loop runs. Whenever the condition returns false, the loop does not run and exits.

So, why exactly did we place "i <= 3" in our condition? Because we want to count to 3, but not count above it.

See how once we reach 4, our condition is false? This causes our loop to stop running, therefore preventing us from counting over 3.

I'll explain this in a different way.

Let's say we've run through the loop four times. This would result in our counter variable, i, equaling 3. (Remember, we're counting from 0 to 3, not 1 to 3).

We would then enter the while loop for the fifth time like this:

while 3 <= 3:

This condition is true, so we print the value of 3…

while 3 <= 3:
print(3)
...

…and increment our value of i from 3 to 4.

while 3 <= 3:
print(3)>
i += 1

Now, when we re-enter the loop again, the condition is false…

while 4 <= 3:

…resulting in the loop ending!

### Code to be executed within the loop

i = 0

while i <= 3:
print(i)
i += 1

The big thing to note here is that the value of i is changing each loop, so we'll be printing something different each time.

Now's a good time to run this program on your own computer so you can see the output. Type the following into your Trinket file:

Run your program by clicking the "Run" button above your code. You should get the following output:

Notice how the values change each time we run through the loop in the slideshow below:

• The first time we run through the loop, when the value of i is 0, 0 will be printed in our output.

### Incrementing the counter

i = 0

while i <= 3:
print(i)
i += 1

You might be asking, what does "i += 1" actually mean?

Well, it's shorthand for "i = i + 1". And what does that mean?

Essentially, it means take the old value of i...

i = i + 1

i = i + 1

...and assign it as the new value of i.

i = i + 1

"i += 1" is just a shorter way of writing this. The value in doing this is it enables us to add 1 to the value of i each loop.

Before we move on, you need to know that...

Incrementing the counter is the most crucial step of writing while loops.

But, why is this the most crucial step of writing while loops?

If you don't increment your counters, you'll experience endless loops.

Endless loops occur when the condition will always return true.

#### An endless loop illustrated

Take our current Python program, for example. Imagine that we removed the "i = i + 1" line.

i = 0

while i <= 3:
print(i)
i += 1

Now, let's walk through what happens when this loop executes.

First iteration of the loop, we enter with a value of 0…

while (0 <= 3):

…print 0…

while 0 <= 3:
print(0)

…then exit the loop and resume again.

We enter with a value of 0…

while 0 <= 3:

…print 0…

while 0 <= 3:
print(0)

…and exit the loop and resume again.

We enter with a value of 0...

Get the picture? This process of printing 0 continues forever.

We fix it by incrementing our counter within our loop!

i = 0

while i <= 3:
print(i)
i += 1

### Putting it all together

Now that we've successfully learned how to prevent an endless loop, let's recap how each step of a while loop goes.

First iteration of the loop, we enter with a value of 0…

while 0 <= 3:

…print 0…

while 0 <= 3:
print(0)
...
}

…increment the value of i.

while 0 <= 3:
print(0)
i += 1
}

i now equals 1.

The loop restarts and we enter with a value of 1…

while 1 <= 3:

…print 1…

while 1 <= 3:
print(1)
...
}

…increment the value of i.

while 1 <= 3:
print(1)
i += 1
}

i now equals 2.

The loop restarts and we enter with a value of 2…

This process continues until i reaches a value of 4...

i now equals 4.

The loop restarts and we enter with a value of 4…

while 4 <= 3:

...but since "4 <= 3" is false, the loop stops running and ends.

## Revisiting the while loop template

Now that we've broken down our while loop that counts from 0 to 3, here's a template for while loops that you can use in the future:

define counter variable (if necessary)

while condition:
code to be executed
increment counter variable (if necessary)

## While loops with flag variables

For the sake of time, I'm not going to get into flag variables here. Chances are, you've got an exam you need to cram for, and flag variables may take up too much of your time.

However, in the case that you need to learn about them, I wrote Flag Variables | Python in 30 Minutes for you explaining what they are and how they work.

## Practice problem

In a new Trinket file, create a program that asks the user for an input, asking "Enter a number to count to from 1.". Save that value as a variable.Then, in a while loop, the program counts to this number from 1, printing each number.

Check out the slideshow below to see what your output should look like.

• The user types 2 and presses enter...

HINT #1: Forget how to ask the user for an input that returns as an integer? Refer to the input() function ...with integers template on the last page of your Python Cheat Sheet!

HINT #2: Need help printing in the output? Check out the print() function template on the last page of your Python Cheat Sheet!

i = 1
integer = int(input("Enter a number to count to from 1."))

while i <= integer:
print(i)
i += 1

Note: if you named your i or integer variables to something else, it's alright. As long as the functionality of the program is the same, that's all that matters!

## Python Follow-along Guide

It's no secret you retain info better when you write it down. That's why I created the Python Follow-along Guide for you!

As you come upon key concepts highlighted in yellow, like this sentence here, you can fill-in-the-blanks on your Python Follow-along Guide so that you remember all the important stuff for later!

You can obtain your Python Follow-along Guide for FREE by entering your email below!

Now that we've learned our first loop, let's move onto the second loop we'll learn in this guide: the for loop. Click below to start learning!

### Concepts

Each exam concept broken down with relatable situations to your life!

### Practice Problems

Include step-by-step explanations through each part of the problem!

"...I was blown away with the videos and the ability to explain what is going on at a simple level. Highly recommend!"

Jack Whelan
March 8, 2021

Rating: 5 out of 5.