In python the equivalent to switch case in other languages is match:
current_mode = 2
match (current_mode):
case 1:
print("Do something A")
case 2:
print("Do something B")
case 3:
print("Do something C")
case _: #<<<<This is the equivalent of "default:" (_ is a wildcard)
print("Unknown")
break
There is no break in Python for match. break is only used for loops.
If you want to achieve being able to break from a match case early you can use an exception trick like this:
current_mode = 2
try:
match (current_mode):
case 1:
print("Do something A")
case 2:
print("Do something B1")
raise GeneratorExit("") #We can use a specific error type like 'GeneratorExit' so we can trap it seperatly from actual errors we may want to handle
print("Do something B2")
case 3:
print("Do something C")
case _:
print("Unknown")
except GeneratorExit:
#match break equivalent exit point (use raise GeneratorExit("") )
pass #placeholder code needed for the except
print("We're out of the match")
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.