If you are familiar with any number of other programming languages – take C for example – you may wonder what happened to “switch”. The answer is, its SO much easier in Python to implement the same function. To keep it very very simple for a demo, consider testing for an “A” or a “B” in an input of any letter.
In C:
enum letter2Test {A, B, C};
enum letter2Test mynum = B ;
switch (mynum)
{
case A:
printf(“The letter is A”);
break;
case B:
printf(“The letter is B”);
break;
default:
printf(“This is some other letter.”);
break;
}
return 0;
}
In Python, we can use a dictionary or list to replace the function of enum with less code:
letter2Test = {“A”:”A”, “B”:”B”, “C”:”C”}
mytestval = “B”
retval = letter2Test.setdefault(mytestval, “Some other letter.”)
print(“The letter is ” + str(retval))
or maybe…
letter2Test = [“A”, “B”]
mytestval = “C”
if mytestval in letter2Test:
print(letter2Test[letter2Test.index(mytestval)])
else:
print(“This is some other letter.”)