How to emulate 'switch' statement in Python

As you may know already, the Python language does not contain conditional statements for making a choice, that depends on the name of some varialbe (better known to C\C++, Java and other C-like programmers as "switch" statements). But there is the way to implement them in Python too. Of course, you always can use if-elif-else statements. But! Python already has as it's core type such a wonderfull type as Dictionary. So, example is below:
C-style
int violet = 1;

color = 1;
switch(color){
  case 0: 
    printf("Roses are red\n");
    break;
   case 1:
     printf("Violets are blue\n");
     break;
   default:
      printf("So, I do love you!\n");
}
python-style:

flowers = {0 : 'red', 1 : 'violet'}
color_number = input('Enter your color number')
color = flowers[color_number]
if flowers.get(color, 0) == 'red':
  print('Roses are red', end='')
elif flowers.get(color,0) == 'violet':
  print('Violets are blue', end='')
else:
  print('So, I do love you!')

0 comments:

Post a Comment