Avatar ·

Is there a switch case operator in Python?

📁 Advanced Python Topics, question, Help, project

I've encountered a need to implement multiple conditions, which in other languages I would implement using a switch-case construct.

In Python, I have to write everything using if-elif-else conditions. This seems quite inconvenient to me.

Is there a more convenient way to write such conditions?

For example, I have units of measurement and depending on the selected one, I need to return the corresponding multiplier:

def get_multiplier(unit):
    if unit == 

                    
                
Avatar ·

UPD END

To begin with, there is nothing particularly bad about using the if-elif-else construct.

If you wish, you can find several alternatives.


Using dictionaries

A fairly common way to implement a switch-case construct in Python is to use a dictionary. It's easier to show with an example:

unit_to_multiplier = {    'mm': 10**-3,    'cm': 10**-2,    'dm': 10**-1,    'm': 1,    'km': 10**3}

Log in to leave an answer

Blogs