Python Loops

In a programming language, the loop is nothing but a sequence of instructions that get executed multiple times until a certain condition is reached. In loops, the statement to be executed repeatedly is written only once, but the loop will be executed multiple times. This tutorial focuses on the various Python Loops.

How do loops work?

In Python loops what we do is:

  • Check for the condition.
  • The block of code will be executed as long as the condition is True.
  • Once the condition becomes False, the loop will be exited.

The general flow diagram for Python Loops is:

Python Loops

Types of Python loops

There are two types of Python loops:

Entry controlled loops

The Condition has to be tested before executing the loop body. The Body loop will be executed only if the condition is True.

Examples: for loop, while loop

Exit Controlled loops

Here the loop body will be executed first before testing the condition. The loop body will be executed at least once irrespective of the condition.

Example: do-while loop.

Note: Python doesn’t have a do-while loop.

Why do we need to use loops in Python?

Loops reduce the redundant code. Consider a scenario, where you have to print the numbers from 1 to 10. There are two possibilities:

  • Use 10 print statements to print the even numbers.
  • Single print statement inside a loop that runs for 10 iterations.

Using loops seems to be the better option right? We can use loops, not only to execute a block of code multiple times but also to traverse the elements of data structures in Python.

Examples

  • Print numbers from 1 to 10.
i=1
while(i<11):
    print(i)
    i+=1
1
2
3
4
5
6
7
8
9
10
  • Traverse the elements of a list.
l=[1,2,'a']
for i in l:
    print(i)
1
2
a

Python Loops

Here are the loops in Python:

for loop

We use for loop when we number of iteration beforehand.

Syntax:

for iteration_variable in sequence:
    loop body

Example

# Example 1
for i in range(5):
    print(i)

# Example 2:
t=(1,2,3)
for i in t:
    print(i)

To know more about for loop, click here.

while loop

We use while loop when we don’t know the number of iterations in advance. The loop body gets executed as long as the condition is True.

 Syntax:

while condition:
    loop body

Example

i=0
while(i<5):
    print(i)
    i+=1

To know more about while loop, click here.

Reference

Translate »