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

 

Leave a Reply

Your email address will not be published. Required fields are marked *