Skip to content

Demystifying Switch Case Logic in Python

Have you ever wanted to execute different blocks of code based on variable values? For example, displaying unique messages whether a user selects "1", "2", or "3" from a menu? This is where switch case logic comes in handy!

Switch case statements allow code to take different paths programmatically based on matching variable values. Languages like JavaScript, Java, and C# have built-in switch/case functionality, but it was excluded from Python.

In this comprehensive guide, I‘ll walk through what switch case is, why Python omits it, and three simple techniques you can use to emulate such functionality in Python today. Time to demystify switch case logic once and for all!

What Exactly is Switch Case?

Switch statements have been around since ALGOL in the 1960s and ALGOL-like languages. The concept allows you to easily execute conditional code based on predefined "cases" – essentially an alternative to chaining multiple if/else statements together.

Here‘s what switch case logic looks like in JavaScript:

let food = "apple";

switch(food) {
  case ‘orange‘:
    console.log(‘Oranges are $0.59 a pound.‘);
    break;
  case ‘apple‘:
    console.log(‘Apples are $0.32 a pound.‘);
    break;
  default:
    console.log(‘Sorry, we don\‘t have ‘ + food + ‘.‘);
}

// Prints "Apples are $0.32 a pound."

The switch expression (food) gets evaluated once. The value of food then gets compared to the cases (orange, apple, etc) defined inside the block. If there‘s a match, that case‘s code runs! Pretty useful for conditionally executing code programatically.

The default case runs if none match. After a matching case hits the break keyword, the entire switch block stops executing.

Make sense? Now let‘s see why Python forces us to be a little more creative…

Python‘s Stance on Leaving Out Switch

Switch case might seem essential, but Python creator Guido van Rossum intentionally excluded it from the language syntax.

In his own words:

"I could never understand why so many programmers were fanatic about switch. IMHO if/elif beats switch in most situations by a fair margin. The only good thing about switch is that it generates compact jump tables, but that only affects performance in the rare cases where the condition actually provides decent branch prediction… So I never missed switch, and I think leaving it out of Python was a good design choice."

The philosophy here is favoring explicit, readable code over terseness – even if that means a few more lines! While debatable, switch logic can be simulated in Python without too much overhead once you know the right techniques.

Let‘s explore three easy ways to achieve switch case functionality in Python today…

Technique 1: If, Elif, Else Statements

The most straightforward way to implement switch case logic is by chaining if, elif, and else statements together:

food = "apple"

if food == "orange":
  print("Oranges are $0.59 a pound.")  
elif food == "apple":
  print("Apples are $0.32 a pound.")
else:
  print("Sorry, we don‘t have " + food)

Here we simply check food against a series of cases. The block under the first matching elif runs, simulating our switch case! Default logic can go in the else statement.

Pros

  • Very readable approach
  • Easy to write and expand cases

Cons

  • More verbose with many cases
  • Unable to lookup values from case inputs

While if/elif/else works great, let‘s explore some more dynamic implementations…

Technique 2: Dictionary Mapping

For simplicity, maps, hashes, or dictionaries are commonly used in many languages to pair input keys with output values. Here is an example in Python:

def food_switch(food):
   meal_costs = {
      "orange": 0.59,
      "apple": 0.32
   }

   cost = meal_costs.get(food)
   if cost:
      print(food + "s cost $" + str(cost) + " per pound.")
   else:
      print("Sorry, we don‘t sell " + food)

food_switch("apple")
# Prints "apples cost $0.32 per pound."  

The meal_costs dictionary maps food items to per-pound costs. Our switch_case function takes the food argument, and prints the corresponding price if the food exists as a key in meal_costs. Much cleaner than multiple if/elifs!

Let‘s compare pros and cons:

Pros

  • Map input values directly to outputs
  • Concise way to handle many cases
  • Faster lookup than conditional chains

Cons

  • Still verbose compared to built-in switch
  • Have to handle defaults manually

While the dictionary method improves upon if/elif/else, experienced Pythonistas may desire a more rigid switch class…

Technique 3: Custom Switch Class

For the ultimate in extensibility, you can build your own Switch style class in Python:

class FoodSwitch:
   def switch(food):
      methods = {
         "orange": self.get_orange_price,
         "apple": self.get_apple_price   
      }

      method = methods.get(food.lower(), self.invalid)
      return method()

   def get_orange_price():
      return "0.59"
   def get_apple_price(): 
      return "0.32"
   def invalid():
      return "Sorry, we don‘t sell " + food

switcher = FoodSwitch()
price = switcher.switch("Orange") # 0.59

Here we map cases to class methods dynamically by name, avoiding conditional chains. Create new cases as additional methods!

Pros:

  • Extremely extensible
  • Mimics native switch classes
  • Easy to add new cases

Cons:

  • More complex implementation

Now that you‘ve seen techniques ranging from simple to advanced – let‘s recap when each approach makes sense…

When to Use Each Switch Technique

If/elif/else is great for smaller use cases with minimal cases. Easy to write and read.

Dictionaries make sense when directly mapping input values to outputs, avoiding conditionals. Cleaner with more cases to check.

A custom switch class shines for advanced use cases with frequent case changes. Ultimate flexibility!

Now you‘re equipped to implement switch logic in Python for virtually any situation. I encourage trying all options on your next control flow scenario to grow your skills.

Let me know if you have any other questions!