Switches and cases. I love them. But when I tried out Python, I was really surprised that it didn’t have them, especially since the C# syntax looks a lot like it could be Python. For example, the Python equivelant of
Maybe it has something to do with having "one way to do it". I never understood the hate for switch/case statements though. It's a little counter-intuitive how they fall through by default in C/C#/C++, but it's still a common thing to want to map a set of possible values to a set of possible actions.
There's another thing I like from Ruby and Lisp: you don't have to explicitly return, you can just have the return value be whatever the last expression was.
If you are doing simple task which involves just one statement, instead of using if-elif in Python, you may implement switch statements more elegantly using dictionary.
>>> switch('a') # 'a' exists as key
'value_a'
>>> switch('z') # 'z' doesn't exists as key
'value_default'
Above function will return "value" function corresponding to "key". If "key" not found in dictionary, it will return value as "default_value", just like default in switch statements.
That's not really a switch statement, but more of a dictionary abstraction. In a real switch, you can run code based on the value. If I were to modify your snippet, I'd have to get busy with functions and stuff.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Switches and cases. I love them. But when I tried out Python, I was really surprised that it didn’t have them, especially since the C# syntax looks a lot like it could be Python. For example, the Python equivelant of
is currently
I know that both PEP 275 and PEP 3103 have been rejected, but I have high hopes that a new one is created and accepted.
Maybe it has something to do with having "one way to do it". I never understood the hate for switch/case statements though. It's a little counter-intuitive how they fall through by default in C/C#/C++, but it's still a common thing to want to map a set of possible values to a set of possible actions.
Or return values! Like in Ruby:
There's another thing I like from Ruby and Lisp: you don't have to explicitly return, you can just have the return value be whatever the last expression was.
Yeah you’re probably right.
If you are doing simple task which involves just one statement, instead of using
if-elif
in Python, you may implement switch statements more elegantly using dictionary.For example:
Sample Run:
Above function will return "value" function corresponding to "key". If "key" not found in dictionary, it will return value as "default_value", just like default in
switch
statements.That's not really a switch statement, but more of a dictionary abstraction. In a real switch, you can run code based on the value. If I were to modify your snippet, I'd have to get busy with functions and stuff.