This file contains examples and tests for converting JavaScript switch statements to Python 3.10+ match statements.
JavaScript:
switch (value) {
case 1:
result = "one";
break;
case 2:
result = "two";
break;
default:
result = "other";
}Python:
match value:
case 1:
result = 'one'
case 2:
result = 'two'
case _:
result = 'other'JavaScript:
switch (color) {
case "red":
case "blue":
flag = true
case "yellow":
result = "primary";
case "green":
sayHello();
break;
case "black":
flag = false
case "white":
sayHello();
break;
default:
result = "unknown";
}Python:
match color:
case 'red':
flag = True
result = 'primary'
sayHello()
case 'blue':
flag = True
result = 'primary'
sayHello()
case 'yellow':
result = 'primary'
sayHello()
case 'green':
sayHello()
case 'black':
flag = False
sayHello()
case 'white':
sayHello()
case _:
result = 'unknown'JavaScript:
switch (x + y) {
case 10:
result = "ten";
break;
default:
result = "not ten";
}Python:
match x + y:
case 10:
result = 'ten'
case _:
result = 'not ten'JavaScript:
switch (status) {
case "ok":
result = true;
break;
case "fail":
result = false;
break;
}Python:
match status:
case 'ok':
result = True
case 'fail':
result = FalseJavaScript:
switch (type) {
case "A":
switch (subtype) {
case 1:
result = "A1";
break;
default:
result = "A-other";
}
break;
default:
result = "other";
}Python:
match type:
case 'A':
match subtype:
case 1:
result = 'A1'
case _:
result = 'A-other'
case _:
result = 'other'