Python For Beginners: match Statement in Python 3.10.2

Introduced in Python 3.10, it’s the equivalent of the switch statement found in other programming languages

Vinicius Monteiro
Programming For Beginners

--

Photo by Nikolay Trebukhin on Unsplash

If you’re familiar with programming languages such as Java or JavaScript, you may know about the switch statement. It can replace if else blocks. Here’s an example of the switch statement in Java,

int letter = 1;
switch (letter) {
case 1:
System.out.println("A");
break;
case 2:
System.out.println("B");
break;
case 3:
System.out.println("C");
break;
default:
System.out.println("D");
}

Similar to the switch above, from Python version 3.10, you can use the match statement.

Basic syntax

It takes an expression value and compares it with patterns in case blocks.

def day_of_week (day):
match day:
case 1:
return "Sunday"
case 2:
return "Monday"
case 3:
return "Tuesday"
case _:
return "Invalid day"
print(day_of_week(3))

Comparing with the switch statement above, the _ at the end of the matchis equivalent to the default block. It executes something when no other case satisfies. It’s…

--

--