{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "#
*) since at least Python 1.6
\n", "\n", "#### ...with assignment" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "18 hours, 32 minutes and 50 seconds\n" ] } ], "source": [ "text = \"18:32:50\"\n", "#text = \"18:32\" # 🔧\n", "\n", "# ↘️\n", "h, m, s = text.split(\":\")\n", "\n", "print(f\"{h} hours, {m} minutes and {s} seconds\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "#### ...with \"for\"" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "red is #FF0000\n", "blue is #0000FF\n", "yellow is #FFFF00\n" ] } ], "source": [ "colors = {\n", " \"red\": (255, 0, 0),\n", " \"blue\": (0, 0, 255),\n", " \"yellow\": (255, 255, 0),\n", " #\"transparent gray\": (100, 100, 100, 0.5) # 🔧\n", "}\n", "\n", "# ↘️ ↘️\n", "for name, (r, g, b) in colors.items():\n", " print(name, \"is\", f\"#{r:02X}{g:02X}{b:02X}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ...with try/except" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "No such file\n" ] } ], "source": [ "try:\n", " open(\"non-existent.txt\")\n", " #open(\"/etc/shadow\")\n", "except FileNotFoundError as e: # ⬅️\n", " print(\"No such file\")\n", "except PermissionError as e: # ⬅️\n", " print(f\"Not allowed (error {e.errno})\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "