Sep. 27, 2012

How to use For and While Loops in Python

Why Loops?

All programming languages need ways of doing similar things many times,
this is called iteration.

For Loop

The for statement is used to iterate over the elements of a sequence. 

It's traditionally used when you have a piece of code which you want to repeat
n number of time. 

The for loop is often distinguished by an explicit loop counter or loop variable.

For Loop Examples

Let's see how the for loop is working with some examples. 

for counter in range(1, 6):
    print counter

#can also be written like this:

	numbers = range(1,6)
	for count in numbers:
	    print (count)

Output

	
>>output
1
2
3
4
5

Loop through words

Here we use the for loop to loop through the word computer
word = "computer"
for letter in word:
    print letter

Output

c
o
m
p
u
t
e
r   

While Loop

The while loop tells the computer to do something as long as the condition is met. 

Its construct consists of a block of code and a condition. 

The condition is evaluated, and if the condition is true, the code within the
block is executed. 

This repeats until the condition becomes false. 
	
a = 0		
while a < 10:	
   a = a + 1	
   print a

While Loop Example

Here is another example using the while loop. 

This will ask the user for an input. 

The while loop ends when the user types "stop".
while True:
    reply = raw_input('Enter text, [tpye "stop" to quit]: ')
    print reply.lower()
    if reply == 'stop':
        break

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.