Loops
What is a loop?
In programming, loops are constructs used to repeat something multiple times.
For example, if you have a list of the grades you've achieved throughout the term, you might use a loop to help you calculate the average grade you achieved.
If you have a list of friends, you might use a loop to help you check which friends' names start with the letter "S"
.
In Python there are two types of loop: the for
loop and the while
loop. They are both used to repeat code, but their purposes are slightly different.
The for
loop is used to repeat something a specific number of times, but the while
loop is used to repeat something an indefinite number of times.
How does the for loop work in Python?
Let's say you have a list of friends, and you want to check which friend has a name starting with the letter "S"
. You could use a for
loop like so:
friends = ["Rolf", "Smith", "Anne"]
for friend in friends:
if friend.startswith("S"):
print(f"{friend} starts with S!")
The for
loop is defined like this: for friend in friends:
What this does is:
- Tells Python you're going to repeat the code using the
friends
list.- The number of times is equal to the number of elements in the
friends
list.
- The number of times is equal to the number of elements in the
- Defines a new variable called
friend
, and gives it the value of the first element of thefriends
list. - Runs the code directly below it (as long as the code is indented, that's important).
- When it reaches the end of the indented code, it goes back to the top but the
friend
variable takes the value of the second element of thefriends
list.
So the loop runs once where friend
is "Rolf"
, then again where friend
is "Smith"
, and then a third time where friend
is "Anne"
.
We've also learned how to check the starting characters of a string, using friend.startswith("S")
.
By doing your_variable.startswith("something")
you check whether your_variable
(which must be a string) starts with the characters placed inside the brackets!
Another example
Imagine you wanted to calculate the average grade you've achieved in your exams.
First, you need a list of your grades:
grades = [90, 95, 98, 99, 100, 60]
Then, you create a variable that will hold the total grade:
grades = [90, 95, 98, 99, 100, 60]
total = 0
We can now go over each grade and add it to the total:
grades = [90, 95, 98, 99, 100, 60]
total = 0
for grade in grades:
total = total + grade
And finally, we can divide it by the length of the grades
list to give us the average:
grades = [90, 95, 98, 99, 100, 60]
total = 0
for grade in grades:
total = total + grade
average = total / len(grades) # Not indented, so not part of the loop!
print(f"Your average grade was {average}.")
It's important to remember there are always many ways to do something! We as programmers are often blinded by the first solution we come up with, and we can't easily think of other, potentially better, solutions.
Here's a better solution to the example above:
grades = [90, 95, 98, 99, 100, 60]
total = sum(grades)
average = total / len(grades)
print(f"Your average grade was {average}.")
Granted, you'd have to know that sum()
exists and that you can use it, but that's why we're learning!
The while loop
The while
loop is similar to the if statement in many ways.
Whereas the if statement runs its body once if the condition is True
, the while
loop keeps repeating the body as long as the condition is True
. Here's an example:
is_learning = True
while is_learning:
print("You're learning!")
If you were to run that, you'd see this output:
You're learning!
You're learning!
You're learning!
You're learning!
You're learning!
You're learning!
You're learning!
...
Continuing endlessly. That's because the while
loop runs the body until the condition is False
.
The condition, is_learning
, is True
and never changes to False
. Therefore, the loop runs infinitely.
Similarly, if you do this:
is_learning = True
while is_learning:
print("You're learning!")
is_learning = False
You would only see:
You're learning!
That's because the loop will run once, since is_learning
is True
, and print out the phrase.
Then we change is_learning
to False
.
The loop then restarts because we reached the end of the body.
But is_learning
is False
, so it does not run the body. Instead, it goes to the very next line after the body ends (which happens to be the end of the code).
An example with user input
Here's a more useful example of a while
loop.
We'll run our loop until the user tells us to stop.
user_input = input("Do you wish to run the program? (yes/no): ")
while user_input == "yes":
print("We're running!")
user_input = input("Do you wish to run the program? (yes/no): ")
print("We stopped running.")
Here you would see first the prompt used to ask the user whether they want to run the program or not. If they type yes
, then we would begin the while
loop.
Do you wish to run the program? (yes/no): yes
We're running!
Do you wish to run the program? (yes/no):
That would continue until the user enters anything that isn't "yes"
.
Do you wish to run the program? (yes/no): yes
We're running!
Do you wish to run the program? (yes/no): yes
We're running!
Do you wish to run the program? (yes/no): bla
We stopped running.
Note that our loop only runs if the user's input is "yes"
, so they can enter "no"
, "bla"
, or anything else to stop the program.
Modifying lists while looping
We learned earlier on how to remove an element from a list. A common pitfall is to use a for
loop to go over all the elements of a list, but while you're in the loop you remove some elements.
Don't do this:
grades = [56, 70, 90, 100]
for grade in grades:
print(f"You got {grade}.")
grades.remove(grade)
Because the output will be confusing!
You got 56.
You got 90.
Where are the other 2 grades?
They disappeared because Python started at grade with index 0 (the first grade).
It printed out "You got 56."
.
Then we removed 56
, so now the next grade, 70
, becomes the first grade with index 0.
When Python moves onto the next grade, it's actually moving onto index 1.
However our list looks like this now: [70, 90, 100]
... The grade with index 1 is 90
.
We the print "You got 90."
, and remove it. We are in index 1 and now move onto index 2.
However, our list is now [70, 90]
. There's no index 2. The loop ends.
Don't modify lists while you're using them in a for loop! Dangerous!
Conclusion
We've learned a bit about loops, for
and while
, in Python. Don't expect to know exactly when to use them in every situation! Loops, like everything else in programming, require practice in order to best know when to use them.
With this section's project and all the other programming you do, you'll gain experience using loops in no time!