Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Member-only story

Python BootCamp -> Match Case

4 min readJun 10, 2024

--

Hello Everyone,

Python 3.10 introduced a powerful and expressive feature: the match case statement. Inspired by pattern matching found in languages like Rust and Haskell, this feature allows for more readable and concise code when dealing with complex data structures. Whether you're processing nested dictionaries, handling various data types, or implementing control flow based on patterns, the match case statement can significantly simplify your code.

Press enter or click to view image in full size

Let’s go on an adventure where textual commands determine actions.

command = input().split()
if command == "quit":
print("Exiting...")
elif command == "look":
print("Looking...")
elif len(command) > 1:
action, *args = command
print(f"Action: {action}, Args: {args}")
else :
print("Invalid command")
  • The code above is less readable and contains a staircase of if elif else statements. Let's refine it using match case.

Less refine it.

command = input()

match command.split():
case ["quit"]:
print("Exiting...")
case ["look"]:
print("Looking...")
case [action, *args]:
print(f"Action: {action}, Args: {args}")
case _:
print("Invalid command")

--

--

Rahul Beniwal
Rahul Beniwal

Written by Rahul Beniwal

I can help you master Python | Backend | System Design | Django | Rust | Computer Science | Databases | Making complex concepts clear and accessible with code