For Loop & Nested Loops
For Loop & Nested Loops
A for loop in Python is a control flow statement that is used to iterate over a sequence (such as a
list, tuple, string, or range) or other iterable objects. It allows you to execute a block of code
multiple times with each iteration. The basic syntax of a for loop in Python is as follows:
✔ element: This is a variable that takes on the value of each item in the iterable one by
Here is a typical use of the for loop. We want to print the balance of our savings account over a
period of years, as shown in this table:
Output:
apple
banana
cherry
You can also use the range function to generate a sequence of numbers and iterate over them.
python
for i in range(5): # This will loop from 0 to 4 (5 times)
print(i)
Output:
0
1
2
3
4
● You can use the break statement to exit a for loop prematurely.
python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 4:
break
print(num)
Output:
1
2
3
● The continue statement is used to skip the current iteration and move to the next one.
python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue
print(num)
Output:
1
2
4
5
These are the basics of using for loops in Python. They are versatile and commonly used for
various tasks like data processing, list manipulation, and more
Similarly, complex iterations sometimes require multiple or nested loops (a loop inside another
loop statement). When processing tables, nested loops occur naturally. An outer loop iterates
over all rows of the table. An inner loop deals with the columns in the current row.
In this section you will see how to print a table. For simplicity, we will print the powers of x, x n,
as in the table at right. Here is the pseudocode for printing the table:
How do you print a table row? You need to print a value for
each exponent. This requires a second loop.
For n from 1 to 4
Print xn
This loop must be placed inside the preceding loop.
We say that the inner loop is nested inside the outer loop.
There are 10 rows in the outer loop. For each x, the program prints four columns in the inner
loop. Thus, a total of 10 × 4 = 40 values are printed.
In this program, we want to show the results of multiple print statements on the same line. This
is achieved by adding the argument end="" to the print function.
Following is the complete program. Note that we also use loops to print the table header.
However, those loops are not nested.