Python Nested Loop
In This Python Lesson You’ll Learn:
What is Python Nested Loop?
Nested for Loop Syntax
for test_variable in sequence: for test_variable in sequence: Block of if loop Block of if loop
Nested while Loop Syntax
while test_expression: while test_expression: Block of while loop Block of while loop
Remember: It is not a strict rule that you can only use for loop inside another for loop but you can insert any loop inside of another loop. Means you can insert for loop inside while loop and vice versa.
Example of Nested Loop
#This is an example of nested while loop # The display will be prime numbers. i = 2 while(i < 100): j = 2 while(j <= (i/j)): if not(i%j): break j = j + 1 if (j > i/j) : print i, " is prime" i = i + 1
When the above code executes it shows the following results.
2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime