Chapter 3: Control of Flow and Logical Expressions

Example 3.1, page no. 82

In [1]:
i = -10;

while(i <= 5):
    print "value of i is %d " %( i)
    print "i == 0 = %d " %( i==0 )
    print "i > -5 = %d\n "  %(i > -5)
    i+=1
value of i is -10 
i == 0 = 0 
i > -5 = 0
 
value of i is -9 
i == 0 = 0 
i > -5 = 0
 
value of i is -8 
i == 0 = 0 
i > -5 = 0
 
value of i is -7 
i == 0 = 0 
i > -5 = 0
 
value of i is -6 
i == 0 = 0 
i > -5 = 0
 
value of i is -5 
i == 0 = 0 
i > -5 = 0
 
value of i is -4 
i == 0 = 0 
i > -5 = 1
 
value of i is -3 
i == 0 = 0 
i > -5 = 1
 
value of i is -2 
i == 0 = 0 
i > -5 = 1
 
value of i is -1 
i == 0 = 0 
i > -5 = 1
 
value of i is 0 
i == 0 = 1 
i > -5 = 1
 
value of i is 1 
i == 0 = 0 
i > -5 = 1
 
value of i is 2 
i == 0 = 0 
i > -5 = 1
 
value of i is 3 
i == 0 = 0 
i > -5 = 1
 
value of i is 4 
i == 0 = 0 
i > -5 = 1
 
value of i is 5 
i == 0 = 0 
i > -5 = 1
 

Example 3.2, page no. 86

In [2]:
s = raw_input("Enter String.. : ")
print s
Enter String.. : python
python

Example 3.3, page no. 87

In [3]:
i = 0
for i in range(11):
    print i
0
1
2
3
4
5
6
7
8
9
10

Example 3.4, page no. 88

In [4]:
i=0
while(i<=10):
    print "%d \n" %i
    i += 1

for i in range(11):
    print "%d \n" %i
0 

1 

2 

3 

4 

5 

6 

7 

8 

9 

10 

0 

1 

2 

3 

4 

5 

6 

7 

8 

9 

10 

Example 3.5 & 3.6, page no. 90-91

In [5]:
for i in range(11):
    if i==1 or i==2:
        print "1 or 2\n"
    elif i==7:
        print "7\n"
    else:
        print "default\n"
default

1 or 2

1 or 2

default

default

default

default

7

default

default

default

Example 3.7, page no. 92

In [6]:
for i in range(-10,11):
    if(i == 0):
        continue;
    print "%f\n" % (15.0/i)
-1.500000

-1.666667

-1.875000

-2.142857

-2.500000

-3.000000

-3.750000

-5.000000

-7.500000

-15.000000

15.000000

7.500000

5.000000

3.750000

3.000000

2.500000

2.142857

1.875000

1.666667

1.500000

Example 3.9, page no. 98

In [7]:
'''
This example demonstrates ?: operator in the textbook.
There isin't a ?: operator in python. Instead we have [value1,value2][condition] 
operator.
'''


for i in range(11):
    print ["odd\n","Even\n"][i&1]
odd

Even

odd

Even

odd

Even

odd

Even

odd

Even

odd

Example 3.10, page no. 99

In [8]:
for i in range(11):
    print "i %d j %d\n" %( i,i*i)
i 0 j 0

i 1 j 1

i 2 j 4

i 3 j 9

i 4 j 16

i 5 j 25

i 6 j 36

i 7 j 49

i 8 j 64

i 9 j 81

i 10 j 100