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.
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.