Making Case Statements In Python
So I am trying to make a case statement for my python script to make it cleaner but there's no such thing (as far as I'm aware) so I have just made a bunch of if/else statements. I
Solution 1:
At a high level, python suggests that you try and use dictionaries for this kind of thing. I won't try and translate your example, since it's a little verbose, but essentially instead of using a case statement like so:
function(argument){
switch(argument) {
case0:
return"zero";
case1:
return"one";
case2:
return"two";
default:
return"nothing";
};
};
You can use a dictionary of possibilities like so
def numbers_to_strings(argument):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(argument, "nothing")
You could also create a switcher class, and map your actions to your conditions. Overall the python way is to increase legibility.
Post a Comment for "Making Case Statements In Python"