For and While Loops in Python

When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.

In python there are two types of loops: 

  • While loop
  • For loop

When we want to run or execute a piece of code multiple times sequentially, this requires a “for loop”, but there is another alternative called a “while loop”. The while loop can only be used when a specific condition is met, or to execute the code for n number of times—or without having a stop.

The While Loop

Let us try to understand the logic of the while loop. Let’s say a person hits a target using his bow till all the arrows are used up. In this case, as long as the container has an arrow in it, the person will take the arrow and hit the target using his bow.
Let’s assume the number of arrows in the container is 10. The target can be shot as long as the number of arrows is greater than zero. The final step would be to put the bow down when all the arrows have been shot.  So basically, as long as the arrows are present in the container, the loop of hitting the target using the bow will continue.  The logic of the while loop is: as long as the condition is true the loop continues.
Format of while loop in Python:

while <<expression>>:
    statements 
    ....
    ....

 

The while loop starts with the keyword “while” as shown in the above snippet. In the expression, we can use any condition that we want to make it true till we want the loop to be executed—followed by a colon.  Next, there could be one or more statements, but a tab is required before any statement. There is one important thing we need to keep in mind: if in any case the expression never becomes false, then the while loop will never stop, making it an “infinite loop”. In this case, the program will never end.
Now let us convert the example into a proper Python program. 

no_of_arrows = 10
while no_of_arrows > 0 :
	no_of_arrows = no_of_arrows -1
	print ("Number of arrows left in the container" + str(no_of_arrows))
print ("All arrows in the container is over and while loop completed")

 

Here is the output we get:

 

>>> 
============ RESTART: C:/Users/swadhin.ray/Desktop/While_loop.py ============
Number of arrows left in the container 9
Number of arrows left in the container 8
Number of arrows left in the container 7
Number of arrows left in the container 6
Number of arrows left in the container 5
Number of arrows left in the container 4
Number of arrows left in the container 3
Number of arrows left in the container 2
Number of arrows left in the container 1
Number of arrows left in the container 0
All arrows in the container is over and while loop completed
>>> 

 

The Python program automatically determines the end of the “while” when the Python interpreter finds a statement that is not tabbed. We don’t have to explicitly define it.

 

The For Loop:

When any string or list is iterated in sequence, this requires a for loop.
Here is a simple example to list the letters of a word using a for loop in python.

 

for x in 'apple':
     print ('Lits of letters in apple :',x)
print ("Apple letter over!")

 

The result will be as shown below:

 

============= RESTART: C:/Users/swadhin.ray/Desktop/for_loop.py =============
Lits of letters in apple : a
Lits of letters in apple : p
Lits of letters in apple : p
Lits of letters in apple : l
Lits of letters in apple : e
Apple letter over!
>>> 

 

Now say for example we have a list which has a few names and we want to loop it.

names = ['Ray', 'Mike',  'David']
for j in names:        
   print ( j , ' is a name')

The above code will print the below result or output:

 

============= RESTART: C:/Users/swadhin.ray/Desktop/for_loop.py =============
Ray  is a name
Mike  is a name
David  is a name
>>> 

 

Thank you for reading my blog , the reference is taken from one of my article that was published by Experts-Exchange.

Please feel free to leave me some feedback or to suggest any future topics.

Looking forward to hear from you – Swadhin Ray (Sloba) -( LinkedIn ) ( Twitter )

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s