Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions lab-python-error-handling.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,40 @@
{
"cell_type": "code",
"execution_count": null,
"id": "cc2c441d-9dcf-4817-b097-cf6cbe440846",
"id": "d9b39448",
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n",
"a\n",
"Warning: Mixed types (int vs str)\n",
"20\n"
]
}
],
"source": [
"# your code goes here"
"def smaller(a, b):\n",
" try:\n",
" # 1. Try to return the actual smaller value\n",
" return a if a < b else b\n",
" except TypeError:\n",
" # 2. If it fails, convert both to strings and compare alphabetically\n",
" print(f\"Warning: Mixed types ({type(a).__name__} vs {type(b).__name__})\")\n",
" return str(a) if str(a) < str(b) else str(b)\n",
"\n",
"\n",
"print(smaller(10, 5)) # Normal math: Returns 10\n",
"print(smaller(\"z\", \"a\")) # Normal string: Returns \"z\"\n",
"print(smaller(5, \"20\")) # Mixed types: Returns '5' (because \"5\" > \"2\" alphabetically!)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "base",
"language": "python",
"name": "python3"
},
Expand All @@ -66,7 +89,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
"version": "3.13.9"
}
},
"nbformat": 4,
Expand Down