Python – Loops

In general, instructions are executed sequentially: The first statement of a function is executed first, followed by the second, and so on. There may be a situation where you need to execute a block of code several times.

Programming languages provide various control structures that allow for more complicated execution paths.

With a loop statement, we can execute a statement or a group of statements multiple times.

Why do we use loops in Python?

Loops simplify complex problems into simple problems. It allows us to change the program flow so that we don’t have to write the same code over and over again, but rather repeat it a finite number of times. For example, if we need to print the first 10 natural numbers, then instead of using the print statement 10 times, we can print within a loop that runs up to 10 iterations.

Advantages of loops

The advantages of loops in Python are as follows

It allows code to be reusable.
With loops, we don’t have to write the same code over and over again.
With loops, we can loop through elements of data structures (arrays or linked lists).

The following loop statements exist in Python.

Loop StatementDescription
for loopThe for loop is used when we need to execute a piece of code until the given condition is met. The for loop is also called a test loop. It is better to use the for loop when the number of iterations is known in advance.
while loopThe while loop is used in case we do not know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is met. It is also called a pre-checked loop.
do-while loopThe do-while loop continues until a certain condition is met. It is also called a retest loop. It is used when it is necessary to execute the loop at least once (especially in menu-driven programs).