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.
Fig 1: Flow Diagram
Type of loops
In python we have three different types of loops:
Types | Description |
While loop | The 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 loop | The for loop iterates over the given sequence which stisfies the condition. Syntax: for <value> in <sequence>: Statement
|
Nested loop | Using 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:
2. For loop
for val in range(0, 5):
print(val)
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: