Python For Loop and While Loop (with SEO Examples)
About 45 minutes
- variable
- string
- list
- dictionary
- if
- comparison
- set
- 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:
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.
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:
Sarah James Ali
I can use:
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:
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.
name = "Sarah"The first time; print(name) runs and Sarah appearsname = "James"The second time, so James appearsname = "Ali"The third time, so Ali appears
So the code:
can be pictured on the inside as:
Sarah James Ali
And the output is the same either way.
for did the repeating for you.What does iteration mean?
You'll meet an important term: Iteration.
In the code:
there are 3 iterations.
name = "Sarah"The first roundname = "James"The second roundname = "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:
Sarah James Ali
And so is this:
Sarah James Ali
But it's better to pick a name that says what the item is.
If you have:
this is better:
/home /about /contact
than:
url is clearer.Indentation with for
Indentation is essential here.
Look at this example:
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:
Sarah Finished James Finished Ali Finished
Why? Because print(name) and print("Finished") are both inside the for.
And that's a very important rule.
A first SEO use of for
We have some URLs:
/home /about /services /contact
What happened:
url = "/home"Iteration 1url = "/about"Iteration 2url = "/services"Iteration 3url = "/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:
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:
{'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 roundpage = {"url": "/about", "status": 404}The second round…And so on
Printing only the URL
If you want the url value inside each dictionary:
/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:
/about /contact
Why?
- 1The first page is
{"url": "/home", "status": 200}. The condition200 != 200is False. Nothing is printed. - 2The second page is
{"url": "/about", "status": 404}. The condition404 != 200is True, so/aboutis printed. - 3The third page's status is 200, so it isn't printed.
- 4The fourth page's status is 500, so
/contactis 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:
0 1 2 3 4
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:
1 2 3 4 5
Why? Because range(1, 6) means: start at 1 and stop before 6.
range(start, stop), and the stop isn't included in the output.Adding a step
We can write:
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.
0246810The 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:
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.
1 <= 5 → TruePrints 1, then number = 22 <= 5 → TruePrints 2, then number = 33 <= 5 → TruePrints 3, then number = 44 <= 5 → TruePrints 4, then number = 55 <= 5 → TruePrints 5, then number = 66 <= 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:
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.
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.
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.
break means: stop the current loop completely, right now.An example:
1 2
Why didn't 3, 4 and 5 appear? Let's walk through it.
number = 11 == 3 is False, so it prints 1number = 2The condition is False, so it prints 2number = 33 == 3 is True, so break runsnumber = 4Never reachednumber = 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.
An example:
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
1 2
It means: at 3, stop the whole loop.
continue
1 2 4 5
It means: skip 3 only, and keep going.
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:
/home /about /contact
Note that we used endswith() here, which simply asks: does the text end with this?
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 themwhileRepeat as long as the condition is TruecontinueSkip the current item and keep goingbreakStop 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:
/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.
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.
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.url = "/home"Not an image and not /stop, so it prints /homeurl = "/image.jpg"endswith(.jpg) is True, so continueurl = "/about"Not an image and not /stop, so it prints /abouturl = "/stop"The condition is True, so breakurl = "/contact"Never reachedattempts = 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.
url = "/home"Prints /homeurl = "/image.jpg"continueurl = "/about"Prints /abouturl = "/stop"breakattempts = 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.
url = "/home"Prints /homeurl = "/image.jpg"continueurl = "/about"Prints /abouturl = "/stop"breakattempts = 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.
0 < 3 → TrueThe first attempt1 < 3 → TrueThe second attempt2 < 3 → TrueThe third attempt3 < 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.
/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
Question 1
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
What's the output?
Question 3
How many iterations will this code do? And what's the value of url in each iteration?
Question 4
What's the output?
Question 5
What's the output?
Question 6
What's the output?
And why didn't the number 5 appear?
Question 7
What's the output?
Question 8
What's the output? And explain to yourself the value of number in each round.
Question 9
What's the problem with this code? And what's the name of the problem it causes?
Question 10
What's the output? And explain to yourself why one number didn't appear.
Question 11
What's the output? And explain to yourself why the numbers after 3 didn't appear.
Question 12, the most important one
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 full output before you run it.
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/15Exercises 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.