Switch Case in Python (original) (raw)

Last Updated : 9 Jun, 2026

Python does not provide a traditional switch-case statement like C++ or Java. However, similar behavior can be achieved using techniques such as dictionary mapping, if-elif-else statements, classes, or the match-case statement introduced in Python 3.10.

Method 1: Using Match-Case (Python 3.10+)

In Python 3.10 and after that, Python will support this by using match in place of switch:

Python `

value = 2

match value: case 1: result = "one" case 2: result = "two" case 3: result = "three" case _: result = "unknown"

print(result)

`

**Explanation:

**Note: It is similar to that of switch cases in C++, Java, etc.

Method 2: Using Dictionary Mapping

Dictionary mapping lets us replace switch-case by mapping keys to values or functions. It makes the code shorter, cleaner, and easier to manage than long if-elif chains.

**Example:

Python `

def one(): return "one"

def two(): return "two"

def three(): return "three"

switcher = { 1: one, 2: two, 3: three }

value = 2 result = switcher.get(value, lambda: "unknown")() print(result)

`

**Explanation:

Method 3: Using If-Elif-Else

The if-else is another method to implement switch case replacement. It is used to determine whether a specific statement or block of statements will be performed or not.

Python `

bike = 'Yamaha'

if bike == 'Hero': print("bike is Hero")

elif bike == "Suzuki": print("bike is Suzuki")

elif bike == "Yamaha": print("bike is Yamaha")

else: print("Please choose correct answer")

`

**Explanation:

Method 4: Using Class Method

In this method, we are using a class to create a switch method inside the switch class in Python.

Python `

class Switch: def case_1(self): return "one"

def case_2(self):
    return "two"

def case_3(self):
    return "three"

def default(self):
    return "unknown"

def switch(self, value):
    # getattr fetches method by name, default → self.default
    return getattr(self, f"case_{value}", self.default)()

obj = Switch() print(obj.switch(2))

`

**Explanation: