switch case with range - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: switch case with range (/thread-16406.html) |
switch case with range - jun - Feb-26-2019 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") 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, RE: switch case with range - scidam - Feb-26-2019 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.
RE: switch case with range - ichabod801 - Feb-27-2019 (Feb-26-2019, 11:04 PM)scidam Wrote: It seems that you are using Python 2.x, since 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. RE: switch case with range - scidam - Feb-27-2019 Sorry for misleading, I just pointed out that range could be a key of a dictionary in python 3.x.
|