Nested Loops in Python

AI SCIENCES
Feb 5, 2023

--

Just like conditional statements, you can nest a loop inside another loop. For instance, in the following example, you have an outer for loop that executes 5 times. You also have an inner for loop that executes 5 times. Hence, the print statement will execute for a total of 5 x 5 = 25 times, as you can see from the output.

Script 1:

for i in range (5):
for j in range (5):
print(i ,"-",j)

Output:

0 - 0
0 - 1
0 - 2
0 - 3
0 - 4
1 - 0
1 - 1
1 - 2
1 - 3
1 - 4
2 - 0
2 - 1
2 - 2
2 - 3
2 - 4
3 - 0
3 - 1
3 - 2
3 - 3
3 - 4
4 - 0
4 - 1
4 - 2
4 - 3
4 - 4

--

--

AI SCIENCES

We are a group of experts, Ph.D. students, and young practitioners of AI and Data Science. Please visit our website www.aisciences.io for more Contents.