Python Forum

Full Version: switch case with range
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm new to python and working on some homework.

def letter(i):
    switcher={
            0:'a',
            1:'b',
            2:'c'
            }
    return switcher.get(i,"Invalid")
Output:
letter(0) -> 'a' letter(2) -> 'c' letter(3) -> 'Invalid'
Can I use a range in the case#? something like below, I tried different ways but didn't work.
            0:'a',
            1:'b',
         2..5:'c'
I also tried

range(2,5):'c' 


didn't work.

Is there easy way to do that?

Thanks,
It seems that you are using Python 2.x, since range(2, 5) isn't hashable and doesn't work.
Switch to Python 3.x (better), or use xrange instead.
(Feb-26-2019, 11:04 PM)scidam Wrote: [ -> ]It seems that you are using Python 2.x, since range(2, 5) isn't hashable and doesn't work.
Switch to Python 3.x (better), or use xrange instead.

That won't work, because 3 != range(2, 5).

To OP, if you want that to work, you have to put all of the numbers in the dictionary. Those are keys to a hash map, not a switch statement. I would just code that with if/elif:

if i == 0:
   return 'a'
elif i == 1:
   return 'b'
elif 2 <= i < 5:
   return 'c'
Only in a much more complicated case would I use a dictionary (or maybe a list or string), but as I said, you would have to put every 'case' in as a separate key.
Sorry for misleading, I just pointed out that range could be a key of a dictionary in python 3.x.