{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c001",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "# Python מינימלי לעבודה עם SQLite\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c002",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## מה צריכה תוכנית Python כדי לשאול מסד נתונים שאלה?\n",
    "\n",
    "במדריך ה־SQL הקלדתם שאילתות ב־DB Browser. תוכנית שולחת את אותן שאילתות ומקבלת את השורות כערכים של Python. השיעור עובר על ה־Python שתוכנית כזו משתמשת בו, לפי הסדר שבו היא משתמשת בו: ערכים וטקסט, טאפלים ורשימות, הקריאות שמדברות עם מסד הנתונים, פרמטרים, פונקציה שמריצה שאילתה, ורשימה שנבנית מתוצאות של שאילתה.\n",
    "\n",
    "הנתונים הם טבלת שיתוף האופניים `daily_ridership` של המדריך: 731 ימים אמיתיים, שורה אחת לכל יום. השיעור משתמש בשש מעמודותיה: `year`, `month`, `season`, `weather` (אחת משלוש תוויות), `working_day` (1 ביום עבודה, 0 אחרת) ו־`total_rides` (ההשכרות של אותו יום).\n",
    "\n",
    "כשיש לנושא שיעור מלא משלו, השיעור הזה חוזר על הרעיון במשפט אחד ומקשר אליו: [ערכים ואוספים](https://dvirross.com/he/courses/intro-data-science/python-values-and-collections), [לולאות ופונקציות](https://dvirross.com/he/courses/intro-data-science/python-loops-and-functions) ו־[SQL מתוך Python](https://dvirross.com/he/courses/intro-data-science/sql-from-python).\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c003",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**איך עובדים:** הריצו את התאים מלמעלה למטה, כי התאים חולקים את המשתנים שלהם. תא שכתוב בו `# Your turn` ריק: כתבו בו את הקוד, הריצו אותו, והריצו את התא שמתחתיו, שבודק את התשובה בלי להראות את הפתרון. במחברת עם הפתרונות יש מתחת לכל משימה את הפתרון, את הטעויות הנפוצות ואת הפלט הצפוי.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c004",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## הכנה: להביא את קובץ מסד הנתונים\n",
    "\n",
    "אין צורך בחשבון ואין צורך במפתח. התא הבא מוריד את מסד הנתונים של הקורס מהאתר הציבורי ושומר אותו ליד המחברת (ב־Colab הוא מופיע בחלונית **Files**). אם ההורדה נכשלת, פותחים את הכתובת שלמטה בדפדפן, מורידים את הקובץ ומעלים אותו לחלונית **Files** של Colab.\n",
    "\n",
    "`https://dvirross.com/materials/courses/intro-data-science/sql-practice.sqlite`\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c005",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.848394Z",
     "iopub.status.busy": "2026-11-01T22:13:40.848198Z",
     "iopub.status.idle": "2026-11-01T22:13:40.857785Z",
     "shell.execute_reply": "2026-11-01T22:13:40.856390Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "קובץ מסד הנתונים מוכן: sql-practice.sqlite\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import urllib.request\n",
    "\n",
    "DB_URL = 'https://dvirross.com/materials/courses/intro-data-science/sql-practice.sqlite'\n",
    "DB_PATH = 'sql-practice.sqlite'\n",
    "\n",
    "if not os.path.exists(DB_PATH):\n",
    "    # the site refuses the default user agent of Python, so the request names one\n",
    "    request = urllib.request.Request(DB_URL, headers={'User-Agent': 'Mozilla/5.0'})\n",
    "    with urllib.request.urlopen(request) as response, open(DB_PATH, 'wb') as file:\n",
    "        file.write(response.read())\n",
    "print('קובץ מסד הנתונים מוכן:', DB_PATH)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c006",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "התא הבא מגדיר את הפונקציה `check(task_number)`. אחרי שמריצים את התא של משימה, מריצים את התא שמתחתיו: `check` מריצה שוב את התא שלכם, אוספת את מה שהוא מדפיס ומשווה אותו לפלט הצפוי. היא אומרת אם הפלט נכון, ואם לא באיזו שורה הוא שונה; היא לא מראה את הפתרון.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c007",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.860094Z",
     "iopub.status.busy": "2026-11-01T22:13:40.859868Z",
     "iopub.status.idle": "2026-11-01T22:13:40.867947Z",
     "shell.execute_reply": "2026-11-01T22:13:40.866292Z"
    }
   },
   "outputs": [],
   "source": [
    "import ast, contextlib, hashlib, io\n",
    "\n",
    "# The expected output of each task, as hashes of its lines (the solutions are not stored here).\n",
    "EXPECTED = {int(k): v for k, v in {\n",
    "    '3': [\n",
    "        '4963af400ece'\n",
    "    ],\n",
    "    '4': [\n",
    "        '7d827bbe5897'\n",
    "    ],\n",
    "    '5': [\n",
    "        '14e4e0edb1cb'\n",
    "    ],\n",
    "    '6': [\n",
    "        '2b855e705c53',\n",
    "        'fa4ea1bc266c'\n",
    "    ],\n",
    "    '7': [\n",
    "        '28af1299a0b7'\n",
    "    ]\n",
    "}.items()}\n",
    "\n",
    "\n",
    "def check(task):\n",
    "    \"\"\"Run the last cell that ran (not a check) again and compare what it prints with the expected output of the task.\"\"\"\n",
    "    if task not in EXPECTED:\n",
    "        print('אין משימה כזו: ', task)\n",
    "        return\n",
    "    cells = [s for s in In[:-1] if s.strip() and not s.lstrip().startswith('check(')]   # In: the cells that ran, kept by IPython\n",
    "    tree = ast.parse(cells[-1] if cells else '')\n",
    "    last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None   # a bare last expression counts as printed\n",
    "    out = io.StringIO()\n",
    "    try:\n",
    "        with contextlib.redirect_stdout(out):\n",
    "            exec(compile(tree, '<task>', 'exec'), globals())\n",
    "            if last is not None:\n",
    "                value = eval(compile(ast.Expression(last.value), '<task>', 'eval'), globals())\n",
    "                if value is not None:\n",
    "                    print(repr(value))\n",
    "    except Exception as error:\n",
    "        print('התא נכשל בשגיאה:', type(error).__name__ + ':', error)\n",
    "        return\n",
    "    got = [hashlib.sha256(line.rstrip().encode()).hexdigest()[:12] for line in out.getvalue().rstrip().splitlines()]\n",
    "    want = EXPECTED[task]\n",
    "    if not got:\n",
    "        print('לא הודפס כלום. הדפיסו את התשובה בתא המשימה, הריצו אותו, והריצו את `check` מיד אחריו.')\n",
    "    elif len(got) != len(want):\n",
    "        print('התא הדפיס {got} שורות והמשימה מצפה ל־{want}. קראו שוב את המשימה ואת הרמז.'.format(got=len(got), want=len(want)))\n",
    "    elif got != want:\n",
    "        print('שורה {k} שונה מהפלט הצפוי. קראו שוב את המשימה ואת הרמז.'.format(k=next(i for i in range(len(want)) if got[i] != want[i]) + 1))\n",
    "    else:\n",
    "        print('OK: הפלט כצפוי.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c008",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## ערכים, משתנים ו־`print`\n",
    "\n",
    "**[משתנה](https://dvirross.com/he/courses/intro-data-science/glossary#variable)** (variable) הוא שם שמפנה לערך, כמו המספר 985 או הטקסט `'Mist or cloudy'`. הפונקציה `print` מציגה ערכים על המסך: היא שמה רווח בין ערך לערך, ולכן אפשר להציג בה טקסט ומספרים יחד. שורה שמתחילה ב־`#` היא **הערה** (comment): Python מתעלמת ממנה, והיא כתובה בשביל הקורא.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c009",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.870373Z",
     "iopub.status.busy": "2026-11-01T22:13:40.870175Z",
     "iopub.status.idle": "2026-11-01T22:13:40.874748Z",
     "shell.execute_reply": "2026-11-01T22:13:40.873275Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Weather: Mist or cloudy Rides: 985\n"
     ]
    }
   ],
   "source": [
    "# one day of the table\n",
    "rides = 985\n",
    "weather = 'Mist or cloudy'\n",
    "print('Weather:', weather, 'Rides:', rides)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c010",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## טקסט וגרשיים\n",
    "\n",
    "טקסט נכתב בין גרשיים, וגרש יחיד וגרשיים כפולים הם אותו דבר. טקסט בין **שלושה גרשיים כפולים** יכול להימשך על פני כמה שורות. עבור Python, ‏SQL הוא טקסט, והוא מכיל גרשיים יחידים סביב ערכי הטקסט שלו, ולכן כותבים אותו בגרשיים כפולים או בשלושה גרשיים כפולים:\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c011",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.877351Z",
     "iopub.status.busy": "2026-11-01T22:13:40.877102Z",
     "iopub.status.idle": "2026-11-01T22:13:40.881444Z",
     "shell.execute_reply": "2026-11-01T22:13:40.880366Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Light rain or snow\n",
      "SELECT * FROM daily_ridership WHERE year = 2012\n"
     ]
    }
   ],
   "source": [
    "label = 'Light rain or snow'\n",
    "one_line = \"SELECT * FROM daily_ridership WHERE year = 2012\"\n",
    "many_lines = \"\"\"\n",
    "    SELECT year, month\n",
    "    FROM daily_ridership\n",
    "    WHERE weather = 'Mist or cloudy'\n",
    "\"\"\"\n",
    "print(label)\n",
    "print(one_line)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c012",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## טאפלים, רשימות וציינים\n",
    "\n",
    "טבלה במסד נתונים היא שורות מתחת לעמודות קבועות. תוצאה של שאילתה מגיעה ל־Python כרשימה של **[טאפלים](https://dvirross.com/he/courses/intro-data-science/glossary#tuple)** (tuple): טאפל נכתב בסוגריים עגולים ומחזיק מספר קבוע של ערכים לפי סדר, אחד לכל עמודה ב־`SELECT`, ואי אפשר לשנות אותו בטעות. **[רשימה](https://dvirross.com/he/courses/intro-data-science/glossary#list)** (list) נכתבת בסוגריים מרובעים ומחזיקה פריטים רבים, כאן שורות רבות. **[ציין](https://dvirross.com/he/courses/intro-data-science/glossary#index)** (index) הוא המקום של פריט, בסוגריים מרובעים, והספירה מתחילה ב־0, ולכן `row[0]` הוא הערך הראשון.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c013",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.884166Z",
     "iopub.status.busy": "2026-11-01T22:13:40.883939Z",
     "iopub.status.idle": "2026-11-01T22:13:40.888536Z",
     "shell.execute_reply": "2026-11-01T22:13:40.887281Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2011 985\n",
      "(2011, 1, 801)\n",
      "801\n"
     ]
    }
   ],
   "source": [
    "row = (2011, 1, 985)\n",
    "rows = [(2011, 1, 985), (2011, 1, 801), (2011, 1, 1349)]\n",
    "print(row[0], row[2])\n",
    "print(rows[1])\n",
    "print(rows[1][2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c014",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "השורה האחרונה לוקחת את השורה השנייה ברשימה, ואז את הערך השלישי באותה שורה. השיעור המלא נמצא ב[טאפלים ורשימות](https://dvirross.com/he/courses/intro-data-science/python-values-and-collections#טאפלים-ורשימות-כמה-ערכים-לפי-סדר).\n",
    "\n",
    "## התחברות, סמן, הרצה ושליפה\n",
    "\n",
    "ארבעה שלבים מביאים שורות ממסד נתונים אל Python. כל שלב הוא שורה אחת. השורה `import sqlite3` מאפשרת להשתמש במודול `sqlite3`, שמגיע עם Python.\n",
    "\n",
    "**התחברות.** הפונקציה `sqlite3.connect` פותחת את קובץ מסד הנתונים שהשם שלו ניתן לה ומחזירה **[חיבור](https://dvirross.com/he/courses/intro-data-science/glossary#connection)** (connection), אובייקט שמייצג את מסד הנתונים הפתוח.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c015",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.891264Z",
     "iopub.status.busy": "2026-11-01T22:13:40.891074Z",
     "iopub.status.idle": "2026-11-01T22:13:40.898200Z",
     "shell.execute_reply": "2026-11-01T22:13:40.893737Z"
    }
   },
   "outputs": [],
   "source": [
    "import sqlite3\n",
    "\n",
    "conn = sqlite3.connect('sql-practice.sqlite')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c016",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**יצירת סמן.** השיטה `cursor` של החיבור יוצרת **[סמן](https://dvirross.com/he/courses/intro-data-science/glossary#cursor)** (cursor), אובייקט ששולח SQL ומחזיק את התשובה עד שלוקחים אותה.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c017",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.900240Z",
     "iopub.status.busy": "2026-11-01T22:13:40.900041Z",
     "iopub.status.idle": "2026-11-01T22:13:40.903597Z",
     "shell.execute_reply": "2026-11-01T22:13:40.902307Z"
    }
   },
   "outputs": [],
   "source": [
    "c = conn.cursor()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c018",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**הרצת שאילתה.** השיטה `execute` של הסמן שולחת שאילתה אחת. היא מחזירה את הסמן עצמו, ולכן מה שרואים הוא אובייקט הסמן, ושורות התשובה מחכות בו.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c019",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.905406Z",
     "iopub.status.busy": "2026-11-01T22:13:40.905216Z",
     "iopub.status.idle": "2026-11-01T22:13:40.911688Z",
     "shell.execute_reply": "2026-11-01T22:13:40.910336Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<sqlite3.Cursor object at 0x7f0000000000>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c.execute(\"\"\"\n",
    "    SELECT year, month, weather, total_rides\n",
    "    FROM daily_ridership\n",
    "    LIMIT 2\n",
    "\"\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c020",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**שליפת התוצאות.** השיטה `fetchall` לוקחת את כל שורות התשובה, כרשימה של טאפלים.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c021",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.914729Z",
     "iopub.status.busy": "2026-11-01T22:13:40.913970Z",
     "iopub.status.idle": "2026-11-01T22:13:40.920065Z",
     "shell.execute_reply": "2026-11-01T22:13:40.918782Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(2011, 1, 'Mist or cloudy', 985), (2011, 1, 'Mist or cloudy', 801)]\n"
     ]
    }
   ],
   "source": [
    "results = c.fetchall()\n",
    "print(results)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c022",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "השיטה `fetchmany` לוקחת את השורות הבאות, כמספר שנותנים לה. השיטה `fetchone` לוקחת את השורה הבאה לבדה, כטאפל. שאילתה יכולה לבחור 731 שורות בזמן ש־`fetchmany(3)` לוקחת שלוש מהן. מכיוון ש־`execute` מחזירה את הסמן, אפשר להוסיף אחריה שליפה באותה שורה. הערכים של שורה נמצאים לפי הסדר של ה־`SELECT`: העמודה הראשונה שנבחרה היא ציין 0.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c023",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.921931Z",
     "iopub.status.busy": "2026-11-01T22:13:40.921751Z",
     "iopub.status.idle": "2026-11-01T22:13:40.926887Z",
     "shell.execute_reply": "2026-11-01T22:13:40.925542Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(2011, 1, 985), (2011, 1, 801), (2011, 1, 1349)]\n",
      "(1, 985)\n",
      "Month: 1\n",
      "Rides: 985\n"
     ]
    }
   ],
   "source": [
    "three = c.execute(\n",
    "    \"SELECT year, month, total_rides FROM daily_ridership\"\n",
    ").fetchmany(3)\n",
    "print(three)\n",
    "row = c.execute(\n",
    "    \"SELECT month, total_rides FROM daily_ridership LIMIT 1\"\n",
    ").fetchone()\n",
    "print(row)\n",
    "print('Month:', row[0])\n",
    "print('Rides:', row[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c024",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## פונקציות סיכום בשאילתה\n",
    "\n",
    "פונקציות הסיכום של [מדריך ה־SQL](https://dvirross.com/he/courses/intro-data-science/sql-in-db-browser#סיכום-ערכים) פועלות באותו אופן בתוך תוכנית. `SUM(total_rides)` מחברת את ההשכרות של הימים שנבחרו, ו־`COUNT(*)` סופרת את הימים; `COUNT(weather)` סופרת את השורות שיש להן תווית, ו־`COUNT(DISTINCT weather)` סופרת את התוויות השונות. שאילתת סיכום מחזירה שורה אחת, ולכן `fetchone()` היא השליפה המתאימה, והשורה היא טאפל גם כשיש בה ערך אחד.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c025",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.928747Z",
     "iopub.status.busy": "2026-11-01T22:13:40.928566Z",
     "iopub.status.idle": "2026-11-01T22:13:40.933411Z",
     "shell.execute_reply": "2026-11-01T22:13:40.931870Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rides: 386839 Days: 115\n"
     ]
    }
   ],
   "source": [
    "result = c.execute(\"\"\"\n",
    "    SELECT SUM(total_rides), COUNT(*)\n",
    "    FROM daily_ridership\n",
    "    WHERE year = 2011 AND working_day = 0\n",
    "\"\"\").fetchone()\n",
    "print('Rides:', result[0], 'Days:', result[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c026",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "השאילתה צריכה `SUM` כי כל שורה היא יום עם השכרות רבות: `COUNT(*)` הייתה מחזירה את מספר הימים, 115, ולא את ההשכרות.\n",
    "\n",
    "### משימה 1 (דוגמה פתורה): ימים ותוויות ב־2012\n",
    "\n",
    "כמה ימים יש ל־2012 בטבלה, וכמה תוויות מזג אוויר שונות יש להם? השוו בין `COUNT(weather)` ל־`COUNT(DISTINCT weather)`: מה כל אחת סופרת? החליטו לפני שאתם מריצים את הקוד.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c027",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.935592Z",
     "iopub.status.busy": "2026-11-01T22:13:40.935406Z",
     "iopub.status.idle": "2026-11-01T22:13:40.940076Z",
     "shell.execute_reply": "2026-11-01T22:13:40.938539Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Days: 366 Different weather labels: 3\n"
     ]
    }
   ],
   "source": [
    "result = c.execute(\"\"\"\n",
    "    SELECT COUNT(weather), COUNT(DISTINCT weather)\n",
    "    FROM daily_ridership\n",
    "    WHERE year = 2012\n",
    "\"\"\").fetchone()\n",
    "print('Days:', result[0], 'Different weather labels:', result[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c028",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "ל־2012 יש 366 ימים (שנה מעוברת), לכל יום יש תווית, והתוויות הן שלוש בסך הכול. השורה היא טאפל עם שני ערכים.\n",
    "\n",
    "שאילתה עם `DISTINCT` מחזירה שורה אחת לכל ערך, וכשהיא בוחרת עמודה אחת השורות הן טאפלים עם ערך אחד. Python כותבת טאפל כזה עם פסיק, `('Mist or cloudy',)`. `LIKE '%cloudy%'` מתאים לטקסט שמכיל את `cloudy` בכל מקום.\n",
    "\n",
    "### משימה 2 (דוגמה פתורה): תוויות שמכילות `cloudy`\n",
    "\n",
    "כמה תוויות מזג אוויר שונות מכילות את הטקסט `cloudy`? אחר כך הציגו רשימה של התוויות האלה.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c029",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.941891Z",
     "iopub.status.busy": "2026-11-01T22:13:40.941710Z",
     "iopub.status.idle": "2026-11-01T22:13:40.946695Z",
     "shell.execute_reply": "2026-11-01T22:13:40.945280Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Labels that contain cloudy: 2\n",
      "[('Mist or cloudy',), ('Clear or partly cloudy',)]\n"
     ]
    }
   ],
   "source": [
    "result = c.execute(\"\"\"\n",
    "    SELECT COUNT(DISTINCT weather)\n",
    "    FROM daily_ridership\n",
    "    WHERE weather LIKE '%cloudy%'\n",
    "\"\"\").fetchone()\n",
    "print('Labels that contain cloudy:', result[0])\n",
    "labels = c.execute(\"\"\"\n",
    "    SELECT DISTINCT weather\n",
    "    FROM daily_ridership\n",
    "    WHERE weather LIKE '%cloudy%'\n",
    "    LIMIT 10\n",
    "\"\"\").fetchall()\n",
    "print(labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c030",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "הספירה היא `result[0]`, והרשימה מחזיקה טאפל עם ערך אחד לכל תווית.\n",
    "\n",
    "### משימה 3: השכרות בימי עבודה\n",
    "\n",
    "**נסו בעצמכם.** השתמשו בסמן `c` כדי לקבל את מספר ההשכרות הכולל בימי העבודה של 2012. הדפיסו את הטקסט `Total rides:` ואחריו את המספר, ב־`print` אחד.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c031",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.948761Z",
     "iopub.status.busy": "2026-11-01T22:13:40.948566Z",
     "iopub.status.idle": "2026-11-01T22:13:40.951971Z",
     "shell.execute_reply": "2026-11-01T22:13:40.950748Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c032",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**פלט צפוי (המספרים מוסתרים)**\n",
    "\n",
    "```text\n",
    "Total rides: <number>\n",
    "```\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c033",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.954562Z",
     "iopub.status.busy": "2026-11-01T22:13:40.954332Z",
     "iopub.status.idle": "2026-11-01T22:13:40.958628Z",
     "shell.execute_reply": "2026-11-01T22:13:40.957388Z"
    }
   },
   "outputs": [],
   "source": [
    "check(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c034",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "> **רמז**\n",
    ">\n",
    "> כותבים את ה־SQL כמו ב־DB Browser: פונקציית סיכום אחת, ו־`WHERE` עם שני תנאים שמחוברים ב־`AND`. התוצאה היא שורה אחת, ולכן לוקחים אותה עם `fetchone` ומוציאים את המספר מהטאפל בציין.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c035",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "### קבוצות והסכום הגדול ביותר\n",
    "\n",
    "`GROUP BY` מקבץ יחד את השורות עם אותו ערך ו־`SUM` מחברת כל קבוצה. `ORDER BY ... DESC` ממיין את הקבוצות מהגדולה, ו־`LIMIT 1` משאיר את הראשונה. כאן הם מוצאים את העונה עם הכי הרבה השכרות ב־2011:\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c036",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.960947Z",
     "iopub.status.busy": "2026-11-01T22:13:40.960762Z",
     "iopub.status.idle": "2026-11-01T22:13:40.965436Z",
     "shell.execute_reply": "2026-11-01T22:13:40.964099Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Season: Summer Rides: 419650\n"
     ]
    }
   ],
   "source": [
    "best = c.execute(\"\"\"\n",
    "    SELECT season, SUM(total_rides)\n",
    "    FROM daily_ridership\n",
    "    WHERE year = 2011\n",
    "    GROUP BY season\n",
    "    ORDER BY SUM(total_rides) DESC\n",
    "    LIMIT 1\n",
    "\"\"\").fetchone()\n",
    "print('Season:', best[0], 'Rides:', best[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c037",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "### משימה 4: החודש העמוס ביותר\n",
    "\n",
    "**נסו בעצמכם.** איזה חודש בשנה היו בו הכי הרבה השכרות בכל הטבלה? ההשכרות של אותו חודש ב־2011 וב־2012 מחוברות יחד. הדפיסו את הטקסט `Busiest month:` ואחריו את הטאפל של מספר החודש וסך ההשכרות שלו, ב־`print` אחד.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c038",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.967367Z",
     "iopub.status.busy": "2026-11-01T22:13:40.967186Z",
     "iopub.status.idle": "2026-11-01T22:13:40.970597Z",
     "shell.execute_reply": "2026-11-01T22:13:40.969375Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**פלט צפוי (המספרים מוסתרים)**\n",
    "\n",
    "```text\n",
    "Busiest month: (<number>, <number>)\n",
    "```\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c040",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.972803Z",
     "iopub.status.busy": "2026-11-01T22:13:40.972575Z",
     "iopub.status.idle": "2026-11-01T22:13:40.976834Z",
     "shell.execute_reply": "2026-11-01T22:13:40.975476Z"
    }
   },
   "outputs": [],
   "source": [
    "check(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c041",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "> **רמז**\n",
    ">\n",
    "> מקבצים את השורות לפי `month`, כך שאותו חודש בשתי השנים הוא קבוצה אחת. ממיינים את הקבוצות לפי הסכום בסדר יורד ומשאירים אחת. השורה היא טאפל של החודש והסכום, וזה מה ש־`print` מציג.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c042",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## ערכים ממשתני Python: פרמטרים\n",
    "\n",
    "תוכנית שואלת בדרך כלל על ערכים שיש לה במשתנים. הערכים עוברים כ**פרמטרים** (parameters): כותבים סימן שאלה `?` ב־SQL במקום שבו שייך ערך, ונותנים את הערכים בנפרד, בטאפל, כארגומנט שני ל־`execute`. סימני השאלה מתמלאים לפי הסדר. אפשר ליצור ב־Python כמה משתנים בשורה אחת, כמו בשורה הראשונה של התיבה שלמטה: השמות משמאל מקבלים את הערכים מימין, לפי הסדר (זה [חילוץ](https://dvirross.com/he/courses/intro-data-science/glossary#unpacking), unpacking).\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c043",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.978871Z",
     "iopub.status.busy": "2026-11-01T22:13:40.978688Z",
     "iopub.status.idle": "2026-11-01T22:13:40.983240Z",
     "shell.execute_reply": "2026-11-01T22:13:40.982019Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rides: 102244\n"
     ]
    }
   ],
   "source": [
    "weather, year, working_day = 'Mist or cloudy', 2011, 0\n",
    "query = \"\"\"\n",
    "    SELECT SUM(total_rides)\n",
    "    FROM daily_ridership\n",
    "    WHERE weather = ? AND year = ? AND working_day = ?\n",
    "\"\"\"\n",
    "values = (weather, year, working_day)\n",
    "result = c.execute(query, values).fetchone()\n",
    "print('Rides:', result[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c044",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**למה לא להכניס את הערכים לטקסט עם מחרוזת f?**\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c045",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "[מחרוזת f](https://dvirross.com/he/courses/intro-data-science/glossary#f-string) מדביקה ערך בטקסט ה־SQL, וערך שמכיל SQL משנה את השאילתה. עונה שמגיעה בצורה `Summer' OR '1'='1` סוגרת את הגרש ומוסיפה תנאי שתמיד מתקיים, ולכן השאילתה שלמטה סופרת את כל 731 הימים. זו [הזרקת SQL](https://dvirross.com/he/courses/intro-data-science/glossary#sql-injection) (SQL injection). עם `?` הערך הוא נתונים בלבד, ואותו טקסט לא מתאים לאף עונה:\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c046",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.987897Z",
     "iopub.status.busy": "2026-11-01T22:13:40.987713Z",
     "iopub.status.idle": "2026-11-01T22:13:40.992784Z",
     "shell.execute_reply": "2026-11-01T22:13:40.991262Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(731,)\n",
      "(0,)\n"
     ]
    }
   ],
   "source": [
    "season = \"Summer' OR '1'='1\"\n",
    "pasted = f\"\"\"\n",
    "    SELECT COUNT(*) FROM daily_ridership\n",
    "    WHERE season = '{season}'\n",
    "\"\"\"\n",
    "print(c.execute(pasted).fetchone())\n",
    "safe = \"\"\"\n",
    "    SELECT COUNT(*) FROM daily_ridership\n",
    "    WHERE season = ?\n",
    "\"\"\"\n",
    "print(c.execute(safe, (season,)).fetchone())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c047",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "[SQL מתוך Python](https://dvirross.com/he/courses/intro-data-science/sql-from-python#העברת-ערכים-פרמטרים) מראה זאת במלואו.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c048",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "### משימה 5: ערכים ממשתנים\n",
    "\n",
    "**נסו בעצמכם.** שמרו את מזג האוויר `'Clear or partly cloudy'`, את השנה 2012 ואת הערך 1 של יום עבודה בשלושה משתנים. השתמשו בהם כשלושה פרמטרים `?` כדי לקבל את מספר ההשכרות הכולל בימים האלה, והדפיסו את הטקסט `Total rides:` ואחריו את המספר.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c049",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.994460Z",
     "iopub.status.busy": "2026-11-01T22:13:40.994267Z",
     "iopub.status.idle": "2026-11-01T22:13:40.997510Z",
     "shell.execute_reply": "2026-11-01T22:13:40.996314Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c050",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**פלט צפוי (המספרים מוסתרים)**\n",
    "\n",
    "```text\n",
    "Total rides: <number>\n",
    "```\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c051",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:40.999204Z",
     "iopub.status.busy": "2026-11-01T22:13:40.998995Z",
     "iopub.status.idle": "2026-11-01T22:13:41.002844Z",
     "shell.execute_reply": "2026-11-01T22:13:41.001577Z"
    }
   },
   "outputs": [],
   "source": [
    "check(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c052",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "> **רמז**\n",
    ">\n",
    "> ב־SQL יש שלושה תנאים, `weather = ?`, ‏`year = ?` ו־`working_day = ?`, שמחוברים ב־`AND`. בטאפל של הערכים המשתנים מופיעים באותו סדר כמו סימני השאלה.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c053",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## פונקציות ששולחות שאילתות\n",
    "\n",
    "**פונקציה** נותנת שם לעבודה. השורה `def get_name(parameter):` מגדירה אותה, השורות המוזחות מתחתיה הן הגוף שלה, ו־`return` שולחת ערך חזרה למי שקרא לה. פונקציה ששולחת שאילתה מקבלת כפרמטרים את הערכים שהיא צריכה ומעבירה אותם הלאה כערכי ה־`?`. השיעור המלא נמצא ב[לולאות ופונקציות](https://dvirross.com/he/courses/intro-data-science/python-loops-and-functions#פונקציות-שם-לעבודה).\n",
    "\n",
    "שאילתת סיכום על אפס שורות מחזירה ערך חסר: `SUM` של כלום היא `NULL`, ו־Python מציגה `NULL` כ־**[`None`](https://dvirross.com/he/courses/intro-data-science/glossary#none)**, הערך שמסמן שאין ערך. פונקציה שמחזירה מספר צריכה להחזיר 0 במקרה כזה. **[ביטוי תנאי](https://dvirross.com/he/courses/intro-data-science/glossary#conditional-expression)** (conditional expression), `a if condition else b`, הוא `a` כשהתנאי מתקיים ו־`b` אחרת, ו־`is not None` מתקיים כשיש ערך:\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "c054",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:41.004631Z",
     "iopub.status.busy": "2026-11-01T22:13:41.004448Z",
     "iopub.status.idle": "2026-11-01T22:13:41.009711Z",
     "shell.execute_reply": "2026-11-01T22:13:41.008599Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(None,)\n",
      "Summer 2011: 419650\n",
      "Summer 2013: 0\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    c.execute(\"\"\"\n",
    "        SELECT SUM(total_rides)\n",
    "        FROM daily_ridership\n",
    "        WHERE season = 'Summer' AND year = 2013\n",
    "    \"\"\").fetchone()\n",
    ")\n",
    "\n",
    "def get_season_rides(season, year):\n",
    "    query = \"\"\"\n",
    "        SELECT SUM(total_rides)\n",
    "        FROM daily_ridership\n",
    "        WHERE season = ? AND year = ?\n",
    "    \"\"\"\n",
    "    row = c.execute(query, (season, year)).fetchone()\n",
    "    return row[0] if row[0] is not None else 0\n",
    "\n",
    "print('Summer 2011:', get_season_rides('Summer', 2011))\n",
    "print('Summer 2013:', get_season_rides('Summer', 2013))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c055",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "הפונקציה משתמשת בסמן `c` שנוצר למעלה. הנתונים כוללים את השנים 2011 ו־2012, ולכן לשנת 2013 אין שורות.\n",
    "\n",
    "### משימה 6: פונקציה ששולחת שאילתה\n",
    "\n",
    "**נסו בעצמכם.** כתבו פונקציה `get_total_rides(year, month)` שמחזירה את מספר ההשכרות הכולל של השנה והחודש שניתנו (מספר שלם מ־1 עד 12), ו־0 כשאין שורה מתאימה. הדפיסו את הטקסט `July 2012:` ואת התוצאה ליולי 2012, ואחר כך את הטקסט `January 2013:` ואת התוצאה לינואר 2013, כל אחד בשורה משלו.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "c056",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:41.011588Z",
     "iopub.status.busy": "2026-11-01T22:13:41.011410Z",
     "iopub.status.idle": "2026-11-01T22:13:41.014787Z",
     "shell.execute_reply": "2026-11-01T22:13:41.013436Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c057",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**פלט צפוי (המספרים מוסתרים)**\n",
    "\n",
    "```text\n",
    "July 2012: <number>\n",
    "January 2013: 0\n",
    "```\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "c058",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:41.016476Z",
     "iopub.status.busy": "2026-11-01T22:13:41.016289Z",
     "iopub.status.idle": "2026-11-01T22:13:41.020114Z",
     "shell.execute_reply": "2026-11-01T22:13:41.018976Z"
    }
   },
   "outputs": [],
   "source": [
    "check(6)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c059",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "> **רמז**\n",
    ">\n",
    "> בתוך הפונקציה: שאילתה עם שני פרמטרים `?`, ‏`fetchone`, וביטוי תנאי שמחזיר 0 כשהערך הראשון בשורה הוא `None`.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c060",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## רשימה מתוצאות שאילתה, ו־`max` עם מפתח\n",
    "\n",
    "**[הבנת רשימה](https://dvirross.com/he/courses/intro-data-science/glossary#list-comprehension)** (list comprehension) בונה רשימה בשורה אחת: `[expression for item in rows]` נותנת את הביטוי לכל פריט. הפונקציה `max` מחזירה את הפריט הגדול ביותר ברשימה. כשהפריטים הם טאפלים, `key=` קובע במה משווים: היא מקבלת פונקציה, ו־`lambda pair: pair[1]` היא **[למדה](https://dvirross.com/he/courses/intro-data-science/glossary#lambda)** (lambda), פונקציה בשורה אחת בלי שם שמחזירה את הערך השני של טאפל. אז `max` מחזירה את הטאפל כולו שהערך השני שלו הוא הגדול ביותר.\n",
    "\n",
    "הדוגמה שלמטה אוספת טאפלים `(season, rides)` של 2011, בעזרת הפונקציה מהסעיף הקודם. הקריאה `fetchall` מסתיימת לפני שהלולאה מתחילה, ולכן אותו סמן יכול להריץ את השאילתות שבתוכה. כל שורה של העונות היא טאפל עם ערך אחד, ולכן `season[0]` הוא הטקסט:\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "c061",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:41.021732Z",
     "iopub.status.busy": "2026-11-01T22:13:41.021551Z",
     "iopub.status.idle": "2026-11-01T22:13:41.026569Z",
     "shell.execute_reply": "2026-11-01T22:13:41.025364Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('Winter', 150000), ('Spring', 347316), ('Summer', 419650), ('Fall', 326137)]\n",
      "('Summer', 419650)\n"
     ]
    }
   ],
   "source": [
    "season_totals = [\n",
    "    (season[0], get_season_rides(season[0], 2011))\n",
    "    for season in c.execute(\n",
    "        \"SELECT DISTINCT season FROM daily_ridership\"\n",
    "    ).fetchall()\n",
    "]\n",
    "print(season_totals)\n",
    "print(max(season_totals, key=lambda pair: pair[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c062",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "### משימה 7: רשימה ו־`max`\n",
    "\n",
    "**נסו בעצמכם.** כתבו פונקציה עם השם והפרמטרים האלה:\n",
    "\n",
    "```text\n",
    "get_rides_by_weather_year_month(weather, year, month)\n",
    "```\n",
    "\n",
    "היא מחזירה את מספר ההשכרות הכולל בימים של מזג האוויר הזה בשנה ובחודש האלה, ו־0 כשאין שורה מתאימה. בעזרתה בנו רשימה של טאפלים `(month, rides)` עבור מזג האוויר `'Clear or partly cloudy'` ב־2012, עם טאפל אחד לכל חודש שונה בטבלה (בטבלה יש גם חודשים של 2011, ולכן בוחרים את החודשים של 2012). מצאו עם `max` את הטאפל עם הכי הרבה השכרות והדפיסו אותו.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "c063",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:41.028332Z",
     "iopub.status.busy": "2026-11-01T22:13:41.028160Z",
     "iopub.status.idle": "2026-11-01T22:13:41.031286Z",
     "shell.execute_reply": "2026-11-01T22:13:41.030119Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c064",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "**פלט צפוי (המספרים מוסתרים)**\n",
    "\n",
    "```text\n",
    "(<number>, <number>)\n",
    "```\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "c065",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:41.032823Z",
     "iopub.status.busy": "2026-11-01T22:13:41.032647Z",
     "iopub.status.idle": "2026-11-01T22:13:41.036297Z",
     "shell.execute_reply": "2026-11-01T22:13:41.035181Z"
    }
   },
   "outputs": [],
   "source": [
    "check(7)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c066",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "> **רמז**\n",
    ">\n",
    "> הפונקציה דומה ל־`get_total_rides` עם תנאי אחד נוסף, `weather = ?`. הבנת הרשימה רצה על שאילתה שבוחרת את החודשים השונים של 2012, ו־`month[0]` הוא מספר החודש.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c067",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## שאלות לשיחה\n",
    "\n",
    "- איזה חלק בקוד משתנה כשמזג האוויר, השנה או החודש מגיעים ממשתנים?\n",
    "- מה עלול להשתבש אם ערך מודבק בטקסט ה־SQL עם מחרוזת f?\n",
    "- היכן בקוד שלכם תוצאה של שאילתה הפכה לערך רגיל של Python?\n",
    "\n",
    "## סגירת החיבור\n",
    "\n",
    "השיטה `close` של החיבור סוגרת את מסד הנתונים כשהעבודה נגמרת. סגירה לא שומרת שינויים (תוכנית ששינתה נתונים קוראת קודם ל־`commit`, ראו [SQL מתוך Python](https://dvirross.com/he/courses/intro-data-science/sql-from-python#שינוי-נתונים-ושמירתם)); השאילתות שלנו רק קוראות.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c068",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "הריצו את התא שלמטה כשלב אחרון: הוא משחרר את קובץ מסד הנתונים.\n",
    "\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "c069",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-01T22:13:41.038078Z",
     "iopub.status.busy": "2026-11-01T22:13:41.037877Z",
     "iopub.status.idle": "2026-11-01T22:13:41.041510Z",
     "shell.execute_reply": "2026-11-01T22:13:41.040309Z"
    }
   },
   "outputs": [],
   "source": [
    "conn.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c070",
   "metadata": {},
   "source": [
    "<div dir=\"rtl\">\n",
    "\n",
    "## לזכור\n",
    "\n",
    "- תוכנית שואלת מסד נתונים בארבעה שלבים: `connect`, ‏`cursor`, ‏`execute` ו־`fetch`. ‏`fetchall` מחזירה רשימה של טאפלים, `fetchone` טאפל אחד, ו־`fetchmany(n)` את `n` הטאפלים הבאים.\n",
    "- הערכים של שורה נמצאים לפי הסדר של ה־`SELECT`, וציין לוקח אחד מהם: `row[0]`.\n",
    "- מעבירים ערכים עם `?` וטאפל של ערכים, ולא מדביקים טקסט בתוך ה־SQL.\n",
    "- שאילתת סיכום על אפס שורות נותנת `None`; ביטוי תנאי, כמו ב־`get_total_rides`, הופך אותה ל־0.\n",
    "- ‏`max` עם `key=lambda pair: pair[1]` מחזירה את הטאפל שהערך השני שלו הוא הגדול ביותר.\n",
    "\n",
    "</div>"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "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.13.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
