Using Switch Structures in Python: Effective Alternatives and Approaches

NUR ARIF
4 min readMay 20, 2023
image source by : https://favtutor.com/blogs/python-switch-case

Switch is a feature that is widely used in several programming languages to adjust program flow based on the value of an expression. However, in the Python programming language, the switch structure is not directly available. There are several alternative and effective approaches to achieve similar results with switch structures. I will explain several approaches that can be used in using the switch structure in Python and analyze the advantages and disadvantages of each of these approaches.

Case Study: Discounting System in E-commerce

Suppose you are building a simple e-commerce system that will give customers discounts based on their total purchases. Here’s an example implementation using a selection structure in Python:

# Input
total_purchase = float(input("Enter your total purchase amount: "))

# Discount calculation
if total_purchase >= 500000:
discount = 0.2 # 20% discount for total purchase above or equal to 500,000
elif total_purchase >= 200000:
discount = 0.1 # 10% discount for total purchase above or equal to 200,000
else:
discount = 0 # No discount for total purchase below 200,000

# Calculate the amount to be paid after the discount
amount_payable = total_purchase - (total_purchase * discount)

# Output
print("Your total purchase amount: ", total_purchase)
print("Discount applied: ", discount * 100, "%")
print("Amount payable after discount: ", amount_payable)

1. Approach Using if-elif-else

The most common approach to replacing the switch structure in Python is to use an if-elif-else structure. In this approach, we use a series of interrelated if-elif-else statements to evaluate the value of the expression and execute the appropriate code block. While this approach is effective, in many cases the code is lengthy and less intuitive.

# Input
total_purchase = float(input("Enter your total purchase: "))

# Calculate discount based on total purchase
if total_purchase == 500000:
discount = 0.2 # If total purchase = 500,000, 20% discount
elif total_purchase == 200000:
discount = 0.1 # If total purchase = 200,000, 10% discount
else:
discount = 0 # Default discount if no matching cases

# Calculate amount payable after discount
amount_payable = total_purchase - (total_purchase * discount)

# Output
print("Your total purchase: ", total_purchase)
print("Discount given: ", discount * 100, "%")
print("Amount payable after discount: ", amount_payable)

2. Approach Using a Dictionary

We can create a dictionary that has the value of an expression as a key and the corresponding function or block of code as a value. Then, we can use the get() method to retrieve the value corresponding to the given key. This approach can provide flexibility and make it easy to add new cases, but requires a little extra work to manage the dictionary.

# Input
total_purchase = float(input("Enter your total purchase amount: "))

# Discount calculation
discount_rates = {
500000: 0.2, # 20% discount for total purchase above or equal to 500,000
200000: 0.1, # 10% discount for total purchase above or equal to 200,000
}

discount = 0 # Default discount

for purchase_amount, discount_rate in discount_rates.items():
if total_purchase >= purchase_amount:
discount = discount_rate
break

# Calculate the amount to be paid after the discount
amount_payable = total_purchase - (total_purchase * discount)

# Output
print("Your total purchase amount: ", total_purchase)
print("Discount applied: ", discount * 100, "%")
print("Amount payable after discount: ", amount_payable)

3. Approach Using Polymorphism

In this approach, we can use the concept of polymorphism in object-oriented programming (OOP) to achieve results similar to switch structures. We can create classes that represent every possible case or expression value, and each class has a method that will be executed when the value of that expression matches. By using polymorphism, we can take advantage of inheritance and dynamic binding to execute code that matches the value of an expression.

class Discount:
def calculate_discount(self, total_purchase):
pass

class NoDiscount(Discount):
def calculate_discount(self, total_purchase):
return 0

class PercentageDiscount(Discount):
def __init__(self, discount_rate):
self.discount_rate = discount_rate

def calculate_discount(self, total_purchase):
return self.discount_rate * total_purchase

class Purchase:
def __init__(self, total_purchase):
self.total_purchase = total_purchase
self.discount = NoDiscount()

def set_discount(self, discount):
self.discount = discount

def calculate_amount_payable(self):
discount_amount = self.discount.calculate_discount(self.total_purchase)
amount_payable = self.total_purchase - discount_amount
return amount_payable

# Input
total_purchase = float(input("Enter your total purchase amount: "))

# Create purchase object
purchase = Purchase(total_purchase)

# Set discount based on purchase amount
if total_purchase >= 500000:
discount = PercentageDiscount(0.2) # 20% discount for total purchase above or equal to 500,000
elif total_purchase >= 200000:
discount = PercentageDiscount(0.1) # 10% discount for total purchase above or equal to 200,000
else:
discount = NoDiscount() # No discount for total purchase below 200,000

purchase.set_discount(discount)

# Calculate the amount to be paid after the discount
amount_payable = purchase.calculate_amount_payable()

# Output
print("Your total purchase amount: ", total_purchase)
print("Discount applied: ", discount.calculate_discount(total_purchase))
print("Amount payable after discount: ", amount_payable)

Conclusion

Although Python does not provide the direct switch structure that some other programming languages provide, Python users can adopt some effective alternative approaches. The if-elif-else approach is the most common and simple approach, but can be less intuitive if there are many cases. The approach using a dictionary provides flexibility and convenience in adding new cases. Meanwhile, the approach using polymorphism utilizes the concept of object-oriented programming and can provide greater flexibility and clarity in managing program logic.

--

--

NUR ARIF

Backend | Data Scraping | Content Writer | Python Programming | Passionate Cyber Security