For Loop
In programing, loops allow you to execute instructions repetitively. The while loop will repeat the instructions while a certain condition is true. The for loop will repeat the instructions for a specific number of times.
A for loop is used for iterating over a sequence and executing the same set of instructions for each item of the sequence.
The syntax of the for
is the following:
where the iterator is a variable existing only inside the for loop, the sequence is a string, a list, a tuple, a dictionary or a set (we will see those later on) and the instructions are indented.
Info
Try to pick a meaningful name for the iterator variable such as letter
if you go through a word or name
if you go through a list of names.
Examples
This code goes through a word, using the for loop, and prints each letter of the word.
This code goes through a list of name and prints each time the word hello
.
Range Function
If you want to loop a specified number of times, you can use the range()
function as a sequence.
The range()
function returns a sequence of numbers. By default, it starts from 0, increases by 1 and ends at the specified number minus 1.
Examples
range(5)
creates a sequence from 0 to 5 not included and increasing by 1 each time.
range(4, 8)
creates a sequence from 4 to 8 not included and increasing by 1 each time.
range(5, 15, 3)
creates a sequence from 5 to 15 not included and increasing by 3 each time.
range(10, 6, -1)
creates a sequence from 10 to 6 not included and decreasing by 1 each time (increasing by -1).
This code will add all the numbers between 0 and 5 and then print the result (15).