<

For and While Loops in Python

Published on
3,924 Points
924 Views
Last Modified:
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 
    ....
    ....

Open in new window


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")

Open in new window


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
>>> 

Open in new window


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!")

Open in new window


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!
>>> 

Open in new window


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')

Open in new window


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
>>> 

Open in new window


Thank you for reading my article. Please feel free to leave me some feedback or to suggest any future topics. Please give my article a thumbs up if you liked it.

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

 
0
Comment
Author:Swadhin Ray
0 Comments

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Join & Write a Comment

Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month