Pages

Wednesday, July 8, 2015

Python – Loops

Most of the languages provides a way which makes it possible to carry out a sequence of statements repeatedly. The code within the loop, i.e. the code carried out repeatedly is called the body of the loop. 

Python supplies two different kinds of loops: the while loop and for loop. 

For

A simple for construct would like this,

>>> fruits = ["apple","mango","grape"]
>>> for fruit in fruits:
...     print fruit
...
apple
mango
grape

That reads, for every element that we assign the variable fruit, in the list fruits  print out the variable fruit

Other example looks as,

>>> numbers = [1,10,20,30,40]
>>> sum = 0
>>> for number in numbers:
...     sum = sum + number
...     print sum
...
1
11
…..

Break - If we need to break out of the loop ,we can use

>>> for i in range(1,10):
...     if i ==5:
...        break
...     print i
...
1
2
3
4
While
The While loop tells to perform an Operation as long as the condition defined is met. An basic example would look like this,

>>> fruits =  ["apple","mango","banana","grape"," raspberry"]
>>> i = 0
>>> while i < len(fruits):
...     print fruits[i]
...     i = i+1
...
apple
mango
banana
grape
raspberry

Another Example using while and reading Input,

>>> while True:
...     ans  = raw_input("Start Typing...")
...     if ans == "Q":
...             break
...     print "Enter Text was", ans
...
Start Typing...this is While Loop Q
Enter Text was this is While Loop Q

Nested Loops
Both for and while loops allow using Nested loops. Below is an Example,

>>> for x in range(1,11):
...     for y in range(11,1):
...             if x ==y:
...                     break

...             print x,y

No comments :

Post a Comment