Python Loops

In general, the statement of code is executed in sequence from top to bottom. There may be a situation when you need to execute the same block of code several times. Loops are used for this purpose. A loop is a block of statements that are executed until the condition of the loop are fail. Python provides two types of Loop.

  • while loop
  • for loop

 

while loop

Python also has the standard while-loop which work the same as other programming languages like c++ and Java. Let’s see the example of Python while loop.

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

This produces the following result:

0
1
2
3
4

For loop

In Python, for loop is used to iterating over the list, tuple, dictionary or string.

vehicle_li = ["car","bus","train"]
for e in vehicle_li:
    print(e)

Output:

car
bus
train
>>> dict = {'a':'red','b':'green','c':'blue'}
>>> for key,val in dict.items():
...     print(f"{key} ==> {val}")
... 
a ==> red
b ==> green
c ==> blue

Range

The range() function is used in for loop to iterate the loop with the specified range. The range(n) function return o to n-1 number. It is not including the last number.

Syntax –

range(start, stop, step)

start: Optional. Default is 0. An integer value specifying the start position.
end: Required. An integer value specifying the end position.
step: Optional.default is 1. An integer value specifying the incrementation.

Examples

>>> for e in range(4):         # end = 4
...     print(e)
... 
0
1
2
3
>>> for e in range(2,6):       # start = 2 & end = 6
... print(e)
... 
2
3
4
5
>>> for e in range(2,10,2):    # start = 2 & end = 10 & step = 2
... print(e)
... 
2
4
6
8

.     .     .

The break Statement

The break statement is used to terminate the execution of the loop before it has looped through all the items.

>>> for e in range(5):
...     if(e == 3):
...         break
...     print(e)
... 
0
1
2

The continue Statement

The continue statement used to stop the current iteration and continue with the next iteration.

>>> li = [1,2,3,4,5]
>>> for e in li:
...     if(e == 3):
...          continue
...     print(e)
... 
1
2
4
5

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials