Today about the simplest and most-used python loop: for.
In programming, we often want to repeat the selected instruction many times. It would be nice to do this without having to type commands multiple times, right? Exactly. In Python — as you probably already guessed — this task is done using the for loop.
Here's the syntax for our loop:
for i in range(n):
# some
# instructions
# here
The for loop is the easiest way to execute repetitive statements in Python.
Let's take a closer look at the for loop
As you can see, in the for loop we use the well-known range(n) command, which generates a sequence of numbers from zero to n‑1. We also use the variable i — which is often called "control variable" or "counter". The for loop therefore may be read like an ordinary English sentence: for i in range 0 to n‑1, execute "instructions".
Or: execute "instructions" for the following values i=0, i=1, i=2, …, i=n‑1.
The variable i can appear in the body of the statement, but does not have to.
A few comments:
1 / the header line of the loop ends with a colon
2 / subsequent line (or lines) containing repetitive instructions are indented four spaces from the main code
3 / you can name the control variable in any way, not necessarily with the letter 'i'.
The for loop "by itself" defines the variable
Many students learning the basics of programming are surprised to see a variable appear "freely" in the for loop, as if it had fallen out of the sky. Recall that in the case of a while loop, the variable had to be defined ("initialized") in the program before it could be used in the loop.
In the case of the for loop, this is not necessary. When in Python you write: for i in range … – you have just defined the variable i.
This otherwise interesting thread could certainly be refined and refined, but it is neither time nor place….[1]
Exercises
- Write a script that will ask the user for their first name four times, and in response to the given name, it will write back: "Hello [name]" each time.
- Write a script that for first five natural numbers displays their "doubles" (desired output: 2, 4, 6, 8, 10).
- Write a script that for each of first five natural numbers (from 1 to 5) will display the sum of the preceding numbers (desired output: 0, 1, 3, 6, 10).
The for loop and compound data
Remember the sixth passage of our cycle when we explained what compound data is? And in particular, the so-called sequence data? It will turn out in a moment why we are returning to them.
Recall: these are data types that consist of smaller elements: "blocks", arranged in a specific order. These building blocks are professionally called constitutive elements.
The content of the attached table seems obvious. The constitutive elements would be quite easy to indicate intuitively, right?
You can also guess that thanks to the for loop we can easily and efficiently break down sequence data into single blocks — our "constitutive elements". So text into single letters, lists into elements, and a range of numbers into single numbers. In other words, we are talking about sequential access to complex data elements.
Sequential access means accessing the items of a collection one by one in a specific order, starting from the beginning. We also use the term "iterate" over collection items.
How does a for loop work on a collection?
The for loop allows sequential access to complex data elements. And this access is extremely simple. Just look at some examples:
First example
S = 'house'
for letter in S:
print(letter)
Output:
h
o
u
s
e
Second example
L = ['cork', 'pen', 'coin', 'spoon']
for element in L:
print(element)
Output:
cork
pen
coin
spoon
In the examples presented above, the for loop notation is an excellent example of a simple, readable Python syntax, intuitively close to the human language. No range needed, no indexes needed. Just the most ordinary: "for item in collection…" — and it's ready!
It is also the most general notation of for loop syntax. The previously presented syntax: using the range function – is just a "special case" of iteration – that is, iterating over successive numbers in a range. But you can iterate — as we just showed — also over the letters in a word and over list items in a list.
Note how we named the variables in the loop: in the first example, the variable is substituted with letters, so we named it letter. In the second example, the variable is substituted with list items, so we named the variable element. However, it is worth emphasizing once again: the choice of the variable name does not matter. Name the variable as you like. You can use pretter or sweater instead of letter — the loop will work anyway.
On the other hand, using suggestive variable names makes your code more understandable:
colors = ['white', 'blue', 'green']
for color in colors:
print (color)
Output:
white
blue
green
The for loop is an extremely useful tool, everyday bread for IT specialists. It's so popular that it's probably found in every major computer program.
Exercises
Exercise 1
Write a program to remove the last character from each of the items in the list
['whitey', 'blacky', 'redy', greeny ',' pinky ']
Exercise 2
Write a program which selects only elements starting with 'to:' from the given list and put them in a new list
['from: Margaret', 'to: John. E', 'to: Steven. H', 'subject: Sales / marketing', 'to: David. L', 'subject: Tech', 'from: Margaret', 'to: Sara. N', 'subject: Provisions', 'from: Margaret', 'to: Chris. B', 'subject: Sales / marketing', 'to: Richard. T', 'subject: Sales / marketing', 'from: Margaret', 'to: Fiona. N', 'subject: Tech', 'to: Denis. L', 'subject: Provisions', 'to: Elias. R', 'subject: Sales / marketing', 'copy to: Bookkeeping Dept', 'from: Margaret', 'to: Mark. B', 'subject: Sales / marketing']
Hint:
How to find — among the various elements — those that begin with a specific string of characters? go to the w3schools website dedicated to "string methods" https://www.w3schools.com/python/python_ref_string.asp Find the right method (we'll tell you that its name starts with the letter "s"). See the syntax and examples. Then apply to our assignment. |
How to add items to the list? go to the w3schools website dedicated to "list methods" https://www.w3schools.com/python/python_ref_list.asp find the right method (we'll tell you that its name starts with the letter "a"). See the syntax and examples. Then apply to our assignment. |
To create a new list (for example, with the name M) write: M = [] |
Exercise 3
Write a program that replaces the word 'See' with the word 'Sea' in each of the given list items:
['the Azov See', 'the Caspian See', 'the Baltic See', 'Black See', 'North See', 'Mediterranean See', 'Adriatic See', 'the Aegean See', 'Japanese See'].
Some sea names lack the article 'the'. Develop an algorithm to compensate for this deficiency.
[1] More precisely, a variable in Python arises (is "initialized") when it is assigned a value; in the for loop, a variable with a fixed name (eg i) is "switched" to a new value after each cycle of the loop.