Nested Loop In Python Programming Language

Python Nested Loop

In this tutorial, you will learn about what is Python nested loop and how you can use it in your code?

What is Python Nested Loop?


In Python Programming Language a Nested Loop means we can use one loop inside of another loop you can say it as a loop into a loop.

Recommended:  Basic Operators In Python Programming Language

Nested for Loop Syntax


Below is the syntax of how we use nested if loop.

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.

Recommended:  Variables,Data Types and Type Conversion In Python Programming Language

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

 

Recommended:  Structuring In Python Programming Language

Jack Sparrow

Hay I am Admin Of This Website. I am very passionate about Computers and technology. This website is the result of my passion. I love to eliminate the barriers comes in the for seeking education. This website is the free source of learning about new technology and up to date knowledge.

Leave a Reply

Close Menu