Python Loops

Instead of writing the same code multiple times we use loop statement to execute group of statements several times. The loop statement will execute until satisfying the given condition.

Python provides the following types of loops,

while loop

While loop will execute a block of statement repeatedly until the given condition satisfies. The while loop consists of a condition block and it will keep on executing the statement until the condition becomes false.

Syntax:

``````while expression:
statement``````

Example:

``````i = 0
while i < 5:
print(i, "is less than 5")
i = i + 1
``````

Output:

``````0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5``````

else Statement

The else statement will execute when the while condition becomes false.

Example:

``````i = 0
while i < 5:
print(i, "is less than 5")
i = i + 1
else:
print(i, "is greater than 5")``````

Output:

``````0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is greater than 5``````

break Statement

The break statement is used to stop the while loop even if the condition is true.

Example:

``````i = 0
while i < 10:
print(i, "is less than 10")
if i == 5:
break
i = i + 1``````

Output:

``````0 is less than 10
1 is less than 10
2 is less than 10
3 is less than 10
4 is less than 10
5 is less than 10``````

continue Statement

The continue statement is used to skip the current iteration, and continue with the next.

Example:

``````i = 0
while i < 5:
i = i + 1
if i == 2:
continue
print(i)``````

Output:

``````1
3
4
5``````

for loop

for loop is used to execute a set of statements each item in the sequence, that is either a list, a Dictionary, a set or a string.

Syntax:

``````for iterating_var in sequence:
statements``````

Example:

``````num = [1, 2, 3, 4, 5, 6, 7]
for i in num:
print(i)``````

Output:

``````1
2
3
4
5
6
7``````

range() Function

Range function returns a sequence of numbers it starts with o and increase by 1 until the special number is reached.

Example:

``````for i in range(5):
print(i)``````

Output:

``````0
1
2
3
4``````

Nested loops

Python allow us to use one loop inside another loop.

Nested for loop

The general syntax for for loop is,

Syntax:

``````for iterating_var in sequence:
for iterating_var in sequence:
statements
statements``````

Example:

``````for i in range(1, 8):
for j in range(i):
print("#",end=' ')
print()``````

Output:

``````#
# #
# # #
# # # #
# # # # #
# # # # # #
# # # # # # #``````

Nested while loop

The general syntax for nested while loop is,

Syntax:

``````while expression:
while expression:
statement
statement``````

Example:

``````a = 1
while(a <= 2):
b = 1
while(b <= 2):
print(b)
b = b+1
print("\n")
a = a + 1``````

Output:

``````1
2

1
2``````