DEV Community

Discussion on: What's a useful programming language feature or concept that a lot of languages don't have?

Collapse
 
tobiassn profile image
Tobias SN

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

switch(word):
    case(Hello):
        otherWord = World;
        break;
    case(World):
        otherWord = Hello;
        break;
    default:
        otherWord = FooBar;
        break;

is currently

if word == Hello:
    other_word = World
elif word == World:
    other_word = Hello
else:
    other_word = FooBar

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.

Collapse
 
cathodion profile image
Dustin King

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:

    case serial_code
    when /\AC/
      "Low risk"
    when /\AL/
      "Medium risk"
    when /\AX/
      "High risk"
    else
      "Unknown risk"
    end

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.

Collapse
 
tobiassn profile image
Tobias SN

Yeah you’re probably right.

Collapse
 
moin18 profile image
Moinuddin Quadri

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:

def switch(key):
     return {
          'a': 'value_a',
          'b': 'value_b'
    }.get(key, 'value_default')

Sample Run:

>>> 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.

Collapse
 
tobiassn profile image
Tobias SN

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.