UPD END
To begin with, there is nothing particularly wrong with using the if-elif-else construction.
If desired, you can find several alteatives.
Dictionary usage
A fairly common way to organize a switch-case construction in Python is to use a dictionary. It's easier to show by example:
unit_to_multiplier = { 'mm': 10**-3, 'cm': 10**-2, 'dm': 10**-1, 'm': 1, 'km': 10**3}
n>}
In order to, to get the desired multiplier in this case, you only need to take the value by key:
try: mult = unit_to_multiplier['cm']except KeyError as e: raise ValueError('Undefined unit: {}'./span>.format(e.args[0]))
If you firmly believe that the meaning will always be present in the dictionary, you can omit the try-except block and be prepared to catch the exception elsewhere.
Some variation of this approach would be to pre-check the value in the condition:
if unit in unit_to_multiplier: mult = unit_to_multiplier[unit]else:
Accepted in Python using an approach that sounds something like this: "it's better to try and get an error than to ask for permission every time," therefore, using exceptions is more preferable.
If you want to use the default value in case the key is missing, it is convenient to use theget method:
mult = unit_to_multiplier.get('ultra-meter', 0)
de>
If you need a dictionary only once, you can combine these expressions into one:
unit_to_multiplier = { 'mm': 10**-3, 'cm': 10**-2, 'dm': 10**-1, 'm': 1, 'km': 10**3}.get('km', 0)
umber">0)
The possibilities of this approach do not end there. You can use conditional expressions as dictionary keys.:
def/span> get_temp_descriptionription(temp): retu { temp< -20: 'Cold', -20; 0: 'ring">'Cool', 0 15: 'Chilly', 15 <= temp < 25: 'Heat', 25 <= temp: 'Hot' }[True]
l">True]
This dictionary, after calculation, will have two keysTrue and False. We are interested in the True key. Be careful that the conditions do not overlap!
Such dictionaries can check any property, for example, type ():
selector = { type(x) == str">str : "it's a str", type(x) == tuple: "it's a tuple", typen">type(x) == dict : "it's a dict"}[1]
>
If more complex actions are necessary, store the function as a value for each key:
import operatoroperations = { '+': operator.add, '*': lambda x, y: x * y, }defd">def calc(operation, a, b): retu operations[operation](a, b)
Be careful when using a dictionary with functions - make sure that you do not call these functions inside the dictionary