аватар danmodenov@mail.ru · 01.01.1970 03:00

Is there a Switch CASE operator in Python?

n

I faced the fact that it is necessary to implement a multiple condition that in other languages ​​I would implement using the design & nbsp; switch-cse

n

in python, I have to sign everything through Conditions & NBSP; if -elif -else . This seems quite inconvenient to me.

n

is there a more convenient way to recording such conditions?

n

for example, I have units of measurement and depending on the selected I need to retu the corresponding factor:

n
   Def   get_multiplier  ( unit ): n  if  unit ==  'mm' : n  retu   10  **- 3  n  if  unit ==  '' cm ': n  Retu   10  **- 2  n  if  unit ==  'dm' : n  retu   10  **- 1  n  f  unit ==  'm' : n  retu   1  n  if  unit ==  'Km' : n  retu   10  **  3  n  raise  valueroror ( 'undefined unit: {}' .  format  (unit)) n   n 
                        
                    
аватар danmodenov@mail.ru · 01.01.1970 03:00

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: #you can also assign a default value instead of throwing an exception 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: # handling missing meaning in dictionary

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] # you can use the number 1 as a synonym for True

>

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

Latest

Similar