contact@eeehub.in +919470012104

Loops in Python

Normally, the execution of the statements will be one after another. There may be a situation when you need to execute a block of code several number of times.

A loop statement allows us to execute a statement or group of statements multiple times.

Loops in python are below:

  1. while loop
  2. for Loop
  3. Nested loop

while Loop:


Repeats a statement or group of statements while a given condition is True. It tests the condition before executing the loop body. It will execute until the mentioned condition is True. So, you can use while loop where you don't know the number of iteration(repetition of the process).

while expression:
statement(s)

Here, statement(s) may be a single statement or a block of statements with uniform indent.  Indentation in Python - Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a statement. It is the representation of block of codes. Remember in Python we don't have open and close braces for while loop body.



>>> a = 1
>>> while(a <= 10):
... print("Count ",a)
... a +=1
...
Count 1
Count 2
Count 3
Count 4
Count 5
Count 6
Count 7
Count 8
Count 9
Count 10


The Infinite Loop:


A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.


>>> a = 1
>>> while(a <= 10):
... print("Count ",a)
...


For Loop:


for iterating_variable in sequence:
statements(s)

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_variable. Next, the statements block is executed. Each item in the list is assigned to iterating_variable, and the statement(s) block is executed until the entire sequence is exhausted.



>>> a = 0
>>> for a in [1,2,3,4,5]:
... print('Count ',a)
...
Count 1
Count 2
Count 3
Count 4
Count 5


Nested loop:


Python programming language allows the use of one loop inside another loop and that is called nested loop.



for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)


while expression:
while expression:
statement(s)
statement(s)