Skip to main content

Python Loops

Python programming Loops are used to perform same  process or blocks until a condition is being to reach paticular state. Python programming has two primary concepts in loops For and While. Both loops are used to execute single or multiple block od code until to reach certain condtion.

In this tutorial we will learn about Python programming loops.The For Loop,  Whille loop and Nested loop  to proceed the same process repeatly.

Techtuts provides an example along with concepts. You have to workout the example programs for good and well.

Loops in Python

Python has the following types in Loops.

  1. For Loop
  2. While Loop

For loop

For loop in a Python Programming used to go over the  order/ position of the string or list or tuples or dictionary data types.

Syntax:

for value in values:
    #Block code
else:
    #Else Block code

Example:

>>> strVar = 'TechTuts'
>>> for value in strVar:
...     print(value)
...
T
e
c
h
T
u
t
s
>>>

For Loop with  Else

In a for loop, If you want to  give  message or information to user after ending the loop, If the string/tuples/list/dictionary is an empty,  Then you can use  for loop with else.

Example:

>>> strVar = 'Techtuts'
>>> for value in strVar:
...     print(value)
... else:
...     print('No more items are available')
...
T
e
c
h
t
u
t
s
No more items are available

 

While loop

Where  in a Python Programming used to do run the process process or blocks untl certain conditions is being to reach paticular state.

Syntax:

while <cond>:
    #Block of codes
else:
    #Else Block codes

Example:

>>> count = 0
>>> while count < 5:
...     print(count)
...     count = count+1
...
0
1
2
3
4
>>>

While Loop with  Else

In a while loop, If you want to  give  message or information to user after ending the loop, Then you can use  for loop with else.

Example:

>>> count = 0
>>> while count < 5:
...     print(count)
...     count = count+1
... else:
...     print("No more item")
...
0
1
2
3
4
No more item
>>>

Nested Loop

A loop has another loop within that blocked code  called nested loops

Example:

>>> a = [1,2]
>>> b = [3,4]
>>> for i in a:
...     for j in b:
...             print(i,'+',j,'=',(i+j))
...
1 + 3 = 4
1 + 4 = 5
2 + 3 = 5
2 + 4 = 6
>>>