For Loop
The next type of loop in Python is the for
loop, which allows us to repeatedly execute a block of code for each element in an array. The for
loop is often used when we know how many times we want to perform an operation or when we want to iterate through all elements in a sequence. On the other hand, the while
loop is used when we do not know how many times we need to repeat the loop.
The structure of a for
loop looks like this:
for element in array: # For each element in the array
# Block of code to be executed for each element
element
is a variable that holds the value of the element corresponding to the iteration of the loop. Practically speaking, during the first iteration of the loop, element
is the first element of the array. During the second iteration of the loop, element
is the second element of the array, and so on.
Example: We want to print all the elements in a list:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
# Prints: 1 2 3 4 5
In this example, we go through all the elements in the numbers
list, and for each number, we execute the block of code that prints the number. Step by step:
- The
numbers
variable is set to the array[1, 2, 3, 4, 5]
. - The first iteration of the loop starts, so the
number
variable is set to the first element of the array:1
. - The
number
is printed, so1
is printed. - The second iteration of the loop starts, so the
number
variable is set to the second element of the array:2
. - The
number
is printed, so2
is printed. - This process continues until we reach the end of the array.
It is important to note that number
is just a variable name we came up with. The program would work the same if we replaced number
with x
or any other name:
numbers = [1, 2, 3, 4, 5]
for x in numbers:
print(x)
# Prints: 1 2 3 4 5
Instructions
Use a for
loop to iterate through the teammates
array and print each value.
Start programming for free
3/8