Python- Nested loop
This was one of the reasons to start writing this blog. Forcing myself to learn, the nested loop was one of the extra exercises in my lesson that I gave up on. So let’s try to learn.
Nested loops can be used to create patterns in python. In this we will make a US flag(which was my exercise for GeoPython course).
Python programming language allows to use one loop inside another loop. The outer loop can contain more than one inner loop. There is no limitation on the chaining of loops.
Nested loops are typically used for working with multidimensional data structures, such as printing two-dimensional arrays, and iterating a list that contains a nested list.
- Multiplication table
To print the multiplication table, we use a nested loop.
In the outer loop to call the first 5 numbers the range has to start from 1 and end in 6. So total number of iteration of the outer loop is 5.
In the inner loop is for each iteration of the outer loop, the inner loop will execute it ten times. In each iteration of an inner loop, we calculated the multiplication of two numbers. Thus we get the multiplication table up to 5.
Here the print function is used with a parameter called end, the value of this parameter is ‘\n’, i.e. the new line character. This will print each multiplication table in a single line.
for i in range(1, 6):
for j in range(1, 11):
print(i * j, end= " ")
print()1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
- Print pattern
In this program, the outer loop is the number of rows print.
Get GIS-ish’s stories in your inbox
Join Medium for free to get updates from this writer.
Next, the inner loop is the total number of columns in each row.
For each iteration of the outer loop, the columns count gets incremented by 1.
In each iteration of an inner loop, for the first 3 rows the condition will vary from the remaining 2 rows.
The first 3 rows will print star up to the 7th column then it will print the line.
line = "-"
star = "*"
flag =''for x in range(5):
for i in range(19):
if x < 3:
if i < 7:
flag = flag + star
else:
flag = flag + line
else:
flag = flag + line
flag = flag + "\n"print(flag)*******------------
*******------------
*******------------
-------------------
-------------------
For more information, please have a look at the sites linked below.







