Nested Loops in Python

Python programming language allows to use one loop inside another loop which is called nested loop. Following section shows few examples to illustrate the concept. 

Nested Loops Syntax:

for iterator_var in sequence:
   for iterator_var in sequence:
       statements(s)
   statements(s)

The syntax for a nested while loop statement in the Python programming language is as follows: 

while expression:
   while expression: 
       statement(s)
   statement(s)

A final note on loop nesting is that we can put any type of loop inside of any other type of loops in Python. For example, a for loop can be inside a while loop or vice versa.

Example: This Python code uses nested for' loops to create a triangular pattern of numbers. It iterates from 1 to 4 and, in each iteration, prints the current number multiple times based on the iteration number. The result is a pyramid-like pattern of numbers.

Python3
from __future__ import print_function
for i in range(1, 5):
    for j in range(i):
        print(i, end=' ')
    print()

Output
1 
2 2 
3 3 3 
4 4 4 4 

Loops in Python – For, While and Nested Loops

Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp – For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops.

While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time. In this article, we will look at Python loops and understand their working with the help of examples.

Similar Reads

While Loop in Python

In Python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed....

For Loop in Python

For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is “for in” loop which is similar to foreach loop in other languages. Let us learn how to use for loops in Python for sequential traversals with examples....

Nested Loops in Python

Python programming language allows to use one loop inside another loop which is called nested loop. Following section shows few examples to illustrate the concept....

Loop Control Statements

Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements....

How for loop in Python works internally?

Before proceeding to this section, you should have a prior understanding of Python Iterators....