PYTHON

Loops


Loops are used to repeat a block of code multiple times. Python supports two types of loops:

  • ‘for’ loop
  • ‘while’ loop

 

‘for’ loop

It is the process of iterating over the iterables and implement same set of code or task on every element of iterable.

Syntax:

for variable in sequence:
   # block of code to be executed for each item in the sequence

Example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
   print(fruit)

Output:

apple
banana
cherry
 

 

Using range() with for Loop

The range() function generates a sequence of numbers, which is often used with for loops.

Example:

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

Output:

0
1
2
3
4

 

You can also specify the start, stop, and step values with range():

Example:

for i in range(2, 10, 2):
  print(i)


Output:

2
4
6
8

 

 

‘while’ loop

The while loop in Python is used to repeat a block of code as long as a condition is true.

Syntax:

while condition:
   # block of code to be executed as long as the condition is true

Example:

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

Output:

0
1
2
3
4
 

 

'break' and ‘continue’ Statements

 

'break' Statement:

break keyword breaks the loop when given condition become true else it will continue to iter in the given iterable.

Example:

for i in range(10):
   if i == 5:
       break
   print(i)

Output:

0
1
2
3
4
 

 

'continue' Statement:

Continue keyword continue the iteration till the end of the iterable, even applied condition may return false.

Example:

for i in range(10):
   if i == 5:
       continue
   print(i)

Output:

0
1
2
3
4
6
7
8
9
 

 

Nested Loops

You can nest loops inside other loops, meaning you can have a loop inside the body of another loop.

Example:

for i in range(3):
   for j in range(2):
       print(f"i = {i}, j = {j}")

Output:

i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
 

PYTHON