# CHAPTER 4: THE CASE CONTROL STRUCTURE¶

## EXAMPLE ON PAGE:126¶

In [1]:

i=2
def switch(i):
return {True: 'I am in default\n',                  #default case
i==1: 'I am in case1\n',
i==2: 'I am in case2\n',
i==3: 'I am in case3\n',
}[True]
print switch(i)

I am in case2



## EXAMPLE ON PAGE:128¶

In [2]:

i=22
def switch(i):
return{True: 'I am in default\n',
i==121: 'I am in case 121\n',
i==7: 'I am in case 7\n',
i==22: 'I am in case 22\n',
}[True]
print switch(i)

I am in case 22



## EXAMPLE ON PAGE:128-129¶

In [3]:

c='x'
def switch(c):
return {True: 'I am in default\n',
c=='v': 'I am in case v\n',
c=='a': 'I am in case a\n',
c=='x': 'I am in case x\n',
}[True]
print switch(c)

I am in case x



## EXAMPLE ON PAGE:129-130¶

In [6]:

print "Enter any one of the alphabets a,b,or c"
ch=raw_input()
def casea():
print ""
def caseb():
print ""
def casec():
print ""
def switch(ch):
return {True: 'wish you knew what are alphabets\n',
ch=='a' or ch=='A': 'a as in ashar\n',
ch=='b' or ch=='B': 'b as in brain\n',
ch=='c' or ch=='C': 'c as in cookie\n',
}[True]
print switch(ch)

Enter any one of the alphabets a,b,or c
B
b as in brain



## EXAMPLE ON PAGE:130¶

In [10]:

print "Enter value of i"
i=eval(raw_input())
def switch(i):
print "Hello\n"                              #It's python,not C :)
try:
return {1: a,
2: b,
}[i]()
except:
print "wrong choice"                     #print message in default case
def a():
j=10
print j                                      #print j as 10 if i=1
def b():
j=20
print j                                      #print j as 20 if i=2
switch(i)

Enter value of i
1
Hello

10


## EXAMPLE ON PAGE:133¶

In [11]:

import sys
print "Enter the number of goals scored against india"
goals=eval(raw_input())
if goals<=5:
print "To err is human!\n"
else:
print "About time soccer players learnt C\n"
print "and said goodbye! adieu! to soccer\n"

Enter the number of goals scored against india
7
About time soccer players learnt C

and said goodbye! adieu! to soccer



## EXAMPLE ON PAGE:134-135¶

In [12]:

for i in range(1,4,1):
for j in range(1,4,1):
for k in range(1,4,1):
if (i==3 and j==3 and k==3):
print "Out of the loop at last!\n"
else:
print "%d %d %d\n" % (i,j,k)

1 1 1

1 1 2

1 1 3

1 2 1

1 2 2

1 2 3

1 3 1

1 3 2

1 3 3

2 1 1

2 1 2

2 1 3

2 2 1

2 2 2

2 2 3

2 3 1

2 3 2

2 3 3

3 1 1

3 1 2

3 1 3

3 2 1

3 2 2

3 2 3

3 3 1

3 3 2

Out of the loop at last!