5.2 switch and case Statements in Python?

Unfortunately, Python doesn’t currently suport switch-case statements. If you’ve worked with other languages before, you may have encountered switch-case or case-when statements - for instance:

  1. In Ruby…

    number = 4
    
    puts case number 
         when 0...10
         "a"
         when 10...20
         "b"
         when 30...40
         "c"
         default
         "d"
         end
  2. In Go (i.e., Golang)…

    package main 
    
    import "fmt"
    
    var number int = 32
    
    func main() {
      switch number {
        case 10:
          fmt.Println("Hello")
        case 20:
          fmt.Println("20")
        case 30:
          fmt.Println("40")
        default:
          fmt.Println("50")
      }
    }
  3. In C++…

    #include <iostream>
    
    int main() {
      int number = 20;
    
      switch(number) {
      case 10:
        std::cout << 20 << "\n";
      case 20:
        std::cout << 30 << "\n";
      case 30:
        std::cout << 40 << "\n";
      }
      return 0;
    }

However, I do know of one approach that somewhat mimics the above examples via a dictionary like so:

def getChoice(x):
  choices = {
    20 : "thing",
    30 : "test",
    40 : "try"
  }
  return(choices.get(x, "Can't find what you want!"))

print(getChoice(20))

In other words, one could use a function and a dictionary in the manner above. They can then call the .get() method from the dictionary class to return the appropriate value; otherwise, if x is not present inside the dictionary (i.e., the default statements in the above examples) then we return the string "Can't find what you want!".

5.2.1 Why bother with switch-case or case-when statements at all when I have if, elif, and else?

This is a great question.

However, I think there are two points worth noting down about switch-case or case-when statements:

  1. It looks neater

    Here’s an example from something that I made in Ruby3 a little while ago. Here, inputs is a two-dimensional array (i.e., a Python list) of strings that I iterate over using the .each method; depending on what the first character of each item in inputs is, I then do one of four things (you don’t have to know what - this is just an example):

    inputs.each do |i|
      case i[0]
      when '+'
        insert((i[1] + last_sum_result) % MODULO)
      when '-'
        erase((i[1] + last_sum_result) % MODULO)
      when '?'
        puts search((i[1] + last_sum_result) % MODULO) ? "Found" : "Not found"
      when 's'
        res = sum((i[1] + last_sum_result) % MODULO, (i[2] + last_sum_result) % MODULO)
        puts res
        last_sum_result = res % MODULO
      end
    end

    However, I can also do the same thing using Ruby’s if, elsif (i.e., the Ruby equivalent of Python’s elif), and else statement:

    inputs.each do |i|
      if i[0] == '+'
        insert((i[1] + last_sum_result) % MODULO)
      elsif i[0] == '-'
        erase((i[1] + last_sum_result) % MODULO)
      elsif i[0] == '?'
        puts search((i[1] + last_sum_result) % MODULO) ? "Found" : "Not found"
      elsif i[0] == 's'
        res = sum((i[1] + last_sum_result) % MODULO, (i[2] + last_sum_result) % MODULO)
        puts res
        last_sum_result = res % MODULO
      end
    end

    Which is easier to read? I personally think that the second code block is harder even though both code blocks essentially perform the same operations!

  2. In some cases, switch-case or case-when statements are faster

    To my knowledge, a data structure called a jump table is generated when a program is being compiled. While I do not have much knowledge in this area of computer science, I believe that a jump table is akin to a dictionary in Python, albeit it works in constant time (i.e., \(O(1)\) time). Because of this, a switch-case or a case-when statement can be rather fast!

    I suppose one could always look at the following link for more information regarding this: https://mortoray.com/2019/06/29/why-switch-is-better-than-if-else/


  1. Not to worry - Ruby’s syntax is similar enough to Python’s that I think you should have little difficulty understanding the examples!↩︎