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:
In Ruby…
= 4 number puts case number when 0...10 "a" when 10...20 "b" when 30...40 "c" default"d" end
In Go (i.e., Golang)…
package main import "fmt" var number int = 32 func main() { switch number { case 10: .Println("Hello") fmtcase 20: .Println("20") fmtcase 30: .Println("40") fmtdefault: .Println("50") fmt} }
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:
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 ininputs
is, I then do one of four things (you don’t have to know what - this is just an example):.each do |i| inputscase i[0] when '+' [1] + last_sum_result) % MODULO) insert((iwhen '-' [1] + last_sum_result) % MODULO) erase((iwhen '?' puts search((i[1] + last_sum_result) % MODULO) ? "Found" : "Not found" when 's' = sum((i[1] + last_sum_result) % MODULO, (i[2] + last_sum_result) % MODULO) res puts res = res % MODULO last_sum_result end end
However, I can also do the same thing using Ruby’s
if
,elsif
(i.e., the Ruby equivalent of Python’selif
), andelse
statement:.each do |i| inputsif i[0] == '+' [1] + last_sum_result) % MODULO) insert((ielsif i[0] == '-' [1] + last_sum_result) % MODULO) erase((ielsif i[0] == '?' puts search((i[1] + last_sum_result) % MODULO) ? "Found" : "Not found" elsif i[0] == 's' = sum((i[1] + last_sum_result) % MODULO, (i[2] + last_sum_result) % MODULO) res puts res = res % MODULO last_sum_result 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!
In some cases,
switch
-case
orcase
-when
statements are fasterTo 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 acase
-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/
Not to worry - Ruby’s syntax is similar enough to Python’s that I think you should have little difficulty understanding the examples!↩︎