Python match + case
writing match + case instead of if + elif + else
2025-11-04 13:15
// updated 2025-11-05 22:18
// updated 2025-11-05 22:18
Instead of writing the if ... elif ... else structure, we can use the match ... case structure, especially if the comparison operators are just looking at one variable but several discrete values:
match my_variable
case 1:
# do 1 stuff here
case 2:
# do 2 stuff here
case 3 | 4:
# do 3 or 4 stuff here
case _:
# do default stuff hereThis match-case structure (similar to a switch-case structure in other programming languages) contrasts with the if-else structure:
if my_variable == 1:
# do 1 stuff here
elif my_variable == 2:
# do 2 stuff here
elif my_variable == 3 or my_variable == 4:
# do 3 or 4 stuff here
else
# do other stuff hereWhile the if ... elif ... else structure might have fewer lines of code, each line feels "lighter" and "neater" with the match ... case structure, perhaps because it eliminates the unnecessary repetition of the variable name!