PadhaiTime Logo
Padhai Time

Python Switch Case Behaviour

In our academics, we would have learnt about switch case in either C or C++.

Example:

    int degree = 0;
    switch (degree) {
    case 0:
        printf("high-school");
        break;
    case 1:
        printf("intermediate");
        break;
    case 2:
        printf("graduate");
        break;
    case 3:
        printf("post-graduate");
        break;
    case 4:
        printf("doctorate");
        break;
    default:
        printf("other”);
        break;
    }

 

Bad News!! Python does not support switch case expressions. But we can simulate the same behaviour through an if-elif-else ladder or through a Python dictionary.

Let us just look at both the approaches one by one:

 

1) Switch Case Behaviour in Python using if-elif-else ladder:

We can simply write all the cases in if-elif-else ladder.

Python Code:

def get_education_label(degree):
    if degree == 0:
        return "high-school"
    elif degree == 1:
        return "intermediate"
    elif degree == 2:
        return "graduate"
    elif degree == 3:
        return "post-graduate"
    elif degree == 4:
        return "doctorate"
    else:
        return "other"

print(get_education_label(0))
print(get_education_label(2))
print(get_education_label(6))

Output:

high-school
graduate
other

Same behaviour can be achieved using a Python Dictionary as well.

 

2) Switch Case Behaviour in Python using Python Dictionary:

Here we would create a dictionary having key value pairs corresponding to the given problem statement and for the else case, we need to pass an additional parameter in the get() function. So that if no key matches then default value will be returned by the function. 

Python code:

def get_education_label_dict(degree):
    education_dict = {
         0: "high-school", 
         1: "intermediate", 
         2: "graduate", 
         3: "post-graduate", 
         4: "doctorate"
    }
    return education_dict.get(degree, "other")

print(get_education_label_dict(0))
print(get_education_label_dict(1))
print(get_education_label_dict(2))
print(get_education_label_dict(3))
print(get_education_label_dict(4))
print(get_education_label_dict(6))

Output:

high-school
intermediate
graduate
post-graduate
doctorate
other

It is pretty much easy in Python to replicate the switch case behaviour.

 

Do you know how to handle exceptions occuring in your Python code?

Check out our article on Exception Handling

Bengaluru, India
contact.padhaitime@gmail.com
  • We collect cookies and may share with 3rd party vendors for analytics, advertising and to enhance your experience. You can read more about our cookie policy by clicking on the 'Learn More' Button. By Clicking 'Accept', you agree to use our cookie technology.
    Our Privacy policy can be found by clicking here