<

Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

For and While Loops in Python

Published on
3,434 Points
434 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
0 Comments

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Join & Write a Comment

This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month