Python Forum
switch case with range
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
switch case with range
#1
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,
Reply
#2
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.
Reply
#3
(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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
Sorry for misleading, I just pointed out that range could be a key of a dictionary in python 3.x.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020