Chapter 6: Decision Making & Branching

example 6.1, page no. 84

In [2]:
weight = [45.0, 55.0, 47.0, 51.0, 54.0]
height = [176.5, 174.2, 168.0, 170.7, 169.0]
count = 0
count1 = 0
for i in range(0, 5):
    if(weight[i]<50.0 and height[i]>170.0):
        count1 += 1
    count += 1
count2 = count - count1
print "Number of persons with..."
print "Weight<50 and height>170  = ", count1
print "Others = ", count2
Number of persons with...
Weight<50 and height>170  =  1
Others =  4

example 6.2, page no. 86

In [3]:
number = [50, 65, 56, 71, 81]
even = 0
odd = 0
for i in range(0, len(number)):
    if(number[i] % 2 == 0):
        even += 1
    else:
        odd += 1
print "Even numbers = ", even, "Odd Numbers = ", odd
Even numbers =  2 Odd Numbers =  3

example 6.3, page no. 89

In [4]:
a = 325
b = 712
c = 478

print "Largets value is ",
if a > b:
    if a > c:
        print a
    else:
        print c
else:
    if c > b:
        print c
    else:
        print b
Largets value is  712

example 6.4, page no. 92

In [5]:
rollnumber = [111, 222, 333, 444]
marks = [81, 75, 43, 58]
for i in range(0, len(rollnumber)):
    if marks[i] > 79:
        print rollnumber[i], "Honours"
    elif marks[i] > 59:
        print rollnumber[i], "I Division"
    elif marks[i] > 49:
        print rollnumber[i], "II Division"
    else:
        print rollnumber[i], "Fail"
111 Honours
222 I Division
333 Fail
444 II Division

example 6.5, page no. 96

In [6]:
#there is switch() statement in python, we will use if...else instead

print "Select your choice: "
print "M --> Madras"
print "B --> Bombay"
print "C --> Calcutta"
print "Choice --> ",
choice = raw_input()
if choice == "M" or choice == "m":
    print "Madras: Booklet 5"
elif choice == "B" or choice == "b":
    print "Bombay: Booklet 9"
elif choice == "C" or choice == "c":
    print "Calcutta: Booklet 15"
else:
    print "Invalid Choice (IC)"
Select your choice: 
M --> Madras
B --> Bombay
C --> Calcutta
Choice --> m
 Madras: Booklet 5