I'd like to create a switch/case where the cases can have intervals as condition, like:
switch = {
1..<21: do one stuff,
21...31: do another
}
How can I achieve this result?
In Python 3.10 an explicit switch statement was introduced - match
.
Although it doesn't support direct containment checking, so we'll have to exploit the guard feature:
number = int(input("num: "))
match number:
case num if 1 <= num < 21:
# do stuff
case num if 21 <= num < 31:
# do other stuff
case _:
# do default
But at this point it begs the question why not just use an if/elif/else
structure... Up to personal taste.
For earlier versions, as it looks like you already tried, the obvious way of implementing a switch
structure in Python is using a dictionary.
In order to support intervals, you could implement your own dict
class:
class Switch(dict):
def __getitem__(self, item):
for key in self.keys(): # iterate over the intervals
if item in key: # if the argument is in that interval
return super().__getitem__(key) # return its associated value
raise KeyError(item) # if not in any interval, raise KeyError
And now you can use range
s as keys:
switch = Switch({
range(1, 21): 'a',
range(21, 31): 'b'
})
And a few examples:
>>> print(switch[4])
a
>>> print(switch[21])
b
>>> print(switch[0])
KeyError: 0
Another option is to unpack the ranges and save each number of the range individually. Something like:
cases = {range(1, 21): 'a',
range(21, 31): 'b'
}
switch = {num: value for rng, value in cases.items() for num in rng}
The rest works the same.
The difference between the two options is that the first saves memory, but loses the time efficiency of dicts (as you check all the keys), while the second one will maintain the dict's O(1)
look-up at the cost of taking more memory (the contents of all ranges together).
According to your application you can choose between them, as a general rule:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With