Python Loops

Introduction

In programming we often come across the scenario where we need to execute the block of code or statement several number of times. Here loops come into picture. With the help of looping technique, we can iterate the statements many ties as required.

Python Loops

Fig 1: Flow Diagram

Type of loops

In python we have three different types of loops:

TypesDescription
While loopThe while loop checks for the condition in the beginning. If the condition computed is True, the loop body is executed.

Syntax : while <expression>:

statements

 

For loopThe for loop iterates over the given sequence which stisfies the condition.

Syntax: for <value> in <sequence>:

Statement

 

Nested loopUsing one loop statement inside another loop.

Syntax: for <value> in <sequence>:

If <condition>:

statement

Else:

statement

 

Examples

1.      While loop

 

counter = 0

while (counter < 3):

counter = counter + 1

print(“Line”, counter)

Output:

While loop Output

2.      For loop

 

for val in range(0, 5):

print(val)

Output:

For loop Output

3.      Nested loop

 

n = 10

for val in range(0, n):

if val % 2 == 0:

print(val,’is even number’)

else:

print(val,’is odd number’)

 

Output:

Nested loop

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.