Skip to content

Commit

Permalink
Add match-case in Python
Browse files Browse the repository at this point in the history
  • Loading branch information
smortezah authored Mar 25, 2024
1 parent 6f45733 commit 181bec2
Show file tree
Hide file tree
Showing 2 changed files with 389 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ Also, my articles on the Medium platform can be found [here](https://medium.com/

- [Lambda](python/lambda.ipynb): an introduction to lambda functions in Python
- [Generators](python/generator.ipynb): a hands-on guide to Python generators
- [Pattern matching](python/match-case.ipynb): a guide to pattern matching in Python with `match-case` statement

## :chart_with_upwards_trend: Statistical analysis

Expand Down
388 changes: 388 additions & 0 deletions python/match-case.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,388 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Click [here]() to access the associated Medium article."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Basic"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Cold-blooded and scaly\n"
]
}
],
"source": [
"def categorize_animal(animal: str):\n",
" match animal:\n",
" case \"mammal\":\n",
" print(\"Warm-blooded and viviparous\")\n",
" case \"reptile\":\n",
" print(\"Cold-blooded and scaly\")\n",
" case \"bird\":\n",
" print(\"Feathered and egg-laying\")\n",
" case _:\n",
" print(\"Unknown category\")\n",
"\n",
"\n",
"categorize_animal(\"reptile\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ah, the warmth of Pythonic sunbeams.\n"
]
}
],
"source": [
"def describe_temperature(temp: int):\n",
" match temp:\n",
" case t if t < 0:\n",
" print(\"Brrr, it's freezing!\")\n",
" case t if 0 <= t < 20:\n",
" print(\"Chilly, but manageable.\")\n",
" case t if t >= 20:\n",
" print(\"Ah, the warmth of Pythonic sunbeams.\")\n",
"\n",
"\n",
"describe_temperature(21)"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"First: 2, Last: 9\n"
]
}
],
"source": [
"def extract_first_and_last(items: list):\n",
" match items:\n",
" case [first, *middle, last]:\n",
" print(f\"First: {first}, Last: {last}\")\n",
" case _:\n",
" print(\"Empty or too mysterious to unpack\")\n",
"\n",
"\n",
"extract_first_and_last([2, 5, 3, 9])"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Unknown tea type. Surprise me!\n"
]
}
],
"source": [
"def serve_tea(tea_type: str):\n",
" match tea_type:\n",
" case \"black\":\n",
" print(\"Steaming hot black tea, anyone?\")\n",
" case \"green\":\n",
" print(\"Refreshing green tea, just the way you like it.\")\n",
" case \"herbal\":\n",
" print(\"Herbal infusion for a calm afternoon.\")\n",
" case _:\n",
" print(\"Unknown tea type. Surprise me!\")\n",
"\n",
"\n",
"serve_tea(\"espresso\")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"100 is positive. Sunshine in numerical form.\n"
]
}
],
"source": [
"def classify_number(number: int):\n",
" match number:\n",
" case n if n < 0:\n",
" print(f\"{n} is negative. Brrr!\")\n",
" case 0:\n",
" print(\"Zero-a serene void.\")\n",
" case n if n > 0:\n",
" print(f\"{n} is positive. Sunshine in numerical form.\")\n",
"\n",
"\n",
"classify_number(100)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Unknown season. Maybe it's 'Sprinter' or 'Autummer'!\n"
]
}
],
"source": [
"def describe_season(season: str):\n",
" match season:\n",
" case \"spring\":\n",
" print(\"Blossoms and chirping birds.\")\n",
" case \"summer\":\n",
" print(\"Sunscreen, ice cream, and beach vibes.\")\n",
" case \"autumn\":\n",
" print(\"Golden leaves, pumpkin spice, and cozy sweaters.\")\n",
" case \"winter\":\n",
" print(\"Snowflakes, hot cocoa, and frosty mornings.\")\n",
" case _:\n",
" print(\"Unknown season. Maybe it's 'Sprinter' or 'Autummer'!\")\n",
"\n",
"\n",
"describe_season(\"leaves\")"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"First: 1, Second: 2, Rest: [3, 4, 5]\n"
]
}
],
"source": [
"def unpack_sequence(sequence: list):\n",
" match sequence:\n",
" case [first, second, *rest]:\n",
" print(f\"First: {first}, Second: {second}, Rest: {rest}\")\n",
" case _:\n",
" print(\"Empty or too mysterious to unpack\")\n",
"\n",
"\n",
"unpack_sequence([1, 2, 3, 4, 5])"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"User: Alice, Age: 30, Location: Wonderland\n"
]
}
],
"source": [
"def extract_nested_data(data: dict):\n",
" match data:\n",
" case {\"user\": {\"name\": name, \"age\": age}, \"location\": location}:\n",
" print(f\"User: {name}, Age: {age}, Location: {location}\")\n",
" case _:\n",
" print(\"Data too cryptic to decipher\")\n",
"\n",
"\n",
"extract_nested_data(\n",
" {\"user\": {\"name\": \"Alice\", \"age\": 30}, \"location\": \"Wonderland\"}\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Fireball inflicts 50 damage. Healing restores 30.\n"
]
}
],
"source": [
"def reveal_spell(spellbook: dict):\n",
" match spellbook:\n",
" case {\"fireball\": damage, \"heal\": healing}:\n",
" print(\n",
" f\"Fireball inflicts {damage} damage. \"\n",
" f\"Healing restores {healing}.\"\n",
" )\n",
" case _:\n",
" print(\"Spellbook written in an ancient dialect\")\n",
"\n",
"\n",
"reveal_spell({\"fireball\": 50, \"heal\": 30})"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Advanced"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Odette glides gracefully in ballet attire.\n"
]
}
],
"source": [
"from dataclasses import dataclass\n",
"\n",
"\n",
"@dataclass\n",
"class Dancer:\n",
" name: str\n",
" style: str\n",
"\n",
"\n",
"def introduce_dancer(dancer: Dancer):\n",
" match dancer:\n",
" case Dancer(\"Odette\", \"ballet\"):\n",
" print(f\"{dancer.name} glides gracefully in {dancer.style} attire.\")\n",
" case Dancer(\"Puck\", \"comedy\"):\n",
" print(f\"{dancer.name} twirls, jigs, and keeps us laughing.\")\n",
" case _:\n",
" print(f\"{dancer.name} joins the dance-an enigma in {dancer.style}.\")\n",
"\n",
"\n",
"introduce_dancer(Dancer(\"Odette\", \"ballet\"))"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Weather forecast: Unpredictable dance of elements.\n"
]
}
],
"source": [
"def analyze_weather(temperature: int, precipitation: float):\n",
" match (temperature, precipitation):\n",
" case (t, p) if t > 30 and p < 0.2:\n",
" print(\"Sunny and warm-perfect picnic weather!\")\n",
" case (t, p) if t < 10 or p > 0.5:\n",
" print(\"Bundle up! It's chilly or rainy.\")\n",
" case _:\n",
" print(\"Weather forecast: Unpredictable dance of elements.\")\n",
"\n",
"\n",
"analyze_weather(25, 0.3)"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hearty breakfast with extras-fuel for the day!\n"
]
}
],
"source": [
"def process_order(order: dict):\n",
" match order:\n",
" case {\n",
" \"items\": [\"coffee\", \"croissant\"], \"total\": amount\n",
" } if amount < 20:\n",
" print(\"Small order-grab a seat by the window.\")\n",
" case {\n",
" \"items\": [\"breakfast\", *extras], \"total\": amount\n",
" } if len(extras) >= 2:\n",
" print(\"Hearty breakfast with extras-fuel for the day!\")\n",
" case _:\n",
" print(\"Order complexity: Off the charts!\")\n",
"\n",
"\n",
"process_order({\"items\": [\"breakfast\", \"juice\", \"pancakes\"], \"total\": 25})"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}

0 comments on commit 181bec2

Please sign in to comment.