{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 3: Loops and functions\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 2, Tuesday.\n",
    "\n",
    "This notebook follows the lesson page. Read the text, run the cell under it with Shift + Enter, then change the values in the cell and run it again. Seeing the output change is how the rules become clear.\n",
    "\n",
    "Run the cells from top to bottom. The practice problems are in a separate notebook, topic-03-practice.ipynb.\n",
    "\n",
    "What matters most today: the `for` loop with `range()`, the `while` loop with its start, condition and update, writing a function with `def`, parameters and `return`, and the difference between `print` and `return`. Lambda functions, scope and recursion are a first look; they come back in later topics (lambda already in the next one, with `map` and `filter`). There are 31 solved problems at the end. Start with Level 1 and come back for the rest.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. The for loop\n",
    "2. The while loop\n",
    "3. break, continue, loop else, nested loops and patterns\n",
    "4. Functions\n",
    "5. Parameters, arguments and return values\n",
    "6. Lambda functions\n",
    "7. Scope\n",
    "8. Recursion\n",
    "9. How to approach problems\n",
    "10. Common mistakes\n",
    "11. Solved problems\n",
    "12. Summary"
   ],
   "id": "t03-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Why do we need loops?\n",
    "\n",
    "You should already know variables, data types, operators, and `if/else`. The examples use numbers, text, and Boolean values only.\n",
    "\n",
    "Imagine you must print \"Hello\" five times. Without loops you copy and paste:"
   ],
   "id": "t03-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Hello\")\n",
    "print(\"Hello\")\n",
    "print(\"Hello\")\n",
    "print(\"Hello\")\n",
    "print(\"Hello\")"
   ],
   "id": "t03-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now imagine 1,000 times. That is not realistic. A loop repeats a block of code for you. Change 5 to 10 below: one number controls how often the block runs."
   ],
   "id": "t03-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(5):\n",
    "    print(\"Hello\")"
   ],
   "id": "t03-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Loops are used whenever a task repeats: adding up numbers, checking every character of a word, repeating a question until the user answers correctly, running a game until it ends, and so on.\n",
    "\n",
    "Python has two kinds of loops:\n",
    "\n",
    "- The `for` loop repeats a known number of times.\n",
    "- The `while` loop repeats as long as a condition is True."
   ],
   "id": "t03-005"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. The for loop\n",
    "\n",
    "### 1.1 Syntax\n",
    "\n",
    "```python\n",
    "for variable in sequence:\n",
    "    # code that repeats\n",
    "```\n",
    "\n",
    "The most common \"sequence\" is `range()`, which produces numbers. Change 5 to 3 below, then to 1. What is always the first number?"
   ],
   "id": "t03-006"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(5):\n",
    "    print(number)"
   ],
   "id": "t03-007"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notice that `range(5)` gives 0, 1, 2, 3, 4. It starts at 0 and stops before 5.\n",
    "\n",
    "### 1.2 How range() works\n",
    "\n",
    "| Code | Numbers produced | Meaning |\n",
    "|---|---|---|\n",
    "| `range(5)` | 0, 1, 2, 3, 4 | from 0 up to (not including) 5 |\n",
    "| `range(1, 6)` | 1, 2, 3, 4, 5 | from 1 up to (not including) 6 |\n",
    "| `range(0, 10, 2)` | 0, 2, 4, 6, 8 | the third number is the step |\n",
    "| `range(10, 0, -2)` | 10, 8, 6, 4, 2 | a negative step counts down |\n",
    "| `range(5, 1)` | nothing | start is already past the end |\n",
    "\n",
    "Remember: the stop value is never included. To count from 1 to 10, write `range(1, 11)`.\n",
    "\n",
    "To see all the numbers of a range at once, wrap it in `list()` (lists are the topic of the next lesson):"
   ],
   "id": "t03-008"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(list(range(5)))\n",
    "print(list(range(1, 6)))\n",
    "print(list(range(0, 10, 2)))\n",
    "print(list(range(10, 0, -2)))\n",
    "print(list(range(5, 1)))"
   ],
   "id": "t03-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(1, 6):\n",
    "    print(number)"
   ],
   "id": "t03-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Change the step from -3 to -2. Is 0 ever printed?"
   ],
   "id": "t03-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(10, 0, -3):\n",
    "    print(number)"
   ],
   "id": "t03-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 How Python runs a for loop\n",
    "\n",
    "For `for i in range(3):` Python does this:\n",
    "\n",
    "1. Put the first value (0) into `i`, run the block.\n",
    "2. Put the next value (1) into `i`, run the block.\n",
    "3. Put the next value (2) into `i`, run the block.\n",
    "4. No values are left, so the loop ends and Python continues below it.\n",
    "\n",
    "Each run of the block is called an iteration. The variable (`i`, `number`, anything you like) is called the loop variable.\n",
    "\n",
    "### 1.4 Looping over text\n",
    "\n",
    "A string is a sequence of characters, so a `for` loop can visit each character. Put your own name between the quotes."
   ],
   "id": "t03-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for letter in \"Python\":\n",
    "    print(letter)"
   ],
   "id": "t03-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.5 The accumulator pattern (adding things up)\n",
    "\n",
    "A very common job is to collect a result as the loop runs. Create a variable before the loop, and update it inside. Change `range(1, 6)` to `range(1, 11)`: the total becomes 55."
   ],
   "id": "t03-015"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "total = 0\n",
    "for i in range(1, 6):\n",
    "    total = total + i\n",
    "print(\"Total:\", total)"
   ],
   "id": "t03-016"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is what happens step by step (a trace table):\n",
    "\n",
    "| Iteration | i | total after the update |\n",
    "|---|---|---|\n",
    "| start | | 0 |\n",
    "| 1 | 1 | 1 |\n",
    "| 2 | 2 | 3 |\n",
    "| 3 | 3 | 6 |\n",
    "| 4 | 4 | 10 |\n",
    "| 5 | 5 | 15 |\n",
    "\n",
    "Tracing a loop on paper like this is the best way to understand and debug it.\n",
    "\n",
    "### 1.6 Printing on the same line\n",
    "\n",
    "`print()` normally ends with a new line. Use `end=\" \"` to put a space instead. The empty `print()` at the end moves to a new line."
   ],
   "id": "t03-017"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(1, 6):\n",
    "    print(number, end=\" \")\n",
    "print()"
   ],
   "id": "t03-018"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.7 Useful facts about for\n",
    "\n",
    "If the range is empty (like `range(5, 1)`), the loop body runs zero times."
   ],
   "id": "t03-019"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(5, 1):\n",
    "    print(number)\n",
    "print(\"The loop body ran zero times.\")"
   ],
   "id": "t03-020"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After the loop, the loop variable keeps its last value."
   ],
   "id": "t03-021"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(1, 4):\n",
    "    print(number)\n",
    "print(\"After the loop, number is still\", number)"
   ],
   "id": "t03-022"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you don't need the loop variable, many programmers name it `_`."
   ],
   "id": "t03-023"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for _ in range(3):\n",
    "    print(\"Hi\")"
   ],
   "id": "t03-024"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. The while loop\n",
    "\n",
    "### 2.1 Syntax\n",
    "\n",
    "```python\n",
    "while condition:\n",
    "    # code that repeats as long as the condition is True\n",
    "```\n",
    "\n",
    "A `while` loop works like an `if` statement that keeps coming back. Python checks the condition. If it is True, it runs the block and then checks the condition again. When the condition becomes False, the loop stops.\n",
    "\n",
    "Change `count <= 5` to `count < 5` below. Which line disappears?"
   ],
   "id": "t03-025"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "count = 1\n",
    "while count <= 5:\n",
    "    print(\"Count is\", count)\n",
    "    count = count + 1\n",
    "print(\"Done\")"
   ],
   "id": "t03-026"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 The three parts of a while loop\n",
    "\n",
    "1. Start: create the variable before the loop (`count = 1`).\n",
    "2. Condition: decide when to keep going (`count <= 5`).\n",
    "3. Update: change the variable inside the loop (`count = count + 1`).\n",
    "\n",
    "### 2.3 The infinite loop (the classic danger)\n",
    "\n",
    "If the condition never becomes False, the loop never stops. This one is shown as text, so that \"Run All\" does not hang:\n",
    "\n",
    "```python\n",
    "count = 1\n",
    "while count <= 5:\n",
    "    print(\"Count is\", count)\n",
    "    # forgot to update count, so this runs forever!\n",
    "```\n",
    "\n",
    "How to stop a runaway loop: in Jupyter, click the stop (square) button or use Kernel, then Interrupt. In a terminal, press Ctrl + C. Always double-check that something inside the loop moves it toward ending.\n",
    "\n",
    "### 2.4 When you don't know how many times\n",
    "\n",
    "`while` is the right tool when the number of repeats isn't known in advance. How many times must you double 1 before it passes 1000? Then change 1000 to 1000000."
   ],
   "id": "t03-027"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "amount = 1\n",
    "steps = 0\n",
    "while amount <= 1000:\n",
    "    amount = amount * 2\n",
    "    steps = steps + 1\n",
    "print(amount, \"after\", steps, \"doublings\")"
   ],
   "id": "t03-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5 Repeat until the user gives a valid answer\n",
    "\n",
    "Run the cell and type a wrong password or two, then `python123`. The loop keeps asking until the answer is right."
   ],
   "id": "t03-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "asiman": {
     "typed": [
      "hello",
      "abc",
      "python123"
     ]
    }
   },
   "outputs": [],
   "source": [
    "password = \"\"\n",
    "while password != \"python123\":\n",
    "    password = input(\"Enter the password: \")\n",
    "print(\"Access granted\")"
   ],
   "id": "t03-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6 while True with break\n",
    "\n",
    "Sometimes it is clearer to loop \"forever\" and stop from inside with `break` (explained in part 3):"
   ],
   "id": "t03-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 1\n",
    "while True:\n",
    "    if n * n > 200:\n",
    "        break\n",
    "    n = n + 1\n",
    "print(\"First n whose square is above 200:\", n)"
   ],
   "id": "t03-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.7 for vs while (the differences)\n",
    "\n",
    "| | for loop | while loop |\n",
    "|---|---|---|\n",
    "| Repeats | a fixed, known number of times | as long as a condition is True |\n",
    "| Best when | you know how many times (or have a range) | you don't know how many times |\n",
    "| Counter | handled automatically by `range()` | you create and update it yourself |\n",
    "| Risk of infinite loop | very low | high, if you forget the update |\n",
    "| Typical use | counting, going through every character | waiting for something, repeating until valid, digit processing |\n",
    "| Length of code | usually shorter | usually a bit longer |\n",
    "\n",
    "The same task both ways (print 1 to 5):"
   ],
   "id": "t03-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# for version\n",
    "for i in range(1, 6):\n",
    "    print(i)"
   ],
   "id": "t03-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# while version\n",
    "i = 1\n",
    "while i <= 5:\n",
    "    print(i)\n",
    "    i = i + 1"
   ],
   "id": "t03-035"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How to choose:\n",
    "\n",
    "- \"Do this 10 times\" or \"for each number from 1 to 100\" means `for`.\n",
    "- \"Keep doing this until something happens\" or \"while the number is bigger than 0\" means `while`.\n",
    "\n",
    "Every `for` loop can be rewritten as a `while` loop, but not always the other way around in a simple form."
   ],
   "id": "t03-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. break, continue, loop else, nested loops and patterns\n",
    "\n",
    "### 3.1 break: stop the loop immediately\n",
    "\n",
    "Without `break`, the loop below would keep going to 199. With it, we leave as soon as we find the answer. Change 13 to 17 in both places."
   ],
   "id": "t03-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(101, 200):\n",
    "    if number % 13 == 0:\n",
    "        print(\"First multiple of 13 above 100:\", number)\n",
    "        break"
   ],
   "id": "t03-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 continue: skip to the next iteration\n",
    "\n",
    "`continue` skips the rest of the current iteration and jumps to the next one. Even numbers are skipped, so only odd numbers print."
   ],
   "id": "t03-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(1, 10):\n",
    "    if number % 2 == 0:\n",
    "        continue\n",
    "    print(number)"
   ],
   "id": "t03-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.3 else on a loop (a Python special)\n",
    "\n",
    "A loop can have an `else` block. It runs only if the loop finished without hitting `break`."
   ],
   "id": "t03-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 7\n",
    "for divisor in range(2, number):\n",
    "    if number % divisor == 0:\n",
    "        print(number, \"is not prime\")\n",
    "        break\n",
    "else:\n",
    "    print(number, \"is prime\")"
   ],
   "id": "t03-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If a divisor had been found, `break` would skip the `else` part. Here is the same code with 9, which is divisible by 3. Set `number` to 11, 15 and 13."
   ],
   "id": "t03-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 9\n",
    "for divisor in range(2, number):\n",
    "    if number % divisor == 0:\n",
    "        print(number, \"is not prime\")\n",
    "        break\n",
    "else:\n",
    "    print(number, \"is prime\")"
   ],
   "id": "t03-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.4 pass\n",
    "\n",
    "`pass` does nothing. It is a placeholder when Python needs a block but you have nothing to write yet."
   ],
   "id": "t03-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(3):\n",
    "    pass    # nothing to do yet\n",
    "\n",
    "print(\"The loop ran, but did nothing.\")"
   ],
   "id": "t03-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.5 Nested loops (a loop inside a loop)\n",
    "\n",
    "You can put one loop inside another. For each step of the outer loop, the inner loop runs completely. Change both ranges to `range(1, 6)` to get a 5 by 5 table."
   ],
   "id": "t03-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for row in range(1, 4):\n",
    "    for column in range(1, 4):\n",
    "        print(row * column, end=\" \")\n",
    "    print()"
   ],
   "id": "t03-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How it works:\n",
    "\n",
    "- `row = 1`: the inner loop runs `column = 1, 2, 3`, printing 1 2 3. Then `print()` starts a new line.\n",
    "- `row = 2`: the inner loop runs again, printing 2 4 6.\n",
    "- `row = 3`: printing 3 6 9.\n",
    "\n",
    "The inner body ran 3 x 3 = 9 times in total. Nested loops are used for tables, grids, and patterns."
   ],
   "id": "t03-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "runs = 0\n",
    "for row in range(1, 4):\n",
    "    for column in range(1, 4):\n",
    "        runs = runs + 1\n",
    "print(\"The inner body ran\", runs, \"times\")"
   ],
   "id": "t03-050"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.6 Common loop patterns\n",
    "\n",
    "| Pattern | Idea | Example |\n",
    "|---|---|---|\n",
    "| Counter | count how many times something happens | `count = count + 1` inside an `if` |\n",
    "| Accumulator (sum) | add values together | `total = total + i` |\n",
    "| Accumulator (product) | multiply values together (start at 1!) | `result = result * i` |\n",
    "| Build text | add characters to a string | `reversed_word = letter + reversed_word` |\n",
    "| Search | stop when found | `if ...: ... break` |\n",
    "| Repeat until valid | keep asking | `while answer != \"yes\":` |\n",
    "\n",
    "The counter pattern: how many numbers from 1 to 20 are divisible by 3?"
   ],
   "id": "t03-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "count = 0\n",
    "for number in range(1, 21):\n",
    "    if number % 3 == 0:\n",
    "        count = count + 1\n",
    "print(\"Numbers divisible by 3:\", count)"
   ],
   "id": "t03-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The product pattern. It must start at 1, because anything multiplied by 0 stays 0."
   ],
   "id": "t03-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = 1\n",
    "for i in range(1, 6):\n",
    "    result = result * i\n",
    "print(\"1 x 2 x 3 x 4 x 5 =\", result)"
   ],
   "id": "t03-054"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Building text (reversing a word). Each new letter is placed in front of the previous result, so the word grows backwards. Put your own word between the quotes."
   ],
   "id": "t03-055"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "word = \"hello\"\n",
    "reversed_word = \"\"\n",
    "for letter in word:\n",
    "    reversed_word = letter + reversed_word\n",
    "print(reversed_word)"
   ],
   "id": "t03-056"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Functions\n",
    "\n",
    "### 4.1 What is a function?\n",
    "\n",
    "A function is a named block of code that does one job. You write it once, then call it whenever you need it.\n",
    "\n",
    "Real-life picture: a vending machine. You give it something (money and a choice), it does the work inside, and it gives something back (a snack). You don't need to know how it works inside.\n",
    "\n",
    "You already use functions:\n",
    "\n",
    "| Function | What it does |\n",
    "|---|---|\n",
    "| `print()` | shows something on the screen |\n",
    "| `input()` | asks the user for text |\n",
    "| `len(\"hello\")` | counts the characters in a text |\n",
    "| `abs(-5)` | gives the positive value |\n",
    "| `round(3.14159, 2)` | rounds a number |\n",
    "| `int(\"5\")` | converts text to a whole number |\n",
    "| `type(5)` | tells the data type |"
   ],
   "id": "t03-057"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(len(\"hello\"))\n",
    "print(abs(-5))\n",
    "print(round(3.14159, 2))\n",
    "print(int(\"5\"))\n",
    "print(type(5))"
   ],
   "id": "t03-058"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now you will learn to write your own.\n",
    "\n",
    "### 4.2 Why use functions? (advantages over normal code)\n",
    "\n",
    "Suppose a shop adds 20% tax to prices. Without a function you repeat the formula everywhere:"
   ],
   "id": "t03-059"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "price1 = 100\n",
    "price2 = 250\n",
    "price3 = 80\n",
    "\n",
    "total1 = price1 + price1 * 20 / 100\n",
    "total2 = price2 + price2 * 20 / 100\n",
    "total3 = price3 + price3 * 20 / 100\n",
    "\n",
    "print(total1)\n",
    "print(total2)\n",
    "print(total3)"
   ],
   "id": "t03-060"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With a function you write the formula once. The tax becomes 18%: change 20 to 18. You edit one place, and all three results change."
   ],
   "id": "t03-061"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_tax(price):\n",
    "    return price + price * 20 / 100\n",
    "\n",
    "print(add_tax(100))\n",
    "print(add_tax(250))\n",
    "print(add_tax(80))"
   ],
   "id": "t03-062"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| Advantage | What it means |\n",
    "|---|---|\n",
    "| Reuse | write once, use as many times as you want |\n",
    "| Less repetition (DRY) | \"Don't Repeat Yourself\": fewer copy-pasted lines |\n",
    "| Easy to change | if the tax becomes 18%, you edit one place, not 100 |\n",
    "| Fewer mistakes | one tested formula instead of many copies that may differ |\n",
    "| Readability | `add_tax(100)` tells you the intention; a raw formula doesn't |\n",
    "| Easy testing | you can test a small function separately |\n",
    "| Organization | a big program becomes small, named pieces |\n",
    "| Teamwork | people can build different functions at the same time |\n",
    "| Hiding details (abstraction) | users of the function don't need to know how it works inside |\n",
    "\n",
    "### 4.3 Defining and calling functions\n",
    "\n",
    "```python\n",
    "def function_name():\n",
    "    # code of the function (indented)\n",
    "```\n",
    "\n",
    "- `def` is the keyword that defines a function.\n",
    "- Then the name, parentheses `()`, and a colon `:`.\n",
    "- The body is indented by 4 spaces."
   ],
   "id": "t03-063"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say_hello():\n",
    "    print(\"Hello!\")\n",
    "    print(\"Welcome to Python functions.\")\n",
    "\n",
    "say_hello()\n",
    "say_hello()"
   ],
   "id": "t03-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.4 Defining is not running\n",
    "\n",
    "- `def` only stores the instructions. Nothing happens yet.\n",
    "- The code inside runs only when you call the function with `name()`.\n",
    "- You must define a function before you call it (higher in the file).\n",
    "- The parentheses are required to call it. `say_hello` alone does nothing.\n",
    "\n",
    "Defined, but never called:"
   ],
   "id": "t03-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say_hello():\n",
    "    print(\"Hello!\")\n",
    "\n",
    "print(\"The function is defined, but nobody called it.\")"
   ],
   "id": "t03-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Written without the parentheses:"
   ],
   "id": "t03-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def say_hello():\n",
    "    print(\"Hello!\")\n",
    "\n",
    "say_hello      # no parentheses: the function is not called\n",
    "print(\"Nothing was printed by say_hello.\")"
   ],
   "id": "t03-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Called before it is defined (shown as text, because it fails in a fresh program):\n",
    "\n",
    "```python\n",
    "say_hello()\n",
    "\n",
    "def say_hello():\n",
    "    print(\"Hello!\")\n",
    "```\n",
    "\n",
    "```\n",
    "NameError: name 'say_hello' is not defined\n",
    "```\n",
    "\n",
    "### 4.5 What happens when you call a function\n",
    "\n",
    "1. Python reaches the call: `say_hello()`\n",
    "2. It jumps into the function and runs the body line by line\n",
    "3. When the body ends, it jumps back to just after the call\n",
    "4. The program continues\n",
    "\n",
    "### 4.6 Naming rules and style\n",
    "\n",
    "- Same rules as variable names: letters, numbers, underscores, no spaces, not starting with a number.\n",
    "- Use lowercase with underscores: `calculate_area`, not `CalculateArea`.\n",
    "- Use verbs that describe the job: `add_tax`, `is_even`, `print_report`.\n",
    "\n",
    "### 4.7 Docstrings (documenting a function)\n",
    "\n",
    "A text in triple quotes as the first line of the body explains what the function does. You can read it later with `help(add_tax)`."
   ],
   "id": "t03-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_tax(price):\n",
    "    \"\"\"Return the price plus 20% tax.\"\"\"\n",
    "    return price + price * 20 / 100\n",
    "\n",
    "print(add_tax(50))"
   ],
   "id": "t03-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Parameters, arguments and return values\n",
    "\n",
    "### 5.1 Parameters and arguments\n",
    "\n",
    "Functions become powerful when they can receive inputs.\n",
    "\n",
    "| Term | Meaning | Example |\n",
    "|---|---|---|\n",
    "| Parameter | the variable name in the function definition | `name` in `def greet(name):` |\n",
    "| Argument | the actual value you pass in when calling | `\"Aylin\"` in `greet(\"Aylin\")` |\n",
    "\n",
    "Add a call with your own name."
   ],
   "id": "t03-071"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def greet(name):\n",
    "    print(\"Hello,\", name)\n",
    "\n",
    "greet(\"Aylin\")\n",
    "greet(\"Murad\")"
   ],
   "id": "t03-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.2 Several parameters"
   ],
   "id": "t03-073"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rectangle_area(width, height):\n",
    "    return width * height\n",
    "\n",
    "print(rectangle_area(5, 3))"
   ],
   "id": "t03-074"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.3 Positional vs. keyword arguments\n",
    "\n",
    "- Positional: the values are matched by position. Order matters.\n",
    "- Keyword: you write `parameter_name=value`, so order does not matter."
   ],
   "id": "t03-075"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def subtract(a, b):\n",
    "    return a - b\n",
    "\n",
    "print(subtract(10, 3))\n",
    "print(subtract(3, 10))\n",
    "print(subtract(b=3, a=10))"
   ],
   "id": "t03-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.4 Default values\n",
    "\n",
    "You can give a parameter a default that is used when the caller doesn't provide one:"
   ],
   "id": "t03-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def greet(name, greeting=\"Hello\"):\n",
    "    print(greeting + \", \" + name + \"!\")\n",
    "\n",
    "greet(\"Aylin\")\n",
    "greet(\"Aylin\", \"Good morning\")"
   ],
   "id": "t03-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add `print(power(2, 10))` at the end of the next cell."
   ],
   "id": "t03-079"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def power(base, exponent=2):\n",
    "    return base ** exponent\n",
    "\n",
    "print(power(5))\n",
    "print(power(5, 3))"
   ],
   "id": "t03-080"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Rule: parameters with defaults must come after those without defaults. `def f(a=1, b):` causes a SyntaxError:\n",
    "\n",
    "```python\n",
    "def f(a=1, b):\n",
    "    return a + b\n",
    "```\n",
    "\n",
    "```\n",
    "SyntaxError: parameter without a default follows parameter with a default\n",
    "```\n",
    "\n",
    "### 5.5 Wrong number of arguments\n",
    "\n",
    "```python\n",
    "def rectangle_area(width, height):\n",
    "    return width * height\n",
    "\n",
    "rectangle_area(5)\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: rectangle_area() missing 1 required positional argument: 'height'\n",
    "```\n",
    "\n",
    "### 5.6 Arguments can be variables or expressions"
   ],
   "id": "t03-081"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def double(n):\n",
    "    return n * 2\n",
    "\n",
    "x = 7\n",
    "print(double(x))\n",
    "print(double(x + 3))\n",
    "print(double(double(2)))"
   ],
   "id": "t03-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python does not check the type of arguments for you. `add(\"5\", 3)` would crash when it tries to add text and a number. Make sure you pass the right kind of value.\n",
    "\n",
    "```python\n",
    "def add(a, b):\n",
    "    return a + b\n",
    "\n",
    "print(add(\"5\", 3))\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: can only concatenate str (not \"int\") to str\n",
    "```\n",
    "\n",
    "### 5.7 return sends a result back\n",
    "\n",
    "The call `add(2, 3)` is replaced by its returned value (5), so you can store it in a variable or use it inside bigger expressions."
   ],
   "id": "t03-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add(a, b):\n",
    "    return a + b\n",
    "\n",
    "result = add(2, 3)\n",
    "print(result)\n",
    "print(add(10, 20) * 2)"
   ],
   "id": "t03-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.8 print vs. return (a very important difference)\n",
    "\n",
    "| | print() | return |\n",
    "|---|---|---|\n",
    "| Purpose | shows something to the human | gives a value back to the program |\n",
    "| Can the result be reused? | no | yes (store it, calculate with it) |\n",
    "| Ends the function? | no | yes |"
   ],
   "id": "t03-085"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def show_double(n):\n",
    "    print(n * 2)      # only displays\n",
    "\n",
    "def get_double(n):\n",
    "    return n * 2      # gives the value back\n",
    "\n",
    "a = show_double(4)    # prints 8, but a receives nothing useful\n",
    "b = get_double(4)     # prints nothing, b receives 8\n",
    "\n",
    "print(\"a is\", a)\n",
    "print(\"b is\", b)"
   ],
   "id": "t03-086"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A function without `return` gives back `None`. `None` is Python's \"nothing here\" value. That is why `a` above is None.\n",
    "\n",
    "### 5.9 return ends the function immediately\n",
    "\n",
    "Lines after `return` are never executed:"
   ],
   "id": "t03-087"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def test():\n",
    "    print(\"Before return\")\n",
    "    return 1\n",
    "    print(\"After return (never runs)\")\n",
    "\n",
    "print(test())"
   ],
   "id": "t03-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.10 Several return statements\n",
    "\n",
    "A function can return from different places, often together with `if`:"
   ],
   "id": "t03-089"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sign(n):\n",
    "    if n > 0:\n",
    "        return \"positive\"\n",
    "    elif n < 0:\n",
    "        return \"negative\"\n",
    "    return \"zero\"\n",
    "\n",
    "print(sign(5))\n",
    "print(sign(-2))\n",
    "print(sign(0))"
   ],
   "id": "t03-090"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.11 Functions that return True or False\n",
    "\n",
    "Functions that answer a yes/no question are very useful inside `if` and loops. Call `is_adult(15)` instead: nothing is printed."
   ],
   "id": "t03-091"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_adult(age):\n",
    "    return age >= 18\n",
    "\n",
    "if is_adult(20):\n",
    "    print(\"Welcome!\")"
   ],
   "id": "t03-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5.12 Functions can call other functions"
   ],
   "id": "t03-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def square(n):\n",
    "    return n * n\n",
    "\n",
    "def sum_of_squares(a, b):\n",
    "    return square(a) + square(b)\n",
    "\n",
    "print(sum_of_squares(3, 4))"
   ],
   "id": "t03-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For now, a function returns one value. (Returning several values at once uses a data type called a tuple, which belongs to a later topic.)"
   ],
   "id": "t03-095"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Lambda functions: a small function in one line\n",
    "\n",
    "### 6.1 What is a lambda function?\n",
    "\n",
    "A lambda is a small function written in one line, without `def` and without a name. It takes parameters and gives back the value of one expression. Here is the same function written both ways. Change `n * 2` to `n * 3` in the lambda only: the two results are now different."
   ],
   "id": "t03-096"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def double(n):\n",
    "    return n * 2\n",
    "\n",
    "double_short = lambda n: n * 2\n",
    "\n",
    "print(double(5))\n",
    "print(double_short(5))"
   ],
   "id": "t03-097"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both are called in the same way, with parentheses and an argument. The only difference is how they are written.\n",
    "\n",
    "### 6.2 Syntax\n",
    "\n",
    "```python\n",
    "lambda parameters: expression\n",
    "```\n",
    "\n",
    "1. The keyword `lambda` starts the function. It replaces `def` and the name.\n",
    "2. The parameters, without parentheses. Several are separated by commas.\n",
    "3. A colon.\n",
    "4. One expression. Its value is returned automatically: you do not write `return`.\n",
    "\n",
    "### 6.3 Parameters: none, one, several, with a default\n",
    "\n",
    "Everything you learned about parameters in part 5 works here too. Add a third parameter to `add` and call it with three numbers."
   ],
   "id": "t03-098"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "add = lambda a, b: a + b\n",
    "print(add(2, 3))\n",
    "\n",
    "greeting = lambda: \"Hello!\"\n",
    "print(greeting())\n",
    "\n",
    "power = lambda base, exponent=2: base ** exponent\n",
    "print(power(5))\n",
    "print(power(5, 3))"
   ],
   "id": "t03-099"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.4 A lambda that decides\n",
    "\n",
    "A lambda has room for one expression only, so an `if` block does not fit. The one-line `if/else` from the last lesson is an expression, so it does. Then write a lambda `smaller` that returns the smaller of two numbers."
   ],
   "id": "t03-100"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "parity = lambda n: \"even\" if n % 2 == 0 else \"odd\"\n",
    "print(parity(7))\n",
    "print(parity(10))\n",
    "\n",
    "larger = lambda a, b: a if a > b else b\n",
    "print(larger(12, 45))"
   ],
   "id": "t03-101"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.5 A lambda is a value\n",
    "\n",
    "A lambda creates a function, and a function is a value like a number or a text. You can store it in a variable, and you can even use it at once without giving it a name. That is why a lambda is also called an anonymous function (a function without a name)."
   ],
   "id": "t03-102"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "square = lambda n: n * n\n",
    "\n",
    "print(type(square))\n",
    "print(square(4))\n",
    "print((lambda n: n * n)(4))"
   ],
   "id": "t03-103"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 6.6 def vs. lambda (the differences)\n",
    "\n",
    "| | def function | lambda |\n",
    "|---|---|---|\n",
    "| Name | always has a name | no name (it can be stored in a variable) |\n",
    "| Length | one or many lines | always one line |\n",
    "| Body | any code: several steps, loops, if blocks | one expression only |\n",
    "| `return` | you write it | automatic: the value of the expression is returned |\n",
    "| Docstring | yes | no |\n",
    "| Best for | a job with several steps, or one that you reuse | a tiny job used once, usually given to another function |\n",
    "\n",
    "Writing `return` inside a lambda is an error, because `return` is a statement, not an expression:\n",
    "\n",
    "```python\n",
    "square = lambda n: return n * n\n",
    "```\n",
    "\n",
    "```\n",
    "SyntaxError: invalid syntax\n",
    "```\n",
    "\n",
    "### 6.7 Where lambdas are really used: as an argument\n",
    "\n",
    "A function can receive another function as an argument. In part 4 you saw that a function name without parentheses does not call the function: it is the function itself. That is exactly what we pass. Pass `lambda n: n - 1` too, and predict the result before you run it."
   ],
   "id": "t03-104"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def apply_twice(function, value):\n",
    "    return function(function(value))\n",
    "\n",
    "def add_ten(n):\n",
    "    return n + 10\n",
    "\n",
    "print(apply_twice(add_ten, 5))\n",
    "print(apply_twice(lambda n: n * 2, 5))\n",
    "print(apply_twice(lambda text: text + \"!\", \"Hi\"))"
   ],
   "id": "t03-105"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`add_ten` needed two extra lines and a name. The lambda is written right where it is used. This is the real job of a lambda: a small rule that you hand to another function.\n",
    "\n",
    "Several built-in functions accept such a rule. `max` and `min` take a `key`: a function that says what to compare."
   ],
   "id": "t03-106"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(max(-7, 3, 5))\n",
    "print(max(-7, 3, 5, key=abs))\n",
    "print(max(-7, 3, 5, key=lambda n: n * n))\n",
    "\n",
    "print(min(\"pear\", \"fig\", \"banana\", key=len))\n",
    "print(max(\"pear\", \"fig\", \"banana\", key=lambda word: word.count(\"a\")))"
   ],
   "id": "t03-107"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- `key=abs` compares the numbers without their sign, so -7 wins.\n",
    "- `key=len` compares the lengths of the words, so `min` gives the shortest word.\n",
    "- When no ready function exists for your rule, a lambda writes it on the spot.\n",
    "\n",
    "In the next lesson, `map`, `filter` and `sorted` receive a function in exactly this way. A lambda is what you will usually give them, for example `map(lambda n: n * 2, numbers)`.\n",
    "\n",
    "### 6.8 When not to use a lambda\n",
    "\n",
    "- The job needs more than one step, a loop, or several decisions: write `def`.\n",
    "- You reuse the function in many places: give it a proper name with `def`. (Storing a lambda in a variable, as in the examples above, is good for learning. In real programs, Python's style guide recommends `def` for that.)\n",
    "- The line becomes hard to read. Short code is good only while it stays clear."
   ],
   "id": "t03-108"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def describe(score):\n",
    "    if score >= 90:\n",
    "        return \"excellent\"\n",
    "    elif score >= 50:\n",
    "        return \"pass\"\n",
    "    return \"fail\"\n",
    "\n",
    "describe_short = lambda score: \"excellent\" if score >= 90 else \"pass\" if score >= 50 else \"fail\"\n",
    "\n",
    "print(describe(95), describe(60), describe(30))\n",
    "print(describe_short(95), describe_short(60), describe_short(30))"
   ],
   "id": "t03-109"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both give the same answers. The first one is easier to read, to test and to change."
   ],
   "id": "t03-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Scope: where a variable lives\n",
    "\n",
    "Scope means the part of the program where a variable can be used.\n",
    "\n",
    "### 7.1 Local scope\n",
    "\n",
    "A variable created inside a function is local. It exists only while the function runs and cannot be used outside."
   ],
   "id": "t03-111"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def show():\n",
    "    message = \"I am local\"\n",
    "    print(message)\n",
    "\n",
    "show()"
   ],
   "id": "t03-112"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using it outside the function fails:\n",
    "\n",
    "```python\n",
    "def show():\n",
    "    message = \"I am local\"\n",
    "    print(message)\n",
    "\n",
    "show()\n",
    "print(message)\n",
    "```\n",
    "\n",
    "```\n",
    "NameError: name 'message' is not defined\n",
    "```\n",
    "\n",
    "Parameters are also local variables of the function.\n",
    "\n",
    "### 7.2 Global scope\n",
    "\n",
    "A variable created outside all functions is global. A function can read it:"
   ],
   "id": "t03-113"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tax_rate = 20\n",
    "\n",
    "def add_tax(price):\n",
    "    return price + price * tax_rate / 100\n",
    "\n",
    "print(add_tax(50))"
   ],
   "id": "t03-114"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.3 Same name, different variables\n",
    "\n",
    "A variable assigned inside a function is a new local one, even if a global one has the same name. The global one is not changed:"
   ],
   "id": "t03-115"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 10\n",
    "\n",
    "def change():\n",
    "    x = 99\n",
    "    print(\"inside:\", x)\n",
    "\n",
    "change()\n",
    "print(\"outside:\", x)"
   ],
   "id": "t03-116"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Likewise, a parameter name doesn't affect a global variable with the same name:"
   ],
   "id": "t03-117"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def double(n):\n",
    "    return n * 2\n",
    "\n",
    "n = 100\n",
    "print(double(5))\n",
    "print(n)"
   ],
   "id": "t03-118"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.4 Changing a global variable (the global keyword)\n",
    "\n",
    "To modify a global variable inside a function, you must declare it with `global`:"
   ],
   "id": "t03-119"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "count = 0\n",
    "\n",
    "def increase():\n",
    "    global count\n",
    "    count = count + 1\n",
    "\n",
    "increase()\n",
    "increase()\n",
    "print(count)"
   ],
   "id": "t03-120"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Without the `global` line, Python treats `count` as local and raises an UnboundLocalError:\n",
    "\n",
    "```python\n",
    "count = 0\n",
    "\n",
    "def increase():\n",
    "    count = count + 1\n",
    "\n",
    "increase()\n",
    "```\n",
    "\n",
    "```\n",
    "UnboundLocalError: cannot access local variable 'count' where it is not associated with a value\n",
    "```\n",
    "\n",
    "### 7.5 The better way: pass in, return out\n",
    "\n",
    "Using `global` makes programs harder to understand because functions secretly change things. Prefer sending values in as parameters and getting results out with `return`:"
   ],
   "id": "t03-121"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def increase(count):\n",
    "    return count + 1\n",
    "\n",
    "count = 0\n",
    "count = increase(count)\n",
    "count = increase(count)\n",
    "print(count)"
   ],
   "id": "t03-122"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.6 Variables die when the function ends\n",
    "\n",
    "Local variables are created when the function is called and destroyed when it returns. Calling the function again starts fresh."
   ],
   "id": "t03-123"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def count_once():\n",
    "    counter = 0\n",
    "    counter = counter + 1\n",
    "    print(\"counter is\", counter)\n",
    "\n",
    "count_once()\n",
    "count_once()"
   ],
   "id": "t03-124"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.7 Loops do not create a new scope\n",
    "\n",
    "Unlike functions, a `for` or `while` loop does not have its own scope:"
   ],
   "id": "t03-125"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(3):\n",
    "    pass\n",
    "print(i)"
   ],
   "id": "t03-126"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 7.8 Local vs. global summary\n",
    "\n",
    "| | Local variable | Global variable |\n",
    "|---|---|---|\n",
    "| Created | inside a function | outside all functions |\n",
    "| Usable | only inside that function | everywhere (can be read in functions) |\n",
    "| Lifetime | until the function ends | until the program ends |\n",
    "| Changing inside a function | free | needs the `global` keyword (avoid it) |\n",
    "\n",
    "### 7.9 Loops vs. functions vs. normal code\n",
    "\n",
    "These tools solve different problems, and they work best together.\n",
    "\n",
    "| | Normal code | Loop | Function |\n",
    "|---|---|---|---|\n",
    "| Runs | once, top to bottom | many times in place | each time it is called |\n",
    "| Main purpose | one-time steps | repeat actions | package a job for reuse |\n",
    "| Reuse in other places | copy and paste | copy and paste | just call it |\n",
    "| Takes inputs | no | no | yes (parameters) |\n",
    "| Gives a result back | no | no | yes (`return`) |\n",
    "| Example | `x = 5` | `for i in range(5):` | `def add_tax(price):` |\n",
    "\n",
    "Combining them:\n",
    "\n",
    "- A function can contain a loop (`factorial(n)` uses a loop inside).\n",
    "- A loop can call a function (call `is_prime(n)` for every number in a range).\n",
    "\n",
    "Both at once: the function below has a loop inside, and the loop at the bottom calls the function."
   ],
   "id": "t03-127"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_prime(n):\n",
    "    if n < 2:\n",
    "        return False\n",
    "    for divisor in range(2, n):\n",
    "        if n % divisor == 0:\n",
    "            return False\n",
    "    return True\n",
    "\n",
    "for number in range(1, 11):\n",
    "    if is_prime(number):\n",
    "        print(number, \"is prime\")"
   ],
   "id": "t03-128"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Recursion: a function that calls itself\n",
    "\n",
    "### 8.1 The idea\n",
    "\n",
    "Recursion means a function solves a problem by calling itself on a smaller version of the same problem. Think of Russian nesting dolls: to open the biggest doll you open the next one inside, and so on, until you reach the smallest.\n",
    "\n",
    "Every recursive function needs two parts:\n",
    "\n",
    "1. Base case: the simplest situation where the answer is known, so the function stops.\n",
    "2. Recursive case: the function calls itself with a smaller input, moving toward the base case.\n",
    "\n",
    "Call `countdown(5)` after running the cell once."
   ],
   "id": "t03-129"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def countdown(n):\n",
    "    if n == 0:                 # base case\n",
    "        print(\"Liftoff!\")\n",
    "    else:\n",
    "        print(n)\n",
    "        countdown(n - 1)       # recursive case\n",
    "\n",
    "countdown(3)"
   ],
   "id": "t03-130"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.2 How recursion runs (the call stack)\n",
    "\n",
    "For `factorial(3)` where `factorial(n) = n * factorial(n - 1)`:\n",
    "\n",
    "```\n",
    "factorial(3) waits for  3 * factorial(2)\n",
    "  factorial(2) waits for  2 * factorial(1)\n",
    "    factorial(1) returns 1            (base case)\n",
    "  factorial(2) returns 2 * 1 = 2\n",
    "factorial(3) returns 3 * 2 = 6\n",
    "```\n",
    "\n",
    "Python remembers each waiting call on a \"stack\", then finishes them in reverse order. Print `factorial(5)` too: it unfolds as 5 * 4 * 3 * 2 * 1."
   ],
   "id": "t03-131"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def factorial(n):\n",
    "    if n <= 1:                     # base case\n",
    "        return 1\n",
    "    return n * factorial(n - 1)    # recursive case\n",
    "\n",
    "print(factorial(3))"
   ],
   "id": "t03-132"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 8.3 What if there is no base case?\n",
    "\n",
    "```python\n",
    "def forever(n):\n",
    "    return forever(n + 1)\n",
    "\n",
    "forever(1)\n",
    "```\n",
    "\n",
    "```\n",
    "RecursionError: maximum recursion depth exceeded\n",
    "```\n",
    "\n",
    "Python stops you after about 1000 nested calls. Always make sure the input gets smaller and a base case exists.\n",
    "\n",
    "### 8.4 Recursion vs. loops\n",
    "\n",
    "| | Loop version | Recursive version |\n",
    "|---|---|---|\n",
    "| Idea | repeat steps with a counter | solve a smaller copy of the problem |\n",
    "| Code length | usually longer | often shorter and closer to the math definition |\n",
    "| Speed and memory | fast, little memory | slower, uses extra memory for every call |\n",
    "| Risk | infinite loop | RecursionError (too deep) |\n",
    "| Best for | simple counting and repeating | problems that naturally contain smaller copies of themselves |\n",
    "\n",
    "A warning about recursive Fibonacci: it recalculates the same values again and again. Here we count how many function calls it makes (this also shows `global` in action). Change 20 to 10, then to 25, and watch how fast the number of calls grows."
   ],
   "id": "t03-133"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "calls = 0\n",
    "\n",
    "def fib(n):\n",
    "    global calls\n",
    "    calls = calls + 1\n",
    "    if n <= 1:\n",
    "        return n\n",
    "    return fib(n - 1) + fib(n - 2)\n",
    "\n",
    "print(fib(20))\n",
    "print(\"Function calls:\", calls)"
   ],
   "id": "t03-134"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finding the 20th Fibonacci number needs 21,891 calls. The loop version does the same job with only 20 steps. That is why loops are often better for simple repeated work."
   ],
   "id": "t03-135"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. How to approach problems with loops and functions\n",
    "\n",
    "1. Understand the problem. Write what goes in (inputs) and what must come out (result).\n",
    "2. Try a small example by hand. For \"sum of digits of 1234\", work it out on paper and notice the steps.\n",
    "3. Choose the tool. Known number of repeats means `for`. Unknown means `while`. A reusable job means a function.\n",
    "4. Plan the loop. What is the starting value? What is the condition? What changes each time?\n",
    "5. Write the code and trace it with a small input using a trace table.\n",
    "6. Test edge cases: 0, 1, negative numbers, very big numbers."
   ],
   "id": "t03-136"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10. Common mistakes\n",
    "\n",
    "Loop mistakes\n",
    "\n",
    "| Mistake | What happens | Fix |\n",
    "|---|---|---|\n",
    "| Off-by-one with `range` | `range(1, 10)` stops at 9 | use `range(1, 11)` to include 10 |\n",
    "| Forgetting the update in `while` | infinite loop | change the variable inside the loop |\n",
    "| Resetting the accumulator inside the loop | `total = 0` placed in the loop erases progress | create it before the loop |\n",
    "| Starting a product at 0 | everything becomes 0 | start multiplication at 1 |\n",
    "| Wrong indentation | code runs at the wrong time or not at all | indent the loop body by 4 spaces |\n",
    "| Using `range()` with decimals | TypeError | `range()` only accepts whole numbers |\n",
    "| Forgetting `int()` for input | text used as a number | `n = int(input())` |\n",
    "| Wrong condition direction | `while n < 0` when you meant `> 0`: the loop never starts | trace with a small example |\n",
    "\n",
    "Two of them run without any error and simply give a wrong answer. The accumulator is reset in every round, so only the last number is left:"
   ],
   "id": "t03-137"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(1, 6):\n",
    "    total = 0\n",
    "    total = total + i\n",
    "print(\"Total:\", total)"
   ],
   "id": "t03-138"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The print is indented, so it belongs to the loop and runs in every round:"
   ],
   "id": "t03-139"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "total = 0\n",
    "for i in range(1, 4):\n",
    "    total = total + i\n",
    "    print(\"Total:\", total)"
   ],
   "id": "t03-140"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Function mistakes\n",
    "\n",
    "| Mistake | What happens | Fix |\n",
    "|---|---|---|\n",
    "| Forgetting the colon after `def ...()` | SyntaxError | add `:` |\n",
    "| Calling before defining | NameError | define the function higher in the file |\n",
    "| Forgetting the parentheses on a call | nothing happens | write `say_hello()` |\n",
    "| Using `print` instead of `return` | the result can't be reused (you get None) | `return` the value |\n",
    "| Wrong number of arguments | TypeError | match the parameters |\n",
    "| Using a local variable outside the function | NameError | return it, or define it outside |\n",
    "| Putting code after `return` | it never runs | place `return` last |\n",
    "| Recursion with no base case | RecursionError | add a base case and shrink the input |\n",
    "| Writing `return` inside a lambda | SyntaxError | leave `return` out: `lambda n: n * n` |\n",
    "| Calling a function while passing it: `apply_twice(add_ten(5), 5)` | TypeError | pass the name without parentheses: `add_ten` |\n",
    "| Overusing `global` | confusing, bug-prone code | use parameters and `return` |\n",
    "\n",
    "The message Python shows for a missing colon:\n",
    "\n",
    "```python\n",
    "def say_hello()\n",
    "    print(\"Hello!\")\n",
    "```\n",
    "\n",
    "```\n",
    "SyntaxError: expected ':'\n",
    "```\n",
    "\n",
    "And for `range()` with a decimal step:\n",
    "\n",
    "```python\n",
    "for x in range(0, 1, 0.1):\n",
    "    print(x)\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: 'float' object cannot be interpreted as an integer\n",
    "```"
   ],
   "id": "t03-141"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 11. Solved problems\n",
    "\n",
    "Every example was run, and the outputs are real. Each one shows the problem, the code, and why it works.\n",
    "\n",
    "### Level 1: Easy"
   ],
   "id": "t03-142"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 1. Print the numbers 1 to 5"
   ],
   "id": "t03-143"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for number in range(1, 6):\n",
    "    print(number)"
   ],
   "id": "t03-144"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While version:"
   ],
   "id": "t03-145"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 1\n",
    "while number <= 5:\n",
    "    print(number)\n",
    "    number = number + 1"
   ],
   "id": "t03-146"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `range(1, 6)` stops before 6. In the `while` version we create, test, and update the counter ourselves."
   ],
   "id": "t03-147"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. Sum of the numbers from 1 to n\n",
    "\n",
    "Set `n` to 100: the answer is 5050."
   ],
   "id": "t03-148"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 10\n",
    "total = 0\n",
    "for i in range(1, n + 1):\n",
    "    total = total + i\n",
    "print(\"Sum of 1 to\", n, \"is\", total)"
   ],
   "id": "t03-149"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While version:"
   ],
   "id": "t03-150"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 10\n",
    "total = 0\n",
    "i = 1\n",
    "while i <= n:\n",
    "    total = total + i\n",
    "    i = i + 1\n",
    "print(\"Sum of 1 to\", n, \"is\", total)"
   ],
   "id": "t03-151"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the accumulator starts at 0 and grows. (A shortcut formula also exists: `n * (n + 1) // 2` gives 55.)"
   ],
   "id": "t03-152"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 3. Countdown"
   ],
   "id": "t03-153"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "count = 5\n",
    "while count >= 1:\n",
    "    print(count)\n",
    "    count = count - 1\n",
    "print(\"Liftoff!\")"
   ],
   "id": "t03-154"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For version (counting down with a negative step):"
   ],
   "id": "t03-155"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for count in range(5, 0, -1):\n",
    "    print(count)\n",
    "print(\"Liftoff!\")"
   ],
   "id": "t03-156"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. Multiplication table of 7\n",
    "\n",
    "Make it the table of 9 by changing both 7s."
   ],
   "id": "t03-157"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(1, 11):\n",
    "    print(\"7 x\", i, \"=\", 7 * i)"
   ],
   "id": "t03-158"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the loop variable `i` changes from 1 to 10 and is used in every line."
   ],
   "id": "t03-159"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 5. Sum of the even numbers from 1 to 20"
   ],
   "id": "t03-160"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "total = 0\n",
    "for number in range(2, 21, 2):\n",
    "    total = total + number\n",
    "print(\"Sum of even numbers:\", total)"
   ],
   "id": "t03-161"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alternative with `if`:"
   ],
   "id": "t03-162"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "total = 0\n",
    "for number in range(1, 21):\n",
    "    if number % 2 == 0:\n",
    "        total = total + number\n",
    "print(\"Sum of even numbers:\", total)"
   ],
   "id": "t03-163"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the first version uses a step of 2 so it never visits odd numbers. The second visits all numbers and filters them with `if`."
   ],
   "id": "t03-164"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 6. Count the vowels in a word"
   ],
   "id": "t03-165"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "word = \"programming\"\n",
    "vowel_count = 0\n",
    "\n",
    "for letter in word:\n",
    "    if letter in \"aeiou\":\n",
    "        vowel_count = vowel_count + 1\n",
    "\n",
    "print(\"Vowels in\", word, \":\", vowel_count)"
   ],
   "id": "t03-166"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `letter in \"aeiou\"` checks whether the letter appears inside the text `\"aeiou\"`. This is the counter pattern."
   ],
   "id": "t03-167"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 7. A function with two parameters"
   ],
   "id": "t03-168"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def introduce(name, age):\n",
    "    print(\"My name is\", name, \"and I am\", age, \"years old.\")\n",
    "\n",
    "introduce(\"Aylin\", 20)\n",
    "introduce(\"Murad\", 25)"
   ],
   "id": "t03-169"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the function does the printing, and each call supplies different arguments."
   ],
   "id": "t03-170"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 8. Square and cube"
   ],
   "id": "t03-171"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def square(n):\n",
    "    return n * n\n",
    "\n",
    "def cube(n):\n",
    "    return n * n * n\n",
    "\n",
    "print(square(6))\n",
    "print(cube(3))\n",
    "print(square(4) + cube(2))"
   ],
   "id": "t03-172"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: because the functions return values, we can combine them in a calculation."
   ],
   "id": "t03-173"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 9. Even checker and the larger of two numbers"
   ],
   "id": "t03-174"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_even(number):\n",
    "    return number % 2 == 0\n",
    "\n",
    "def larger(a, b):\n",
    "    if a > b:\n",
    "        return a\n",
    "    return b\n",
    "\n",
    "print(is_even(10))\n",
    "print(is_even(7))\n",
    "print(larger(12, 45))"
   ],
   "id": "t03-175"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `is_even` returns a Boolean directly. In `larger`, the second `return` only runs when the `if` was not true, so no `else` is needed."
   ],
   "id": "t03-176"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Level 2: Medium"
   ],
   "id": "t03-177"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 10. Factorial (loop version and recursion version)\n",
    "\n",
    "The factorial of n (written n!) is 1 x 2 x 3 x ... x n. For example 5! = 120. By definition, 0! = 1."
   ],
   "id": "t03-178"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Loop version:"
   ],
   "id": "t03-179"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def factorial_loop(n):\n",
    "    result = 1\n",
    "    for i in range(2, n + 1):\n",
    "        result = result * i\n",
    "    return result\n",
    "\n",
    "print(factorial_loop(5))\n",
    "print(factorial_loop(0))\n",
    "print(factorial_loop(10))"
   ],
   "id": "t03-180"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Recursive version:"
   ],
   "id": "t03-181"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def factorial_recursive(n):\n",
    "    if n <= 1:                      # base case\n",
    "        return 1\n",
    "    return n * factorial_recursive(n - 1)   # recursive case\n",
    "\n",
    "print(factorial_recursive(5))\n",
    "print(factorial_recursive(0))"
   ],
   "id": "t03-182"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the loop multiplies as it goes (the product starts at 1). The recursive version follows the definition n! = n x (n-1)!, and stops at the base case. For 5! the calls unfold like this: `5 * 4 * 3 * 2 * 1`."
   ],
   "id": "t03-183"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 11. Power without using **"
   ],
   "id": "t03-184"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def power(base, exponent):\n",
    "    result = 1\n",
    "    for _ in range(exponent):\n",
    "        result = result * base\n",
    "    return result\n",
    "\n",
    "print(power(2, 10))\n",
    "print(power(5, 0))\n",
    "print(power(3, 4))"
   ],
   "id": "t03-185"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: multiplying `base` by itself `exponent` times. We use `_` because we don't need the loop variable."
   ],
   "id": "t03-186"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 12. Fibonacci numbers (loop and recursion)\n",
    "\n",
    "The Fibonacci sequence starts 0, 1, and every next number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, ..."
   ],
   "id": "t03-187"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Print the first 10 terms:"
   ],
   "id": "t03-188"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 0\n",
    "b = 1\n",
    "for _ in range(10):\n",
    "    print(a, end=\" \")\n",
    "    next_value = a + b\n",
    "    a = b\n",
    "    b = next_value\n",
    "print()"
   ],
   "id": "t03-189"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A function that returns the n-th term (loop version):"
   ],
   "id": "t03-190"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fibonacci_loop(n):\n",
    "    a = 0\n",
    "    b = 1\n",
    "    for _ in range(n):\n",
    "        next_value = a + b\n",
    "        a = b\n",
    "        b = next_value\n",
    "    return a\n",
    "\n",
    "print(fibonacci_loop(10))\n",
    "print(fibonacci_loop(50))"
   ],
   "id": "t03-191"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Recursive version:"
   ],
   "id": "t03-192"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def fibonacci_recursive(n):\n",
    "    if n <= 1:                                  # base cases: fib(0)=0, fib(1)=1\n",
    "        return n\n",
    "    return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)\n",
    "\n",
    "print(fibonacci_recursive(10))"
   ],
   "id": "t03-193"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the recursive code reads exactly like the definition, but it is very slow for big inputs (see part 8). The loop version keeps only the last two values and is instant, even for `n = 50`."
   ],
   "id": "t03-194"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 13. Sum of the digits of a number\n",
    "\n",
    "For 1234 the answer is 1 + 2 + 3 + 4 = 10."
   ],
   "id": "t03-195"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 1234\n",
    "total = 0\n",
    "\n",
    "while number > 0:\n",
    "    digit = number % 10      # last digit\n",
    "    total = total + digit\n",
    "    number = number // 10    # remove the last digit\n",
    "\n",
    "print(\"Sum of digits:\", total)"
   ],
   "id": "t03-196"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Trace table:\n",
    "\n",
    "| number at the start | digit | total | number after // 10 |\n",
    "|---|---|---|---|\n",
    "| 1234 | 4 | 4 | 123 |\n",
    "| 123 | 3 | 7 | 12 |\n",
    "| 12 | 2 | 9 | 1 |\n",
    "| 1 | 1 | 10 | 0 (loop ends) |\n",
    "\n",
    "As a function (loop version and recursive version):"
   ],
   "id": "t03-197"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sum_of_digits(n):\n",
    "    total = 0\n",
    "    while n > 0:\n",
    "        total = total + n % 10\n",
    "        n = n // 10\n",
    "    return total\n",
    "\n",
    "def sum_of_digits_recursive(n):\n",
    "    if n < 10:                                    # base case: a single digit\n",
    "        return n\n",
    "    return n % 10 + sum_of_digits_recursive(n // 10)\n",
    "\n",
    "print(sum_of_digits(98765))\n",
    "print(sum_of_digits_recursive(98765))"
   ],
   "id": "t03-198"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `% 10` gives the last digit and `// 10` removes it. This is the standard trick for working with digits using `while`."
   ],
   "id": "t03-199"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 14. Count the digits and reverse a number"
   ],
   "id": "t03-200"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def count_digits(n):\n",
    "    if n == 0:\n",
    "        return 1\n",
    "    count = 0\n",
    "    while n > 0:\n",
    "        count = count + 1\n",
    "        n = n // 10\n",
    "    return count\n",
    "\n",
    "def reverse_number(n):\n",
    "    reversed_n = 0\n",
    "    while n > 0:\n",
    "        digit = n % 10\n",
    "        reversed_n = reversed_n * 10 + digit\n",
    "        n = n // 10\n",
    "    return reversed_n\n",
    "\n",
    "print(count_digits(98765))\n",
    "print(count_digits(0))\n",
    "print(reverse_number(1234))\n",
    "print(reverse_number(1200))"
   ],
   "id": "t03-201"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: to reverse, we take the last digit of `n` and attach it to the end of `reversed_n` (multiply by 10, then add). `1200` becomes `21` because a number cannot keep leading zeros."
   ],
   "id": "t03-202"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 15. Palindromes (numbers and text)\n",
    "\n",
    "A palindrome reads the same forwards and backwards (121, \"level\")."
   ],
   "id": "t03-203"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Palindrome number:"
   ],
   "id": "t03-204"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def reverse_number(n):\n",
    "    reversed_n = 0\n",
    "    while n > 0:\n",
    "        reversed_n = reversed_n * 10 + n % 10\n",
    "        n = n // 10\n",
    "    return reversed_n\n",
    "\n",
    "def is_palindrome_number(n):\n",
    "    return n == reverse_number(n)\n",
    "\n",
    "print(is_palindrome_number(121))\n",
    "print(is_palindrome_number(123))\n",
    "print(is_palindrome_number(1221))"
   ],
   "id": "t03-205"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Palindrome text:"
   ],
   "id": "t03-206"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_palindrome_text(text):\n",
    "    text = text.lower()\n",
    "    reversed_text = \"\"\n",
    "    for letter in text:\n",
    "        reversed_text = letter + reversed_text\n",
    "    return text == reversed_text\n",
    "\n",
    "print(is_palindrome_text(\"Level\"))\n",
    "print(is_palindrome_text(\"Python\"))\n",
    "print(is_palindrome_text(\"Racecar\"))"
   ],
   "id": "t03-207"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: both build the reversed version and compare it with the original. For text we use `.lower()` first so that capital letters don't matter. (This simple version doesn't handle spaces or punctuation.)"
   ],
   "id": "t03-208"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 16. Prime number checker\n",
    "\n",
    "A prime number is greater than 1 and divisible only by 1 and itself."
   ],
   "id": "t03-209"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_prime(n):\n",
    "    if n < 2:\n",
    "        return False\n",
    "    divisor = 2\n",
    "    while divisor * divisor <= n:\n",
    "        if n % divisor == 0:\n",
    "            return False\n",
    "        divisor = divisor + 1\n",
    "    return True\n",
    "\n",
    "print(is_prime(17))\n",
    "print(is_prime(18))\n",
    "print(is_prime(1))\n",
    "print(is_prime(2))"
   ],
   "id": "t03-210"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Print all primes up to 30:"
   ],
   "id": "t03-211"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_prime(n):\n",
    "    if n < 2:\n",
    "        return False\n",
    "    divisor = 2\n",
    "    while divisor * divisor <= n:\n",
    "        if n % divisor == 0:\n",
    "            return False\n",
    "        divisor = divisor + 1\n",
    "    return True\n",
    "\n",
    "for number in range(2, 31):\n",
    "    if is_prime(number):\n",
    "        print(number, end=\" \")\n",
    "print()"
   ],
   "id": "t03-212"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: we only need to test divisors up to the square root of `n` (that is why the condition is `divisor * divisor <= n`). If any divisor works, we return False immediately. If none works, the number is prime. The final loop shows how a loop can call a function."
   ],
   "id": "t03-213"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 17. Temperature conversion table\n",
    "\n",
    "Change the step from 20 to 10."
   ],
   "id": "t03-214"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def celsius_to_fahrenheit(c):\n",
    "    return c * 9 / 5 + 32\n",
    "\n",
    "for celsius in range(0, 101, 20):\n",
    "    print(celsius, \"C =\", celsius_to_fahrenheit(celsius), \"F\")"
   ],
   "id": "t03-215"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the function holds the formula once, and the loop produces a whole table using a step of 20."
   ],
   "id": "t03-216"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 18. A grade function used inside a loop"
   ],
   "id": "t03-217"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_grade(score):\n",
    "    if score >= 90:\n",
    "        return \"A\"\n",
    "    elif score >= 80:\n",
    "        return \"B\"\n",
    "    elif score >= 70:\n",
    "        return \"C\"\n",
    "    elif score >= 60:\n",
    "        return \"D\"\n",
    "    else:\n",
    "        return \"F\"\n",
    "\n",
    "for score in range(55, 100, 10):\n",
    "    print(score, \"->\", get_grade(score))"
   ],
   "id": "t03-218"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `if/elif/else` inside a function with several `return` statements. Each `return` ends the function, so no extra `else` is needed after it."
   ],
   "id": "t03-219"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 19. A calculator function"
   ],
   "id": "t03-220"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def calculate(a, b, operator):\n",
    "    if operator == \"+\":\n",
    "        return a + b\n",
    "    elif operator == \"-\":\n",
    "        return a - b\n",
    "    elif operator == \"*\":\n",
    "        return a * b\n",
    "    elif operator == \"/\":\n",
    "        if b == 0:\n",
    "            return \"Error: cannot divide by zero\"\n",
    "        return a / b\n",
    "    else:\n",
    "        return \"Unknown operator\"\n",
    "\n",
    "print(calculate(10, 5, \"+\"))\n",
    "print(calculate(10, 4, \"/\"))\n",
    "print(calculate(10, 0, \"/\"))\n",
    "print(calculate(10, 5, \"%\"))"
   ],
   "id": "t03-221"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the function combines everything from the `if/else` topic and makes it reusable with any numbers and operators."
   ],
   "id": "t03-222"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Level 3: Medium-Hard"
   ],
   "id": "t03-223"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 20. Greatest common divisor (GCD) and least common multiple (LCM)\n",
    "\n",
    "The GCD of 48 and 18 is 6, the biggest number that divides both."
   ],
   "id": "t03-224"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Euclid's algorithm with a `while` loop:"
   ],
   "id": "t03-225"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def gcd(a, b):\n",
    "    while b != 0:\n",
    "        remainder = a % b\n",
    "        a = b\n",
    "        b = remainder\n",
    "    return a\n",
    "\n",
    "def lcm(a, b):\n",
    "    return a * b // gcd(a, b)\n",
    "\n",
    "print(gcd(48, 18))\n",
    "print(lcm(4, 6))"
   ],
   "id": "t03-226"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Trace for `gcd(48, 18)`:\n",
    "\n",
    "| a | b | a % b |\n",
    "|---|---|---|\n",
    "| 48 | 18 | 12 |\n",
    "| 18 | 12 | 6 |\n",
    "| 12 | 6 | 0 |\n",
    "| 6 | 0 | (stop, answer is 6) |\n",
    "\n",
    "Recursive version:"
   ],
   "id": "t03-227"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def gcd_recursive(a, b):\n",
    "    if b == 0:\n",
    "        return a\n",
    "    return gcd_recursive(b, a % b)\n",
    "\n",
    "print(gcd_recursive(48, 18))"
   ],
   "id": "t03-228"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the key idea is that `gcd(a, b)` equals `gcd(b, a % b)`. The loop and the recursion do exactly the same steps."
   ],
   "id": "t03-229"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 21. The Collatz sequence\n",
    "\n",
    "Start with any positive whole number. If it is even, divide it by 2. If it is odd, multiply by 3 and add 1. Repeat until you reach 1. How many steps does it take?"
   ],
   "id": "t03-230"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def collatz_steps(n):\n",
    "    steps = 0\n",
    "    while n != 1:\n",
    "        if n % 2 == 0:\n",
    "            n = n // 2\n",
    "        else:\n",
    "            n = 3 * n + 1\n",
    "        steps = steps + 1\n",
    "    return steps\n",
    "\n",
    "print(collatz_steps(6))\n",
    "print(collatz_steps(27))"
   ],
   "id": "t03-231"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: we don't know in advance how many steps it will take, so `while` is the right choice. For 6 the path is 6, 3, 10, 5, 16, 8, 4, 2, 1, which is 8 steps."
   ],
   "id": "t03-232"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 22. Guessing a number by halving\n",
    "\n",
    "A number between 1 and 100 is hidden. Always guess the middle of the remaining range. How many guesses does it take? Change the secret to 1, 100 or 50 and count the guesses."
   ],
   "id": "t03-233"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "secret = 73\n",
    "low = 1\n",
    "high = 100\n",
    "guesses = 0\n",
    "\n",
    "while True:\n",
    "    middle = (low + high) // 2\n",
    "    guesses = guesses + 1\n",
    "    if middle == secret:\n",
    "        print(\"Found\", secret, \"in\", guesses, \"guesses\")\n",
    "        break\n",
    "    elif middle < secret:\n",
    "        low = middle + 1\n",
    "    else:\n",
    "        high = middle - 1"
   ],
   "id": "t03-234"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: each guess throws away half of the possibilities. This idea (called binary search) can find any number from 1 to 100 in at most 7 guesses. It uses `while True` with `break`."
   ],
   "id": "t03-235"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 23. How many years until the money doubles?\n",
    "\n",
    "You save 1000 at 5% yearly interest. After how many years do you have at least 2000? Then change 105 to 110, which is 10% a year."
   ],
   "id": "t03-236"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "balance = 1000\n",
    "years = 0\n",
    "\n",
    "while balance < 2000:\n",
    "    balance = balance * 105 / 100\n",
    "    years = years + 1\n",
    "\n",
    "print(\"Money doubles after\", years, \"years\")\n",
    "print(\"Balance:\", round(balance, 2))"
   ],
   "id": "t03-237"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: we don't know the number of years in advance. The loop runs while the goal is not reached."
   ],
   "id": "t03-238"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 24. Armstrong numbers\n",
    "\n",
    "A 3-digit number is an Armstrong number if the sum of the cubes of its digits equals the number. Example: 153 = 1³ + 5³ + 3³."
   ],
   "id": "t03-239"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_armstrong(n):\n",
    "    original = n\n",
    "    total = 0\n",
    "    while n > 0:\n",
    "        digit = n % 10\n",
    "        total = total + digit ** 3\n",
    "        n = n // 10\n",
    "    return total == original\n",
    "\n",
    "for number in range(100, 1000):\n",
    "    if is_armstrong(number):\n",
    "        print(number, end=\" \")\n",
    "print()"
   ],
   "id": "t03-240"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: it combines a `while` loop (digit extraction) inside a function, called from a `for` loop that tests every 3-digit number. Note that we saved `original` first because `n` gets destroyed by the loop."
   ],
   "id": "t03-241"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 25. Perfect numbers\n",
    "\n",
    "A number is perfect if it equals the sum of its divisors smaller than itself. Example: 6 = 1 + 2 + 3."
   ],
   "id": "t03-242"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sum_of_divisors(n):\n",
    "    total = 0\n",
    "    for i in range(1, n):\n",
    "        if n % i == 0:\n",
    "            total = total + i\n",
    "    return total\n",
    "\n",
    "for number in range(2, 1001):\n",
    "    if sum_of_divisors(number) == number:\n",
    "        print(number, \"is perfect\")"
   ],
   "id": "t03-243"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: this is a nested structure: the outer loop goes through the numbers, and each call of the function runs its own inner loop to add the divisors."
   ],
   "id": "t03-244"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 26. Convert a decimal number to binary"
   ],
   "id": "t03-245"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def to_binary(n):\n",
    "    if n == 0:\n",
    "        return \"0\"\n",
    "    binary = \"\"\n",
    "    while n > 0:\n",
    "        remainder = n % 2\n",
    "        binary = str(remainder) + binary\n",
    "        n = n // 2\n",
    "    return binary\n",
    "\n",
    "print(to_binary(10))\n",
    "print(to_binary(255))\n",
    "print(to_binary(0))"
   ],
   "id": "t03-246"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: repeatedly divide by 2 and collect the remainders. The last remainder is the first digit, so each new digit is placed in front (`str(remainder) + binary`)."
   ],
   "id": "t03-247"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 27. Star patterns (nested loops and text repetition)"
   ],
   "id": "t03-248"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A right triangle. Change `rows` to 8."
   ],
   "id": "t03-249"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rows = 5\n",
    "for i in range(1, rows + 1):\n",
    "    print(\"*\" * i)"
   ],
   "id": "t03-250"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A centered pyramid:"
   ],
   "id": "t03-251"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rows = 5\n",
    "for i in range(1, rows + 1):\n",
    "    spaces = \" \" * (rows - i)\n",
    "    stars = \"*\" * (2 * i - 1)\n",
    "    print(spaces + stars)"
   ],
   "id": "t03-252"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The right triangle again, the nested-loop way:"
   ],
   "id": "t03-253"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rows = 5\n",
    "for i in range(1, rows + 1):\n",
    "    for _ in range(i):\n",
    "        print(\"*\", end=\"\")\n",
    "    print()"
   ],
   "id": "t03-254"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `\"*\" * i` repeats the text `i` times. Row `i` of the pyramid needs `rows - i` spaces and `2 * i - 1` stars. The same result can be built with an inner loop that prints one star at a time, which is the nested-loop way."
   ],
   "id": "t03-255"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 28. Digital root\n",
    "\n",
    "Keep adding the digits of a number until a single digit remains. 9875 gives 9 + 8 + 7 + 5 = 29, then 2 + 9 = 11, then 1 + 1 = 2."
   ],
   "id": "t03-256"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sum_of_digits(n):\n",
    "    total = 0\n",
    "    while n > 0:\n",
    "        total = total + n % 10\n",
    "        n = n // 10\n",
    "    return total\n",
    "\n",
    "def digital_root(n):\n",
    "    while n >= 10:\n",
    "        n = sum_of_digits(n)\n",
    "    return n\n",
    "\n",
    "print(digital_root(9875))\n",
    "print(digital_root(5))"
   ],
   "id": "t03-257"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: a `while` loop in one function calls another function that has its own `while` loop. Splitting the work into two small functions keeps each one easy to understand."
   ],
   "id": "t03-258"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 29. A countdown with recursion and a loop"
   ],
   "id": "t03-259"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def countdown_recursive(n):\n",
    "    if n == 0:\n",
    "        return\n",
    "    print(n)\n",
    "    countdown_recursive(n - 1)\n",
    "\n",
    "countdown_recursive(4)"
   ],
   "id": "t03-260"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def countdown_loop(n):\n",
    "    while n > 0:\n",
    "        print(n)\n",
    "        n = n - 1\n",
    "\n",
    "countdown_loop(4)"
   ],
   "id": "t03-261"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: both functions do the same job. A bare `return` simply ends the function early (and gives back None). Comparing the two shows how recursion replaces the loop counter with a smaller input in each call."
   ],
   "id": "t03-262"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 30. Number of digits that are even, using a loop and a function\n",
    "\n",
    "Count how many digits of a number are even. For 482915 the even digits are 4, 8, 2, so the answer is 3."
   ],
   "id": "t03-263"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_even(number):\n",
    "    return number % 2 == 0\n",
    "\n",
    "def count_even_digits(n):\n",
    "    count = 0\n",
    "    while n > 0:\n",
    "        digit = n % 10\n",
    "        if is_even(digit):\n",
    "            count = count + 1\n",
    "        n = n // 10\n",
    "    return count\n",
    "\n",
    "print(count_even_digits(482915))\n",
    "print(count_even_digits(13579))"
   ],
   "id": "t03-264"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: it brings together all three ideas of this topic: a `while` loop to extract the digits, an `if` to decide, and small functions that each do one job."
   ],
   "id": "t03-265"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 31. Count the numbers that pass a test (a function as an argument)\n",
    "\n",
    "Write one function that counts how many numbers in a range pass a test. The test itself is given as a function, so the same loop can count even numbers, numbers divisible by 3 and 5, primes, or anything else. Then count the numbers from 1 to 100 that end in 7 with `lambda n: n % 10 == 7`."
   ],
   "id": "t03-266"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_prime(n):\n",
    "    if n < 2:\n",
    "        return False\n",
    "    divisor = 2\n",
    "    while divisor * divisor <= n:\n",
    "        if n % divisor == 0:\n",
    "            return False\n",
    "        divisor = divisor + 1\n",
    "    return True\n",
    "\n",
    "def count_if(test, start, stop):\n",
    "    count = 0\n",
    "    for n in range(start, stop + 1):\n",
    "        if test(n):\n",
    "            count = count + 1\n",
    "    return count\n",
    "\n",
    "print(count_if(lambda n: n % 2 == 0, 1, 20))\n",
    "print(count_if(lambda n: n % 3 == 0 and n % 5 == 0, 1, 100))\n",
    "print(count_if(is_prime, 1, 30))"
   ],
   "id": "t03-267"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the loop and the counter are written once, and the rule arrives as the parameter `test`. A short rule is a lambda written at the call. A longer rule such as `is_prime` is a `def` function, passed by its name without parentheses. In the next lesson, `filter` works in exactly this way."
   ],
   "id": "t03-268"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 12. Summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "|---|---|---|\n",
    "| `for` loop | repeats a known number of times | `for i in range(5):` |\n",
    "| `range(a, b, step)` | produces numbers (stop is excluded) | `range(1, 11)` gives 1 to 10 |\n",
    "| `while` loop | repeats while a condition is True | `while n > 0:` |\n",
    "| Infinite loop | a loop that never ends (forgot the update) | stop it with Ctrl + C or Interrupt |\n",
    "| `break` | leaves the loop immediately | `if found: break` |\n",
    "| `continue` | skips to the next iteration | `if n % 2 == 0: continue` |\n",
    "| Nested loop | a loop inside a loop | tables and patterns |\n",
    "| Accumulator | collects a result in a loop | `total = total + i` |\n",
    "| Function | a named, reusable block of code | `def add_tax(price):` |\n",
    "| Parameter / argument | input name / input value | `def f(x)` / `f(5)` |\n",
    "| Default value | used when no argument is given | `def f(x, y=2):` |\n",
    "| `return` | sends a value back and ends the function | `return a + b` |\n",
    "| `print` vs `return` | show to the user vs give back to the program | `return` can be reused |\n",
    "| Lambda | a small one-line function without a name | `lambda n: n * 2` |\n",
    "| Local variable | exists only inside the function | created in a function |\n",
    "| Global variable | exists outside all functions | needs `global` to change inside |\n",
    "| Recursion | a function calling itself with a smaller input | `factorial(n - 1)` |\n",
    "| Base case | the stopping point of recursion | `if n <= 1: return 1` |\n",
    "\n",
    "Golden rules\n",
    "\n",
    "1. Use `for` when you know the number of repeats, and `while` when you don't.\n",
    "2. Always make sure a `while` loop changes something that will end it.\n",
    "3. Start sums at 0 and products at 1, and create them before the loop.\n",
    "4. A function should do one job and have a clear name.\n",
    "5. `return` the result instead of printing it, so it can be reused.\n",
    "6. Prefer parameters and `return` over `global` variables.\n",
    "7. Recursion needs a base case and a smaller input every time.\n",
    "8. Trace with a small example and test edge cases.\n",
    "\n",
    "Next: the practice notebook (topic-03-practice.ipynb), then Topic 4: lists and tuples."
   ],
   "id": "t03-269"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
