Chapter Four : Control flow

Example 4.1 page no : 27

In [1]:
numberOfObjects = 42;
a = []
for i in range(numberOfObjects):
    # Recommended
    print  i 
    a.append(i)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

EXAMPLE 4.2 page no :27

In [2]:
numberOfObjects = 42;
a = []
for i in range(numberOfObjects):
    # Recommended
    a.append(i)

print "Enter value: ";
value = int(raw_input())

if value == 1 or value==2:
    print "1 or 2: " , a[value] 
else:
    if (value > 2 and value < numberOfObjects):
        print "Not 1 or 2: " , a[value] 
Enter value: 
10
Not 1 or 2:  10

EXAMPLE 4.3 page no : 28

In [3]:
class Status:
    red = 1
    green = 2

def convertStatus(status):
    if status == Status.red:
        return "Red"
    elif status == Status.green:
        return "Green"
    else: 
        return "Illegal value"        

print convertStatus(1)        
print convertStatus(2)
print convertStatus(5)
Red
Green
Illegal value

EXAMPLE 4.4 page no : 29

In [4]:
m = 10;
errorflag = False;

for i in range(m):
    if (True):
        errorflag = True;
        break; # leaves loop

# no goto needed
if(errorflag):
    pass
In [ ]: