Python For Loop and While Loop (with SEO Examples)

About 45 minutes

What you need before this lesson
  • variable
  • string
  • list
  • dictionary
  • if
  • print
  • comparison
  • set
What this lesson adds
  • for
  • in
  • iteration
  • indentation
  • range
  • while
  • break
  • continue
  • endswith

The counter at the top counts this lesson's exercises (15 of them). Reading and running the examples don't count.

Before we get into code, let's understand the problem loops solve.

Say you have 4 URLs:

Example
Expected output
https://example.com/page1
https://example.com/page2
https://example.com/page3
https://example.com/page4

The code works, but the problem is you wrote print() four times.

If you had 10,000 URLs, would you write print() ten thousand times?

Of course not.

This is where the idea of a loop comes in.

The rule
A loop simply means: repeat the same thing more than once.

But repeating can happen in two different ways, and that's why we have both for and while.

First: for

The mindset

Use for when you have a group of items and want to do something with each one.

A simple example:

That's a list with 3 names.

I want to print each name.

Instead of writing:

The manual way
Expected output
Sarah
James
Ali

I can use:

Example
Expected output
Sarah
James
Ali

Now let's understand the code word by word.

What does for mean?

When you write:

you can read it in plain English as:

The rule
For each name in names, run the code under for.

for here means Python goes through the items one by one.

What does in mean?

in here means: inside.

So:

means, more or less: for each name inside names.

Where did name come from?

We have the list:

And when we wrote:

we created a variable called name.

Each time round, Python puts one item from the list into it.

What happens each time
  • name = "Sarah"The first time; print(name) runs and Sarah appears
  • name = "James"The second time, so James appears
  • name = "Ali"The third time, so Ali appears

So the code:

can be pictured on the inside as:

The same code, unrolled by hand
Expected output
Sarah
James
Ali

And the output is the same either way.

Note
The difference is that the for did the repeating for you.

What does iteration mean?

You'll meet an important term: Iteration.

The rule
An iteration is one round of the loop.

In the code:

there are 3 iterations.

  • name = "Sarah"The first round
  • name = "James"The second round
  • name = "Ali"The third round

So if you have 100 items, the for will usually do 100 iterations.

Do I have to call the variable name?

No.

This code is correct:

Try it: change it and run
Expected output
Sarah
James
Ali

And so is this:

Try it: change it and run
Expected output
Sarah
James
Ali

But it's better to pick a name that says what the item is.

If you have:

this is better:

Example
Expected output
/home
/about
/contact

than:

Note
Both are correct, but url is clearer.

Indentation with for

Indentation is essential here.

Look at this example:

Example
Expected output
Sarah
James
Ali
Finished

Why did Finished appear only once?

Because print("Finished") isn't inside the for. Notice it starts at the beginning of the line.

But if we write:

Example
Expected output
Sarah
Finished
James
Finished
Ali
Finished

Why? Because print(name) and print("Finished") are both inside the for.

The rule
So indentation decides: which code gets repeated?

And that's a very important rule.

A first SEO use of for

We have some URLs:

Try changing the list and running it
Expected output
/home
/about
/services
/contact

What happened:

  • url = "/home"Iteration 1
  • url = "/about"Iteration 2
  • url = "/services"Iteration 3
  • url = "/contact"Iteration 4

So if you have a list of URLs, a for can go through them one by one.

Combining for with if

Now we start putting the lessons together.

We have some status codes:

We want to print the codes that aren't 200.

We write:

Example
Expected output
404
500

Let's go round by round.

Round one

status = 200. The condition status != 200 means 200 != 200, and the result is False.

So print(status) doesn't run.

Round two

status = 404. The condition becomes 404 != 200, which is True.

So print(status) prints 404.

Round three

status = 200. The condition is False, so nothing is printed.

Round four

status = 500. The condition 500 != 200 is True, so it prints 500.

And that's why the final output is 404 and 500.

Using a list of dictionaries

Now let's take data shaped more like real work.

Here we have a list. Inside the list, we have dictionaries.

Let's try this first:

Example
Expected output
{'url': '/home', 'status': 200}
{'url': '/about', 'status': 404}
{'url': '/services', 'status': 200}
{'url': '/contact', 'status': 500}

Why? Because in each iteration the variable page holds a whole dictionary.

  • page = {"url": "/home", "status": 200}The first round
  • page = {"url": "/about", "status": 404}The second round
  • …And so on

Printing only the URL

If you want the url value inside each dictionary:

Try it: change it and run
Expected output
/home
/about
/services
/contact

Why did we write page["url"]? Because page itself is a dictionary.

For example, in the first iteration page equals {"url": "/home", "status": 200}, and when we write page["url"] we get /home.

Printing only the pages with a problem

Now we combine: list + dictionary + for + if.

The code:

Example
Expected output
/about
/contact

Why?

  1. 1The first page is {"url": "/home", "status": 200}. The condition 200 != 200 is False. Nothing is printed.
  2. 2The second page is {"url": "/about", "status": 404}. The condition 404 != 200 is True, so /about is printed.
  3. 3The third page's status is 200, so it isn't printed.
  4. 4The fourth page's status is 500, so /contact is printed.

Second: range()

Sometimes you don't have a list to go through; you just want to do something a set number of times.

That's where we use range().

An example:

Example
Expected output
0
1
2
3
4
Watch out
Notice something important: range(5) didn't print 5. That's because range(5) starts at zero and stops before 5.

Setting the start and the end

You can write:

Try it: change it and run
Expected output
1
2
3
4
5

Why? Because range(1, 6) means: start at 1 and stop before 6.

The rule
So the rule is range(start, stop), and the stop isn't included in the output.

Adding a step

We can write:

Try it: change it and run
Expected output
0
2
4
6
8

Here the values mean: range(0, 10, 2) starts at 0, stops before 10, and moves by 2 each time.

So it goes
  • 0
  • 2
  • 4
  • 6
  • 8
  • 10The next number, but we stop before 10

Third: while

The mindset

for says: I have a group of items, go through them.

But while says: keep repeating as long as the condition is True.

So while doesn't really depend on a list; it depends on a condition.

A simple example:

Example
Expected output
1
2
3
4
5

Let's take this slowly.

The start

We wrote number = 1. So right now number equals 1.

Then while number <= 5: Python asks, is 1 less than or equal to 5? The answer is True, so it goes inside the while.

The rounds, one by one
  • 1 <= 5 → TruePrints 1, then number = 2
  • 2 <= 5 → TruePrints 2, then number = 3
  • 3 <= 5 → TruePrints 3, then number = 4
  • 4 <= 5 → TruePrints 4, then number = 5
  • 5 <= 5 → TruePrints 5, then number = 6
  • 6 <= 5 → FalseSo it stops

So the final output is 1, 2, 3, 4 and 5.

Why does number = number + 1 matter?

If we delete it:

This code never stops. Don't run it
Output
1
1
1
1
1
1
1
1
...

What happens? At the start number = 1, and the condition 1 <= 5 is True, so it prints 1. But number never changed.

So the while comes back and asks again: 1 <= 5? Still True. It prints 1, then comes back again. And it goes on forever.

Watch out
That's called an Infinite Loop: a loop that never ends.

So with while, always ask yourself: what will happen inside the loop that eventually turns the condition from True to False?

In our example, number = number + 1 is what changed the value of number.

Note
If you try running a loop with no end in any block here, the page stops it after 10 seconds and shows you a TimeoutError instead of freezing the tab.

The basic difference between for and while

Remember the logic, not the code.

for

I have a group of items and want to do something with each one.

An SEO example: for url in urls: means go through every URL.

while

I want to repeat something as long as a condition holds.

An example: while attempts < 3: means keep going as long as the number of attempts is under 3.

Fourth: break

Before the code, the mindset.

The rule
break means: stop the current loop completely, right now.

An example:

Example
Expected output
1
2

Why didn't 3, 4 and 5 appear? Let's walk through it.

  • number = 11 == 3 is False, so it prints 1
  • number = 2The condition is False, so it prints 2
  • number = 33 == 3 is True, so break runs
  • number = 4Never reached
  • number = 5Never reached

break means: leave the for at once. So it never reaches 4 and 5.

And 3 itself isn't printed, because break happened before print(number).

Fifth: continue

continue is different.

The rule
It doesn't stop the loop. It just skips the current iteration and moves on to the next item.

An example:

Example
Expected output
1
2
4
5

Notice that only 3 disappeared. 4 and 5 ran as normal.

Why? When number = 3, continue ran, and it means: that's it, skip the rest of this iteration's code and go to the next iteration.

So print() didn't run for 3. But the loop didn't stop: it moved on to number = 4, then number = 5.

The difference between break and continue

Look at the two examples side by side.

break

Output
1
2

It means: at 3, stop the whole loop.

continue

Output
1
2
4
5

It means: skip 3 only, and keep going.

The rule
break = stop the loop. continue = skip the current round only.

An SEO example of continue

We have:

Say we don't want to process images. We write:

Try it: change it and run
Expected output
/home
/about
/contact

Note that we used endswith() here, which simply asks: does the text end with this?

Try it on its own
Expected output
True

So for the images, continue ran and they were skipped.

A quick mindset before the final example

We now have four ideas.

  • forI have a group of items, go through them
  • whileRepeat as long as the condition is True
  • continueSkip the current item and keep going
  • breakStop the current loop completely

Now we'll put all four in one example. It's the most important example in the lesson.

The final example: for + while + continue + break

Here's the code:

The most important example in the lesson: run it and compare with the walkthrough below
Expected output
/home
/about
/home
/about
/home
/about

Now let's take the example apart completely.

First: the data

That's a list with 5 items. Then:

So the number of attempts starts at zero.

Where does attempts = attempts + 1 belong?

Look at the indentation:

The line attempts = attempts + 1 is inside the while, so it belongs to the while. But it isn't inside the for.

Notice the levels: while attempts < 3:, and inside it for url in urls:, and everything inside the for gets extra indentation, like print(url). But attempts = attempts + 1 steps back one level.

The rule
So it means: after the for finishes or stops, add 1 to attempts.

Running it

At the start, attempts = 0. The while tests 0 < 3, and the result is True. So we go into the first attempt.

The first attempt

The for starts from the first item in the list. That matters a lot.

Watch out
Every time the while runs the code again, the new for starts from the beginning of the list. It doesn't carry on from where it stopped in the previous attempt.
The first attempt
  • url = "/home"Not an image and not /stop, so it prints /home
  • url = "/image.jpg"endswith(.jpg) is True, so continue
  • url = "/about"Not an image and not /stop, so it prints /about
  • url = "/stop"The condition is True, so break
  • url = "/contact"Never reached
  • attempts = 1After the for stopped

So we never reach print(url) for /image.jpg, which is why it doesn't show in the result.

And break means: stop the current for completely. So the for never reaches the next item, /contact. That's the key reason /contact never appears at all.

We leave the for, but we're still inside the while, so we reach attempts = attempts + 1. It was attempts = 0, so now it's attempts = 1.

The second attempt

The while comes back and tests 1 < 3, which is True. So a new round starts.

And here's a very important point: the for inside it starts again from /home, not from /contact. Why? Because it's a new for, starting from the top of the list.

The second attempt: exactly the same path
  • url = "/home"Prints /home
  • url = "/image.jpg"continue
  • url = "/about"Prints /about
  • url = "/stop"break
  • attempts = 2

The third attempt

The while asks 2 < 3, which is True. So it starts a third time, and the for starts again from the first item.

The third attempt
  • url = "/home"Prints /home
  • url = "/image.jpg"continue
  • url = "/about"Prints /about
  • url = "/stop"break
  • attempts = 3

Is there a fourth attempt?

The while tests the condition again: 3 < 3, and the result is False. So it stops.

That's why we got only 3 attempts.

The values that met the condition
  • 0 < 3 → TrueThe first attempt
  • 1 < 3 → TrueThe second attempt
  • 2 < 3 → TrueThe third attempt
  • 3 < 3 → FalseStop

Why didn't /contact appear even once?

Because the list is in this order: /home, then /image.jpg, then /about, then /stop, then /contact. And in every attempt, when the for reaches /stop, break runs and the for ends.

So it never got to /contact at all. Not in the first attempt, not in the second, and not in the third.

Why didn't /image.jpg appear?

Because continue made Python skip that iteration only. So /image.jpg was reached, but skipped.

/contact is a different story: Python never reached it, because of break.

The rule
/image.jpg was reached and then skipped. /contact was never reached at all.

The difference between continue and break in this example

At /image.jpg, continue ran, meaning: leave this item and go to the next one. So we moved on to /about.

But at /stop, break ran, meaning: stop the whole for. So we never moved on to /contact.

The whole lesson's mindset

When you hit a problem and want to know what to use, think like this.

I have a set of data

Like URLs, keywords, status codes or pages, and I want to go through them one by one? Use for.

I want the repeating to continue based on a condition?

Like: keep going while attempts is under 3. Keep going while there's a next page. Keep going while the API is still returning data. Use while.

I'm inside a loop and want to skip the current item only?

Like: I found an image and I don't want to analyze images. Use continue.

I'm inside a loop and want to stop it completely?

Like: I hit the maximum. I found the item I was looking for. I reached a certain value and want to end the process. Use break.

The quiz

Note
Note that I won't give the outputs here, because the point is for you to predict them. Write your prediction first, and after you answer, the real code runs so you can compare for yourself.

Question 1

Answer in your own words

Explain in your own words the difference between for, while, continue and break. I don't want memorized definitions; I want your mindset for each one.

Write your answer first. The value is in trying before you look.

Question 2

Predict the output

What's the output?

Question 3

Check your understanding

How many iterations will this code do? And what's the value of url in each iteration?

The code for question 3

Question 4

Predict the output

What's the output?

Question 5

Predict the output

What's the output?

Question 6

Predict the output

What's the output?

Check your understanding

And why didn't the number 5 appear?

Question 7

Predict the output

What's the output?

Question 8

Predict the output

What's the output? And explain to yourself the value of number in each round.

Question 9

This code never stops. Don't run it
Check your understanding

What's the problem with this code? And what's the name of the problem it causes?

Question 10

Predict the output

What's the output? And explain to yourself why one number didn't appear.

Question 11

Predict the output

What's the output? And explain to yourself why the numbers after 3 didn't appear.

Question 12, the most important one

SEO challenge

Print the URLs whose status code isn't 200

Write code that uses for and if to print the URLs whose status code isn't 200.

Question 13, the lesson challenge

Without running the code, predict the full output:

Predict the output

Predict the full output before you run it.

Check your understanding

How many attempts will there be? And why didn't image.jpg and contact appear?

If you answered all these questions and understood why /contact never appeared even once, then you really understand loops, not just what they look like.

You still have exercises left

0/15

Exercises left: 15 of 15. The lesson counts as complete once you solve them all, and you can come back to them any time.

Well done, you reached the end of the lesson.