= ["Jean", "Golding", "Institute"]
my_words print(my_words[0])
print(my_words[1])
print(my_words[2])
Jean
Golding
Institute
It is possible to make Python repeat certain lines of code using loops. The ability to run a line of code multiple times is the first large step on your road to making your code more structured and reusable.
Imagine we have three strings in a list
that we want to print. We could start by calling print
three times to create a program like:
= ["Jean", "Golding", "Institute"]
my_words print(my_words[0])
print(my_words[1])
print(my_words[2])
Jean
Golding
Institute
This printed the output we want. But you may feel that repeating the same call to print
is wasteful code, particularly if we want to repeat the same operation for many elements. If we can manage to write that line only once then we could save ourselves some typing and potentially make the code easier to read!
FOR EACH word IN my_words
DO SOMETHING WITH word
We can write a for
loop in Python which will perform a task once for each word in our list:
= ["Jean", "Golding", "Institute"]
my_words
for word in my_words:
print(word)
Jean
Golding
Institute
Even in this tiny example, we have ve taken a script that was four lines of code and have reduced it to three lines, and more interestingly the same loop will work no matter how many items there are in the list my_words
.
This maps to real life where you may want, for example, to pay for each item on your shopping list. Another way of saying that could be “for each item on my shopping list, add its price to my total”, or as you would write that in Python:
= 0
total for item in shopping_list:
= total + item.price total
If we want to write more code after the end of a loop, we have to make sure that it is not indented. So the below code will print:
= ["Hello", "Python"]
my_words
for word in my_words:
print(word)
print("...Goodbye")
Hello
Python
...Goodbye
On the contrary, the below code will print ...Goodbye
in each iteration. This is because it was inside the body of the loop since it was indented.
= ["Hello", "Python"]
my_words
for word in my_words:
print(word)
print("...Goodbye")
Hello
...Goodbye
Python
...Goodbye
A lot of the power of loops comes from being able to put a lot of different types of data.
Most simply, instead of putting a variable name there, you can put a list directly:
for word in ["Hello", "Python"]:
print(word)
Hello
Python
As well as lists we can put anything which Python considers iterable. For now we haven’t come across many of those but as we keep learning we’ll discover many more. One that we have already come across is strings: looping over a string will always give you one letter at a time.
= "Hello Python"
phrase
for letter in phrase:
print(letter)
H
e
l
l
o
P
y
t
h
o
n
There’s a built in function in Python called range
which provides you with numbers (integers) in a range. If given one number as an argument it will give you integers, starting from zero and going up to, but not including, the number you gave as an argument. We can put this call to the range
function directly into our loop as the object to loop over and it will print:
for number in range(5):
print(number)
0
1
2
3
4
The range
function can also be given two arguments, in which case, the first argument is the number to start counting from and the second argument is used as above:
for number in range(10, 13):
print(number)
10
11
12
Python also allows you to loop over dictionaries. To discover how it works, let’s do the naïve thing first and just see what happens when we loop over a dictionary:
sounds = {
"cat": "meow",
"dog": "woof",
"horse": "neigh"
}
for animal in sounds:
print(animal)
You will recognise those as the keys from the dictionary. So, it seems that when looping over a dictionary we will be given the keys.
What if, for example, you wanted to loop over the values instead. Well, there is a method on dictionaries called values
which gives you just those so that you can loop over them:
= {
sounds "cat": "meow",
"dog": "woof",
"horse": "neigh"
}
for sound in sounds.values():
print(sound)
meow
woof
neigh
If we want to loop over the dictionary and get both the keys and the values, there is a method called items
. Since it will be giving us two things each loop iteration, we’ll have to use the same trick as we did with enumerate
and give two variable names in the for
loop declaration:
= {
sounds "cat": "meow",
"dog": "woof",
"horse": "neigh"
}
for animal, sound in sounds.items():
print(animal, "goes", sound)
cat goes meow
dog goes woof
horse goes neigh
The items
method gives us two pieces of data where the first is always the key and the second if always the value. We give the keys the name animal
and the values the name sound
. We can then use both those variables in the loop body.