Fnu Parshant
4 min readJun 29, 2021


What is a Loop?

A Loop statement is used to execute a piece of code multiple times. There are three types of loop statements in python. They are,

a) For Loop

b) While Loop

c) Nested Loops

While Loop

In python, while loop is used to execute a piece of code until a specific condition is met. Generally, while loop is used when the number of iterations are not known during compilation.

While Loop with Else

We can also use the else statement with while loop. The else statement will be executed immediately after the termination loop when the condition is not satisfied. The else statement won’t be executed when the loop terminates with break or exception is raised.

In addition to the above, We can also use while loop in a single line. It is simple, but it is not recommended as this may lead to an indefinite loop, where the iterations never ends.


**infinite loop**

For Loop

In Python, for loop is used to traverse through Lists, Arrays, Dictionaries, etc., sequentially. Generally, for loop is used when the number of iterations are known during the compilation or traversing an iterable object. Python’s for loop is equivalent to for each loop of other popular languages.

For Loop with Else

Previously we used else with while loop. Similarly, we can also use else with for in loop, which will be executed on successful termination of the loop.

We can also iterate through the iterable with the help of the index, which is very much useful in case of altering the elements in the iterable.

Nested Loops

A Loop statement which when placed within another loop is called a nested loop. Basically, a nested loop consists of an outer loop and an inner loop.

Nested while loop:

Nested for loop: