Basic While Loop Structure
This lesson shows you the basic syntax of a while
-loop by example. Additionally, the code is debugged in a live session to show you, what’s happening behind the scenes. A simple while
-loop may look like this:
n = 5
while n > 0:
n = n - 1
print(n)
00:00
All right, so let’s start by looking at the basic structure of the Python while
loop. First, we’re always going to start with the word while
.
00:06
Then we’re going to have whatever condition that needs to return True
in order for the block of code to execute. And then we’re going to have our block of code. Now, a few syntactical notes.
00:19
Number one, you need to make sure you have your colon (:
) here. Number two, your code that’s going to be executed needs to be indented four spaces, and that’s just following PEP 8. Now let’s look at an actual example.
00:31
So first, I want to set a variable. I’m going to say n
is equal to 5
. Then I’m going to start my while
loop. So, remember, start with the word while
, and then I’m going to set my condition. So in this case, I’m going to set my condition that n
needs to be greater than 0
.
00:53
And then I’ve got my colon (:
), and now we’re going to start the code that I want to execute every time. First, I’m going to want to decrement n
by 1
, so n
is going to be equal to n - 1
.
01:05
Then I’m just going to print(n)
. Now before we run this code, just take a minute to look over it and think about how many times this is going to be executed. What do you think the output is going to be? Let’s look.
01:21
All right. So we see 4
, 3
, 2
, 1
, and 0
. We can use our debugger in Thonny to actually look at what’s happening step by step in this code.
01:32
First, we’re going to be setting our variable to 5
. So over here, you can kind of keep up with the variable and see how it’s changing. So we have our variable set to 5
.
01:43
Now I’m going to check that my variable is greater than 0
.
01:51
n
is currently set to 5
, so that’s going to return True
. And if it does, then it’s going to execute this code. So it’s going to evaluate n
as 5
and decrement it by 1
, which is going to give us 4
.
02:05
So now if we look back over here, n
is equal to 4
.
02:10
So, whenever we go to our next number, you’ll notice that it jumps back up to the top here. n
is now equal to 4
, and that is still True
that it is greater than 0
.
02:22
So then it’s going to execute the code. And that’s how we got 3
. Now this continues on until we get to 0
.
02:32
So we are going to print 0
,
02:37
and then you’ll notice that it does jump back up to the top, so it didn’t just stop at that point. It’s going back to check if now 0
is greater than 0
.
02:46
However, it finds out that it is False
, therefore it is not going to execute this block of code and it’s actually going to exit the while
loop. Next, we’re going to be looking at how a while
loop can be used with a list.
Become a Member to join the conversation.