Loops in Python

In this section of the Python tutorial, we will have a look at different loops in Python programming language. Loops repeat a statement(s) until the condition is TRUE. Firstly, it tests the conditions defined in the loop & after that, it executes the body of the loop consisting of the statements.

It keeps running until the condition is TRUE, & if by any chance it keeps running forever than we call such loop as an Infinite Loop.

In such cases, we can have another loop inside a loop that can keep track of the number of repetitions performed by the parent loop & can break the loop accordingly.

Like other programming languages like C, C++ & Java, Python is also having same basics loops.

Types of Loops in Python

for loop

It has the capability to repeat over the items of any continuity, such as a list or a string. If a sequence contains a list of expressions, it is evaluated first.

The first item in the sequence is then assigned to the iterating variable iterating var. Next, execute the statements block. Each item in the list is assigned to iterating var, and the statement(s) block is executed until the whole sequence is exhausted.

Syntax of for loop in Python

for iterating_var in sequence:
   statements(s)

while loop

As long as a given condition is true, it repeatedly executes the statements in the loop.

In Python, all statements indented with the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method for grouping statements.

Syntax of while loop in Python

while expression:
   statement(s)

nested loop

As mentioned above, python allows one loop to be used inside another loop. The following section shows the syntax of the nested loop.

Syntax of nested loop in Python

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Shopping cart