For Loop


In [2]:
l = [1,2,'Hi',20]  # initialize a list

In [3]:
# loop on every element in the list 
for item in l:
    print 'item is {x}'.format(x = item)


item is 1
item is 2
item is Hi
item is 20

In [4]:
# loop over the length of the list
for item in l:
    print 'Hello'


Hello
Hello
Hello
Hello

In [5]:
l = [1,2,3,4,5,6,7,8,9]
for item in l:
    if (item % 2) == 0:     # check if it's divisible by 2 or not
        print '{x} is even'.format(x = item)
    else:
        print '{x} is odd'.format(x = item)


1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd

In [27]:
s = 'Hello Bio 2018' # initialize a string 
#loop over every charachter of the string 
for letter in s:
    print letter


H
e
l
l
o
 
B
i
o
 
2
0
1
8

In [10]:
t = (1,2,3,4) #initialize a tuple 
# loop over elements of the tuples 
for item in t:
    print item


1
2
3
4

In [6]:
# list of tuples 
l = [(1,2),(3,9),(5,1)]
# loop over the list of tuples 
for t in l:
    print t


(1, 2)
(3, 9)
(5, 1)

In [14]:
#tuple unpacking 
l = [(1,2),(3,9),(5,1)]
for (t1,t2) in l:
    print t2


2
9
1

In [7]:
# Dictionary looping 
d = {'k1':2,'k2':5,'k3':50}
for item in d:
    print item # looping over the dictionary, prints only the keys


k3
k2
k1

In [17]:
# Dictionary looping 
d = {'k1':2,'k2':5,'k3':50}
#loop over the dictionary as key and value 
for k,v in d.iteritems():
    print v


50
5
2

While Loop


In [29]:
x = 0.0
while x<10.0:
    print x
    x+=1
else:
    print 'Done!!'


0.0
1.0
2.0
3.0
4.0
5.0
6.0
7.0
8.0
9.0
Done!!

Continue, Break


In [8]:
x = 0
y = 1
while y<2:
    
    while x <20:
        x += 1
        if (x/3) == 5:
            print '15 is reached'
            break     # break , breaks from the closest loop 
        else: 
            print x
            continue # continue, continues from the closest loop 
            
    y+=1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 is reached