Writing while and for Loops
00:00 In the former lessons, you learned that functions can bundle together code for you, that you can execute with function calls. As you write more and more complex programs, you may find that you need to repeatedly use the same few lines of code.
00:14 You might be tempted to copy and paste similar code to other parts of your program and modify it as needed. But this is usually a bad idea. If you find a mistake in code that’s been copied and pasted all over the place, then you’ll have to apply the fix everywhere the code was copied.
A loop is a block of code that repeatedly executes either a specific number of times or until some condition is met. Python has two kinds of loops:
while loops and
for loops. Let’s start with
You close the
while statement with a colon in the end. So this line is called a
while statement. When Python executes a
while loop, it evaluates the test condition and determines if it’s true or false. If the test condition of the
while statement is true, then Python executes the code in the loop body.
If you execute the loop now, you create a so-called infinite loop. That’s a loop that never terminates. The loop body will keep repeating forever, printing the value
n has over and over again.
You know what? Let’s do it. Let’s try it out. Ready, go. Enter. And there you go. Now Python prints
1 over and over again. You can see on the right side that the scroll bar gets smaller and smaller.
And with Control+C, Python stops running the program and raises the
KeyboardInterrupt error. And this shortcut works anytime Python is running. As you can see, if I repeatedly press Control+C, then this
KeyboardInterrupt is triggered.
The body of the loop is skipped, and the program ends. Otherwise, if
0 or negative, then the body of the loop executes. The program notifies the user that their input was incorrect and prompts them again to enter a positive number over and over again until the condition fails, and the body of the loop is skipped, and the program ends.
while loops are perfect for repeating a section of code while some condition is met. They aren’t well suited, however, for repeating a section of code a specific number of times. That’s where
for loops come into play.
Let’s look at a
for loop example. Just like the
while loop, the
for loop has two main parts: the
for statement and the loop body. Let’s create a loop that print each letter of the string
"donuts" one at a time. I’ll first type it down, and then we’ll look at it in detail.
On the left, you can see the
for loop example from our IDLE session again. At each step of the loop, the variable
letter is assigned the next letter in the string
"Donut", and then the value of the
letter is printed.
The loop runs once over each character in the string
"Donut", so the loop executes five times. Let’s look at the right side. To achieve the same thing like in the
for loop, you must create a variable to store the index of the next character in the string.
At each step of the loop, you print out the character at the current index and then increment the index. The loop will stop once the value of the
index variable is equal to the length of the string. That’s significantly more complex than the
for loop version.
range() loops from
0 to the number you provide as an argument. You can also give range a starting point. For example,
range(1, 5) is the range of numbers
4. The first argument is the starting point, and the second argument is the endpoint, which is not included in the range.
When Python runs the loop on the left side, you print the numbers
4. Let’s have a look at the
while loop version on the right. First, you assign the integer
1 to a variable,
n. When Python executes a
while loop, it evaluates the test condition and determines if it is true or false.
So yeah, most of the time, a
for loop is more concise and easier to read than an equivalent
while loop. That’s why you’ll probably encounter and use
for loops much more often than
while loops. Before we wrap this lesson up, let me show you another cool thing.
As long as you indent the code correctly, you can even put loops inside of other loops. So for example,
for n in range(1, 4): Enter … So now I’m indented with four spaces, and I create another
for j in range( … again,
1, 4): Enter.
closing the string, closing the parentheses, and hitting Enter once, twice, and now you can see a nice long printed output saying
n = 1 and j = 1,
n = 1 and j = 2, and so on until
n = 3 and j = 3.
print(), Python returns to the inner
for loop and assigns
j and prints
n = 1
and j = 2. Python doesn’t return to the outer
for loop, because the inner
for loop, which is inside the body of the outer
for loop, isn’t done executing.
So next, Python assigns
j and prints
n = 1
and j = 3. At this point, the inner
for loop is done executing, so control returns to the outer
for loop. Python assigns the value
2 to variable
n, and then the inner
for loop executes a second time.
You can nest
while loops inside
for loops and vice versa. You can even nest loops more than two levels deep. But you heard me saying this a few times during this course: if you nest your loops, then you have to take care of the indentation of your code.
All right, now you know a thing or two about
while loops and
for loops. But didn’t somebody say ice cream at the beginning of this lesson? Yeah, you’re right. So there is one last thing that we need to do.
Become a Member to join the conversation.