The for loop
Looping statements are used to repeat an action over and over again. One of the most common looping statements is the for loop. The syntax of this loop is:
for variable in object: statements
Here is a breakdown of the syntax:
- for – the keyword that indicates that the for statement begins.
- variable – specifies the name of the variable that will hold a single element of a sequence.
- in – indicates that the sequence comes next.
- object – the sequence that will be stepped through.
- statements – the statements that will be executed in each iteration.
Take a look at the following example:
for letter in 'Hello World!': print(letter)
The code above will produce the following output:
>>> H e l l o W o r l d ! >>>
Let’s break down the code above:
- for – starts the for statement.
- letter – the name of the variable that will hold the current value. During the first iteration, the first item in the sequence will be assigned to the variable. During the second iteration, the second item in the sequence will be assigned to the variable, etc. In our case, the string value H will be assigned to the variable letter during the first iteration, the value e during the second iteration, etc.
- sequence – in our case, the sequence is a string of characters (Hello world).
- print(letter) – the statement that will be executed in each iteration. In our case, the character currently stored in the variable letter will be printed.
for loops are usually used with the range() function, explained in the next lesson.