From 55717a47dee55e6d62aa161e52840b7075dc0689 Mon Sep 17 00:00:00 2001 From: SAM <60264918+SAM-DEV007@users.noreply.github.com> Date: Tue, 4 Jun 2024 16:48:03 +0530 Subject: [PATCH] Update match_case_statement.md Added patterns with a literal section --- .../advanced-python/match_case_statement.md | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/contrib/advanced-python/match_case_statement.md b/contrib/advanced-python/match_case_statement.md index d4ad861..691d23b 100644 --- a/contrib/advanced-python/match_case_statement.md +++ b/contrib/advanced-python/match_case_statement.md @@ -20,3 +20,60 @@ A match statement takes a statement which compares it to the various cases and t As discussed earlier, match case statements use pattern matching where the patterns consist of sequences, mappings, primitive data types as well as class instances. The structural pattern matching uses declarative approach and it nexplicitly states the conditions for the patterns to match with the data. ### Patterns with a Literal +#### Generic Case +`sample text` is passed as a literal in the `match` block. There are two cases and a wildcard case mentioned. +```python +match 'sample text': + case 'sample text': + print('sample text') + case 'sample': + print('sample') + case _: + print('None found') +``` +The `sample text` case is satisfied as it matches with the literal `sample text` described in the `match` block. + +O/P: +``` +sample text +``` + +#### Using OR +Taking another example, `|` can be used as OR to include multiple patterns in a single case statement where the multiple patterns all lead to a similar task. + +The below code snippets can be used interchangebly and generate the similar output. The latter is more consive and readible. +```python +match 'e': + case 'a': + print('vowel') + case 'e': + print('vowel') + case 'i': + print('vowel') + case 'o': + print('vowel') + case 'u': + print('vowel') + case _: + print('consonant') +``` +```python +match 'e': + case 'a' | 'e' | 'i' | 'o' | 'u': + print('vowel') + case _: + print('consonant') +``` +O/P: +``` +vowel +``` + +#### Without wildcard +When in a `match` block, there is no wildcard case present there are be two cases of match being present or not. If the match doesn't exist, the behaviour is a no-op. +```python +match 'c': + case 'a' | 'e' | 'i' | 'o' | 'u': + print('vowel') +``` +The output will be blank as a no-op occurs.