Hour 7: Working with loops

Example 7.1, Page No.106

In [2]:
c=' '
print "Enter a character:\n(Eneter X to exit)"
while (c!='x'):
    c=raw_input()
    print c
print "Out of the while loop. Bye"
Enter a character:
(Eneter X to exit)
H
H
i
i
x
x
Out of the while loop. Bye

Example 7.2, Page No.108

In [5]:
i=65
while (i<72):
    print "The numeric value of ",chr(i)," is ",i
    i=i+1
The numeric value of  A  is  65
The numeric value of  B  is  66
The numeric value of  C  is  67
The numeric value of  D  is  68
The numeric value of  E  is  69
The numeric value of  F  is  70
The numeric value of  G  is  71

Example 7.3, Page No.110

In [9]:
print "Hex(uppercase)       Hex(lowercase)       Decimal"
for i in range (0,16):
    print  "{:01X}                    {:01x}                    {:d}".format(i,i,i)
    i=i+1
Hex(uppercase)       Hex(lowercase)       Decimal
0                    0                    0
1                    1                    1
2                    2                    2
3                    3                    3
4                    4                    4
5                    5                    5
6                    6                    6
7                    7                    7
8                    8                    8
9                    9                    9
A                    a                    10
B                    b                    11
C                    c                    12
D                    d                    13
E                    e                    14
F                    f                    15

Example 7.4, Page No.114

In [2]:
j=8
for i in range(0,8):
    print i,"+",j,"=",i+j
    j=j-1
0 + 8 = 8
1 + 7 = 8
2 + 6 = 8
3 + 5 = 8
4 + 4 = 8
5 + 3 = 8
6 + 2 = 8
7 + 1 = 8

Example 7.5, Page No.115

In [4]:
j=1
for i in range(0,8):
    print j,"-",i,"=",j-i
    j=j+1
1 - 0 = 1
2 - 1 = 1
3 - 2 = 1
4 - 3 = 1
5 - 4 = 1
6 - 5 = 1
7 - 6 = 1
8 - 7 = 1

Example 7.6, Page No.116

In [5]:
for i in range(1,4):
    print "The Start of iteration",i,"of the outer loop"
    for j in range(1,5):
        print "\tIteration",j,"of the inner loop"
    print "The end of iteration",i,"of the outer loop"
The Start of iteration 1 of the outer loop
	Iteration 1 of the inner loop
	Iteration 2 of the inner loop
	Iteration 3 of the inner loop
	Iteration 4 of the inner loop
The end of iteration 1 of the outer loop
The Start of iteration 2 of the outer loop
	Iteration 1 of the inner loop
	Iteration 2 of the inner loop
	Iteration 3 of the inner loop
	Iteration 4 of the inner loop
The end of iteration 2 of the outer loop
The Start of iteration 3 of the outer loop
	Iteration 1 of the inner loop
	Iteration 2 of the inner loop
	Iteration 3 of the inner loop
	Iteration 4 of the inner loop
The end of iteration 3 of the outer loop