{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Topic 2: Control flow with if and else\n",
    "\n",
    "Asiman Data School, Module 1: Foundations of Python Programming. Week 1, Thursday.\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-02-practice.ipynb.\n",
    "\n",
    "Contents\n",
    "\n",
    "1. Conditions\n",
    "2. The if statement\n",
    "3. else and elif\n",
    "4. Nested if and combining conditions\n",
    "5. Truthy values, text and decimals\n",
    "6. Input, one-line if/else, pass\n",
    "7. How to solve a problem\n",
    "8. Common mistakes\n",
    "9. Solved problems\n",
    "10. Summary"
   ],
   "id": "t02-000"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What is control flow?\n",
    "\n",
    "Normally, Python reads your code from the top to the bottom, one line after another. But real programs need to make decisions:\n",
    "\n",
    "- If the user is 18 or older, allow entry. Otherwise, refuse.\n",
    "- If the temperature is below 0, show \"Freezing\". Otherwise, show \"Not freezing\".\n",
    "\n",
    "Control flow means controlling which lines of code run, depending on conditions. The `if` statement is the most important control flow tool, and every program you will ever write uses it.\n",
    "\n",
    "A real-life example: if it is raining, I take an umbrella. Otherwise, I wear sunglasses. In Python that sentence becomes the cell below. Run it, then change `True` to `False` and run it again."
   ],
   "id": "t02-001"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "is_raining = True\n",
    "\n",
    "if is_raining:\n",
    "    print(\"Take an umbrella\")\n",
    "else:\n",
    "    print(\"Wear sunglasses\")"
   ],
   "id": "t02-002"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Conditions\n",
    "\n",
    "An `if` statement asks a yes/no question. In Python, the answer is a Boolean: `True` or `False`. The question is called a condition.\n",
    "\n",
    "Conditions are usually built with comparison operators:\n",
    "\n",
    "| Operator | Meaning | Example | Result |\n",
    "|---|---|---|---|\n",
    "| `==` | equal to | `5 == 5` | `True` |\n",
    "| `!=` | not equal to | `5 != 3` | `True` |\n",
    "| `>` | greater than | `3 > 5` | `False` |\n",
    "| `<` | less than | `3 < 5` | `True` |\n",
    "| `>=` | greater than or equal to | `5 >= 5` | `True` |\n",
    "| `<=` | less than or equal to | `4 <= 3` | `False` |"
   ],
   "id": "t02-003"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(5 == 5)    # equal to\n",
    "print(5 != 3)    # not equal to\n",
    "print(3 > 5)     # greater than\n",
    "print(3 < 5)     # less than\n",
    "print(5 >= 5)    # greater than or equal to\n",
    "print(4 <= 3)    # less than or equal to"
   ],
   "id": "t02-004"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can see the answer directly. Set `age` to 18, then to 17, and find the value where the answer changes."
   ],
   "id": "t02-005"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 20\n",
    "print(age >= 18)   # True"
   ],
   "id": "t02-006"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Remember: `=` stores a value (`age = 20`). `==` compares two values (`age == 20`). Mixing them up is the most common beginner mistake.\n",
    "\n",
    "The answer of a condition is a value like any other, so it can be stored in a variable."
   ],
   "id": "t02-007"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 20\n",
    "is_adult = age >= 18    # the answer is stored like any other value\n",
    "\n",
    "print(is_adult)\n",
    "print(type(is_adult))"
   ],
   "id": "t02-008"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. The if statement\n",
    "\n",
    "The exact shape:\n",
    "\n",
    "```python\n",
    "if condition:\n",
    "    # code that runs only when the condition is True\n",
    "```\n",
    "\n",
    "The three important parts:\n",
    "\n",
    "1. The keyword `if`.\n",
    "2. The condition, then a colon `:`. The colon is required. Forgetting it causes a SyntaxError.\n",
    "3. The indented block, the lines that belong to the `if`.\n",
    "\n",
    "How Python reads it:\n",
    "\n",
    "1. Evaluate the condition (True or False).\n",
    "2. If True, run the indented block.\n",
    "3. If False, skip the indented block and continue below it."
   ],
   "id": "t02-009"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "temperature = 35\n",
    "\n",
    "if temperature > 30:\n",
    "    print(\"It is a hot day!\")\n",
    "\n",
    "print(\"Program finished\")"
   ],
   "id": "t02-010"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you change `temperature` to 20, the condition becomes False, so Python skips the indented line. Try it in the cell above, or run this one:"
   ],
   "id": "t02-011"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "temperature = 20\n",
    "\n",
    "if temperature > 30:\n",
    "    print(\"It is a hot day!\")\n",
    "\n",
    "print(\"Program finished\")"
   ],
   "id": "t02-012"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Indentation\n",
    "\n",
    "Many languages use curly braces to group code. Python uses indentation (spaces at the start of the line).\n",
    "\n",
    "- Use 4 spaces for each level. In Jupyter, pressing the Tab key does this for you.\n",
    "- All lines in the same block must have the same indentation.\n",
    "- The first line that is not indented is outside the block.\n",
    "\n",
    "Set `number` to 3 below: lines 1 and 2 disappear together, line 3 still prints."
   ],
   "id": "t02-013"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 10\n",
    "\n",
    "if number > 5:\n",
    "    print(\"Line 1: inside the if\")\n",
    "    print(\"Line 2: also inside the if\")\n",
    "print(\"Line 3: outside, always runs\")"
   ],
   "id": "t02-014"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Common indentation errors. These two are shown as text, because a cell with an error would stop \"Run All\".\n",
    "\n",
    "The line under the `if` is not indented:\n",
    "\n",
    "```python\n",
    "number = 10\n",
    "\n",
    "if number > 5:\n",
    "print(\"Hello\")\n",
    "```\n",
    "\n",
    "```\n",
    "IndentationError: expected an indented block after 'if' statement on line 3\n",
    "```\n",
    "\n",
    "One line of the block is indented more than the other:\n",
    "\n",
    "```python\n",
    "number = 10\n",
    "\n",
    "if number > 5:\n",
    "    print(\"A\")\n",
    "      print(\"B\")\n",
    "```\n",
    "\n",
    "```\n",
    "IndentationError: unexpected indent\n",
    "```\n",
    "\n",
    "Don't mix tabs and spaces in the same file. Stick to 4 spaces."
   ],
   "id": "t02-015"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. else and elif\n",
    "\n",
    "### if ... else\n",
    "\n",
    "The `else` part runs when the condition is False. Think of it as \"otherwise.\"\n",
    "\n",
    "```python\n",
    "if condition:\n",
    "    # runs when True\n",
    "else:\n",
    "    # runs when False\n",
    "```\n",
    "\n",
    "Key facts about `else`:\n",
    "\n",
    "- It has no condition of its own. It simply catches \"everything else.\"\n",
    "- It must line up (same indentation) with its `if`.\n",
    "- It also needs a colon.\n",
    "- Exactly one of the two blocks runs, never both and never neither.\n",
    "\n",
    "Test the boundary below: set `age` to 18, then to 19."
   ],
   "id": "t02-016"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 17\n",
    "\n",
    "if age >= 18:\n",
    "    print(\"You can vote.\")\n",
    "else:\n",
    "    print(\"You are too young to vote.\")"
   ],
   "id": "t02-017"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### elif (more than two choices)\n",
    "\n",
    "Sometimes there are more than two possibilities. `elif` means \"else if\" and lets you check another condition.\n",
    "\n",
    "```python\n",
    "if condition1:\n",
    "    # runs if condition1 is True\n",
    "elif condition2:\n",
    "    # runs if condition1 is False AND condition2 is True\n",
    "elif condition3:\n",
    "    # ...\n",
    "else:\n",
    "    # runs if none of the above were True\n",
    "```\n",
    "\n",
    "Try 5 and 0 for `number`. Each value should reach a different block."
   ],
   "id": "t02-018"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = -4\n",
    "\n",
    "if number > 0:\n",
    "    print(\"Positive\")\n",
    "elif number < 0:\n",
    "    print(\"Negative\")\n",
    "else:\n",
    "    print(\"Zero\")"
   ],
   "id": "t02-019"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How it works (very important): Python checks the conditions from top to bottom and runs the first block whose condition is True. After that, it skips all the remaining `elif` and `else` parts.\n",
    "\n",
    "- You can use as many `elif` parts as you want.\n",
    "- `else` is optional, and when used it must be last.\n",
    "\n",
    "Order matters. Look at this mistake:"
   ],
   "id": "t02-020"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "score = 95\n",
    "\n",
    "if score >= 60:\n",
    "    print(\"Grade D\")\n",
    "elif score >= 90:\n",
    "    print(\"Grade A\")   # never reached!"
   ],
   "id": "t02-021"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`95 >= 60` is True, so Python stops there. Always put the most specific or strictest condition first:"
   ],
   "id": "t02-022"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "score = 95\n",
    "\n",
    "if score >= 90:\n",
    "    print(\"Grade A\")\n",
    "elif score >= 60:\n",
    "    print(\"Grade D\")"
   ],
   "id": "t02-023"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### if-elif-else vs. several separate ifs\n",
    "\n",
    "These are not the same thing. In a chain (if / elif / else) only one block can run. Separate `if` statements are each checked independently, so several blocks can run."
   ],
   "id": "t02-024"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 15\n",
    "\n",
    "if number % 3 == 0:\n",
    "    print(\"Divisible by 3\")\n",
    "if number % 5 == 0:\n",
    "    print(\"Divisible by 5\")"
   ],
   "id": "t02-025"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If we had used `elif` for the second one, only the first message would appear:"
   ],
   "id": "t02-026"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 15\n",
    "\n",
    "if number % 3 == 0:\n",
    "    print(\"Divisible by 3\")\n",
    "elif number % 5 == 0:\n",
    "    print(\"Divisible by 5\")   # skipped: the first block already ran"
   ],
   "id": "t02-027"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Use separate `if`s when the checks are independent, and `elif` when the choices exclude each other."
   ],
   "id": "t02-028"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Nested if and combining conditions\n",
    "\n",
    "### Nested if (an if inside an if)\n",
    "\n",
    "You can put an `if` inside another `if` to ask a second question after the first one is answered. Each level is indented further.\n",
    "\n",
    "Set `has_ticket` to False, then set `age` to 16, and follow which lines run each time."
   ],
   "id": "t02-029"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 20\n",
    "has_ticket = True\n",
    "\n",
    "if age >= 18:\n",
    "    if has_ticket:\n",
    "        print(\"Welcome to the concert!\")\n",
    "    else:\n",
    "        print(\"Please buy a ticket first.\")\n",
    "else:\n",
    "    print(\"Sorry, 18+ only.\")"
   ],
   "id": "t02-030"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tip: deep nesting becomes hard to read. Often you can replace it with `and`. Two or three levels is a good maximum. Here are the same concert rules without nesting:"
   ],
   "id": "t02-031"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 20\n",
    "has_ticket = True\n",
    "\n",
    "if age >= 18 and has_ticket:\n",
    "    print(\"Welcome to the concert!\")\n",
    "elif age >= 18:\n",
    "    print(\"Please buy a ticket first.\")\n",
    "else:\n",
    "    print(\"Sorry, 18+ only.\")"
   ],
   "id": "t02-032"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### and, or, not\n",
    "\n",
    "| Operator | Meaning | True when... |\n",
    "|---|---|---|\n",
    "| `and` | both | both sides are True |\n",
    "| `or` | either | at least one side is True |\n",
    "| `not` | opposite | the condition is False |"
   ],
   "id": "t02-033"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 25\n",
    "has_id = True\n",
    "\n",
    "if age >= 18 and has_id:\n",
    "    print(\"Entry allowed\")"
   ],
   "id": "t02-034"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "day = \"Saturday\"\n",
    "\n",
    "if day == \"Saturday\" or day == \"Sunday\":\n",
    "    print(\"Weekend!\")\n",
    "else:\n",
    "    print(\"Weekday\")"
   ],
   "id": "t02-035"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "is_raining = False\n",
    "\n",
    "if not is_raining:\n",
    "    print(\"No umbrella needed\")"
   ],
   "id": "t02-036"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Chained comparisons\n",
    "\n",
    "You can write a range check the way you would in maths. This is the same as `x >= 10 and x < 20`, only shorter. Test the edges 10, 19 and 20."
   ],
   "id": "t02-037"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 15\n",
    "\n",
    "if 10 <= x < 20:\n",
    "    print(\"x is between 10 and 20\")"
   ],
   "id": "t02-038"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Priority of the logical operators\n",
    "\n",
    "Python evaluates `not` first, then `and`, then `or`. Use parentheses to make your meaning clear."
   ],
   "id": "t02-039"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(True or False and False)     # True  (and happens first)\n",
    "print((True or False) and False)   # False (brackets first)"
   ],
   "id": "t02-040"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A very common mistake\n",
    "\n",
    "It is Monday, but this program still says it is the weekend:"
   ],
   "id": "t02-041"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "day = \"Monday\"\n",
    "\n",
    "if day == \"Saturday\" or \"Sunday\":    # WRONG (always True)\n",
    "    print(\"Weekend!\")\n",
    "else:\n",
    "    print(\"Weekday\")"
   ],
   "id": "t02-042"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python reads the condition as `(day == \"Saturday\") or (\"Sunday\")`, and a non-empty text counts as True. The correct way is to repeat the full comparison on both sides:"
   ],
   "id": "t02-043"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "day = \"Monday\"\n",
    "\n",
    "if day == \"Saturday\" or day == \"Sunday\":    # RIGHT\n",
    "    print(\"Weekend!\")\n",
    "else:\n",
    "    print(\"Weekday\")"
   ],
   "id": "t02-044"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When you compare one value with several options, `in` is a shorter way to write the same check:"
   ],
   "id": "t02-045"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "day = \"Sunday\"\n",
    "\n",
    "if day in (\"Saturday\", \"Sunday\"):\n",
    "    print(\"Weekend!\")\n",
    "else:\n",
    "    print(\"Weekday\")"
   ],
   "id": "t02-046"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python stops as soon as it knows the answer. With `and`, if the left side is False, the right side is not looked at. Below, the division never runs when `count` is 0, so there is no error."
   ],
   "id": "t02-047"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "total = 0\n",
    "count = 0\n",
    "\n",
    "if count != 0 and total / count > 50:\n",
    "    print(\"High average\")\n",
    "else:\n",
    "    print(\"No data, or a low average\")"
   ],
   "id": "t02-048"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Truthy values, text and decimals\n",
    "\n",
    "### Truthy and falsy values\n",
    "\n",
    "An `if` doesn't strictly need True or False. Python can treat other values as true or false:\n",
    "\n",
    "- Falsy (count as False): `0`, `0.0`, `\"\"` (empty text), `None`, `False`\n",
    "- Truthy (count as True): almost everything else, such as `5`, `-3`, `\"hello\"`, `True`\n",
    "\n",
    "Put your own name between the quotes and run the cell again."
   ],
   "id": "t02-049"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "name = \"\"\n",
    "\n",
    "if name:\n",
    "    print(\"Hello,\", name)\n",
    "else:\n",
    "    print(\"You didn't enter a name.\")"
   ],
   "id": "t02-050"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(bool(0), bool(\"\"), bool(5), bool(\"hi\"), bool(None))"
   ],
   "id": "t02-051"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "items = 0\n",
    "\n",
    "if items:\n",
    "    print(\"You have\", items, \"items in your cart\")\n",
    "else:\n",
    "    print(\"Your cart is empty\")"
   ],
   "id": "t02-052"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Comparing text\n",
    "\n",
    "- `==` compares text exactly, and it is case-sensitive: `\"Apple\" == \"apple\"` is False.\n",
    "- Convert to lowercase first to ignore the case: `answer.lower() == \"yes\"`.\n",
    "- Text and numbers are never equal: `\"10\" == 10` is False.\n",
    "- Text can be compared in alphabetical order: `\"apple\" < \"banana\"` is True."
   ],
   "id": "t02-053"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Apple\" == \"apple\")    # False: capital letters matter\n",
    "print(\"10\" == 10)            # False: text and a number are never equal\n",
    "print(\"apple\" < \"banana\")    # True: alphabetical order"
   ],
   "id": "t02-054"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"YES\"\n",
    "\n",
    "if answer.lower() == \"yes\":\n",
    "    print(\"You agreed!\")"
   ],
   "id": "t02-055"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "People also type extra spaces. `.strip()` removes them before the comparison."
   ],
   "id": "t02-056"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "answer = \"  Yes \"\n",
    "\n",
    "if answer.strip().lower() == \"yes\":\n",
    "    print(\"You agreed!\")"
   ],
   "id": "t02-057"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Comparing decimals\n",
    "\n",
    "Because computers store decimals approximately, avoid using `==` with them. The second line asks: \"Is the difference tiny?\" That is the safe way to compare decimals. `abs()` gives the value without a minus sign."
   ],
   "id": "t02-058"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(0.1 + 0.2 == 0.3)                      # False (!)\n",
    "print(abs((0.1 + 0.2) - 0.3) < 0.000001)     # True"
   ],
   "id": "t02-059"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Checking for None"
   ],
   "id": "t02-060"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = None\n",
    "\n",
    "if result is None:\n",
    "    print(\"No result yet\")"
   ],
   "id": "t02-061"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Input, one-line if/else, pass\n",
    "\n",
    "### Getting input from the user\n",
    "\n",
    "`input()` asks the user to type something. It always gives you text, so convert it to a number when you need one:\n",
    "\n",
    "```python\n",
    "age = int(input(\"Enter your age: \"))     # whole number\n",
    "price = float(input(\"Enter price: \"))    # decimal number\n",
    "name = input(\"Enter your name: \")        # stays text\n",
    "```\n",
    "\n",
    "Run the next cell and type an age in the box that appears."
   ],
   "id": "t02-062"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = int(input(\"Enter your age: \"))\n",
    "\n",
    "if age >= 18:\n",
    "    print(\"Adult\")\n",
    "else:\n",
    "    print(\"Minor\")"
   ],
   "id": "t02-063"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you skip `int(...)`, then `age >= 18` compares text with a number and Python gives a TypeError:\n",
    "\n",
    "```python\n",
    "age = input(\"Enter your age: \")\n",
    "\n",
    "if age >= 18:\n",
    "    print(\"Adult\")\n",
    "```\n",
    "\n",
    "```\n",
    "TypeError: '>=' not supported between instances of 'str' and 'int'\n",
    "```\n",
    "\n",
    "(If the user types letters instead of digits, `int()` fails too. Handling that is a later topic.)\n",
    "\n",
    "In the other examples of this notebook, we write the values directly (like `age = 20`) so you can see the output easily. You can always replace them with `input()`."
   ],
   "id": "t02-064"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A shorter form (one-line if/else)\n",
    "\n",
    "For simple choices, Python lets you write the whole decision on one line. The pattern is: `value_if_true if condition else value_if_false`. Use it only for simple cases. Normal if/else is easier to read for anything bigger."
   ],
   "id": "t02-065"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 20\n",
    "status = \"adult\" if age >= 18 else \"minor\"\n",
    "print(status)    # adult"
   ],
   "id": "t02-066"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The same decision written the normal way:"
   ],
   "id": "t02-067"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 20\n",
    "\n",
    "if age >= 18:\n",
    "    status = \"adult\"\n",
    "else:\n",
    "    status = \"minor\"\n",
    "\n",
    "print(status)"
   ],
   "id": "t02-068"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The pass placeholder\n",
    "\n",
    "Python doesn't allow an empty block. If you want to leave a block for later, use `pass` (\"do nothing\")."
   ],
   "id": "t02-069"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 30\n",
    "\n",
    "if age > 100:\n",
    "    pass    # I will write this part later\n",
    "\n",
    "print(\"Done\")"
   ],
   "id": "t02-070"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. How to solve a problem with if/else\n",
    "\n",
    "1. Read the problem and underline what the user gives you (the inputs).\n",
    "2. List every possible case. What are all the different outcomes?\n",
    "3. Turn each case into a condition. Make sure the cases don't overlap, or decide their order.\n",
    "4. Choose the structure: two outcomes (if/else), many outcomes (if/elif/else), or a second question (nested if).\n",
    "5. Test with boundary values, the numbers right at the edges. For \"18 or older\", test 17, 18, and 19. Most bugs hide at the boundaries."
   ],
   "id": "t02-071"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Common mistakes\n",
    "\n",
    "| Mistake | Wrong | Right |\n",
    "|---|---|---|\n",
    "| `=` instead of `==` | `if age = 18:` | `if age == 18:` |\n",
    "| Missing colon | `if age > 18` | `if age > 18:` |\n",
    "| Wrong indentation | unindented line under `if` | indent by 4 spaces |\n",
    "| Condition after `else` | `else age < 18:` | `elif age < 18:` or just `else:` |\n",
    "| Incomplete `or` check | `if x == 1 or 2:` | `if x == 1 or x == 2:` |\n",
    "| Comparing text to number | `\"5\" == 5` | `int(\"5\") == 5` |\n",
    "| Wrong order in `elif` | `>= 60` before `>= 90` | strictest condition first |\n",
    "| Decimal equality | `0.1 + 0.2 == 0.3` | compare the difference with `abs()` |\n",
    "| Forgetting to convert input | `input() >= 18` | `int(input()) >= 18` |\n",
    "\n",
    "The messages Python shows for the first two:\n",
    "\n",
    "```python\n",
    "age = 18\n",
    "\n",
    "if age = 18:\n",
    "    print(\"Adult\")\n",
    "```\n",
    "\n",
    "```\n",
    "SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?\n",
    "```\n",
    "\n",
    "```python\n",
    "age = 20\n",
    "\n",
    "if age > 18\n",
    "    print(\"Adult\")\n",
    "```\n",
    "\n",
    "```\n",
    "SyntaxError: expected ':'\n",
    "```"
   ],
   "id": "t02-072"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 9. Solved problems\n",
    "\n",
    "All of these are tested. Each shows the problem, the code, and why it works. After running a cell, try the other values named under it.\n",
    "\n",
    "### Level 1: Easy"
   ],
   "id": "t02-073"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 1. Voting eligibility\n",
    "\n",
    "A person can vote if they are 18 or older."
   ],
   "id": "t02-074"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 17\n",
    "\n",
    "if age >= 18:\n",
    "    print(\"You can vote.\")\n",
    "else:\n",
    "    print(\"You are too young to vote.\")"
   ],
   "id": "t02-075"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: one question, two outcomes. Boundary test: `18` gives \"You can vote.\""
   ],
   "id": "t02-076"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 2. Even or odd\n",
    "\n",
    "Tell whether a number is even or odd."
   ],
   "id": "t02-077"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 7\n",
    "\n",
    "if number % 2 == 0:\n",
    "    print(number, \"is even\")\n",
    "else:\n",
    "    print(number, \"is odd\")"
   ],
   "id": "t02-078"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `%` gives the remainder after division. An even number has remainder 0 when divided by 2."
   ],
   "id": "t02-079"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 3. Positive, negative, or zero"
   ],
   "id": "t02-080"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = -3\n",
    "\n",
    "if number > 0:\n",
    "    print(\"Positive\")\n",
    "elif number < 0:\n",
    "    print(\"Negative\")\n",
    "else:\n",
    "    print(\"Zero\")"
   ],
   "id": "t02-081"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: three outcomes need `elif`. Test values: `5` gives Positive, `0` gives Zero."
   ],
   "id": "t02-082"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 4. Pass or fail\n",
    "\n",
    "A student passes with 50 or more."
   ],
   "id": "t02-083"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "score = 45\n",
    "\n",
    "if score >= 50:\n",
    "    print(\"Pass\")\n",
    "else:\n",
    "    print(\"Fail\")"
   ],
   "id": "t02-084"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Test the boundary: 49, 50 and 51."
   ],
   "id": "t02-085"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 5. Largest of three numbers"
   ],
   "id": "t02-086"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 12\n",
    "b = 45\n",
    "c = 30\n",
    "\n",
    "if a >= b and a >= c:\n",
    "    largest = a\n",
    "elif b >= a and b >= c:\n",
    "    largest = b\n",
    "else:\n",
    "    largest = c\n",
    "\n",
    "print(\"Largest:\", largest)"
   ],
   "id": "t02-087"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `a` is the largest only if it beats both others (`and`). If not, check `b`. If neither, it must be `c`."
   ],
   "id": "t02-088"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Level 2: Medium"
   ],
   "id": "t02-089"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 6. Grade calculator\n",
    "\n",
    "90+ is A, 80-89 is B, 70-79 is C, 60-69 is D, below 60 is F. Scores outside 0-100 are invalid."
   ],
   "id": "t02-090"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "score = 83\n",
    "\n",
    "if score < 0 or score > 100:\n",
    "    print(\"Invalid score\")\n",
    "elif score >= 90:\n",
    "    print(\"Grade A\")\n",
    "elif score >= 80:\n",
    "    print(\"Grade B\")\n",
    "elif score >= 70:\n",
    "    print(\"Grade C\")\n",
    "elif score >= 60:\n",
    "    print(\"Grade D\")\n",
    "else:\n",
    "    print(\"Grade F\")"
   ],
   "id": "t02-091"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the invalid check comes first. Then the grades go from highest to lowest, so we only need `>=`. Test values: `95` gives A, `59` gives F, `105` gives Invalid."
   ],
   "id": "t02-092"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 7. Cinema ticket price\n",
    "\n",
    "Rules: under 5 is free. Ages 5 to 17 pay 6. Ages 18 to 64 pay 12, but students pay 8. Ages 65 and over pay 7. A negative age is invalid."
   ],
   "id": "t02-093"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "age = 20\n",
    "is_student = True\n",
    "\n",
    "if age < 0:\n",
    "    print(\"Invalid age\")\n",
    "else:\n",
    "    if age < 5:\n",
    "        price = 0\n",
    "    elif age < 18:\n",
    "        price = 6\n",
    "    elif age < 65:\n",
    "        if is_student:\n",
    "            price = 8\n",
    "        else:\n",
    "            price = 12\n",
    "    else:\n",
    "        price = 7\n",
    "    print(\"Ticket price:\", price)"
   ],
   "id": "t02-094"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: it combines `elif` with a nested `if` for the student discount. Other tests: age `3` gives 0, age `12` gives 6, age `30` (not student) gives 12, age `70` gives 7, age `-1` gives Invalid."
   ],
   "id": "t02-095"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 8. Number guessing hint\n",
    "\n",
    "The secret number is 42. Say \"Correct\", \"Very close\" (within 5), \"Too high\", or \"Too low\"."
   ],
   "id": "t02-096"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "secret = 42\n",
    "guess = 40\n",
    "difference = abs(secret - guess)\n",
    "\n",
    "if guess == secret:\n",
    "    print(\"Correct!\")\n",
    "elif difference <= 5:\n",
    "    if guess < secret:\n",
    "        print(\"Very close, a little higher!\")\n",
    "    else:\n",
    "        print(\"Very close, a little lower!\")\n",
    "elif guess < secret:\n",
    "    print(\"Too low\")\n",
    "else:\n",
    "    print(\"Too high\")"
   ],
   "id": "t02-097"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `abs()` turns the gap into a positive number, so one check covers both sides. Other tests: `42` gives Correct, `50` gives Too high, `20` gives Too low."
   ],
   "id": "t02-098"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 9. Fizz, Buzz, FizzBuzz\n",
    "\n",
    "If the number is divisible by 3 print \"Fizz\", by 5 print \"Buzz\", by both print \"FizzBuzz\", otherwise print the number."
   ],
   "id": "t02-099"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "number = 15\n",
    "\n",
    "if number % 15 == 0:\n",
    "    print(\"FizzBuzz\")\n",
    "elif number % 3 == 0:\n",
    "    print(\"Fizz\")\n",
    "elif number % 5 == 0:\n",
    "    print(\"Buzz\")\n",
    "else:\n",
    "    print(number)"
   ],
   "id": "t02-100"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the \"both\" case must come first. Otherwise `15` would be caught by the \"divisible by 3\" check and print only \"Fizz\". Tests: `9` gives Fizz, `10` gives Buzz, `7` gives 7."
   ],
   "id": "t02-101"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 10. Simple calculator\n",
    "\n",
    "Take two numbers and an operator (`+`, `-`, `*`, `/`). Don't allow division by zero."
   ],
   "id": "t02-102"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 10\n",
    "b = 0\n",
    "op = \"/\"\n",
    "\n",
    "if op == \"+\":\n",
    "    print(a + b)\n",
    "elif op == \"-\":\n",
    "    print(a - b)\n",
    "elif op == \"*\":\n",
    "    print(a * b)\n",
    "elif op == \"/\":\n",
    "    if b == 0:\n",
    "        print(\"Error: cannot divide by zero\")\n",
    "    else:\n",
    "        print(a / b)\n",
    "else:\n",
    "    print(\"Unknown operator\")"
   ],
   "id": "t02-103"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: the operator is text, so we compare it with `==`. Division has a nested check, because dividing by zero would crash the program. Tests: `10, 4, \"/\"` gives 2.5, and `\"%\"` gives Unknown operator."
   ],
   "id": "t02-104"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 11. Login check\n",
    "\n",
    "The correct username is `admin` (any capitalization allowed) and the password is `secret123` (exact)."
   ],
   "id": "t02-105"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "username = \"Admin\"\n",
    "password = \"wrong\"\n",
    "\n",
    "if username.lower() != \"admin\":\n",
    "    print(\"Unknown user\")\n",
    "elif password != \"secret123\":\n",
    "    print(\"Wrong password\")\n",
    "else:\n",
    "    print(\"Welcome, admin!\")"
   ],
   "id": "t02-106"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: `.lower()` makes the username check ignore capital letters, but passwords stay case-sensitive. Each failure gets its own helpful message."
   ],
   "id": "t02-107"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 12. BMI category\n",
    "\n",
    "BMI = weight (kg) divided by height (m) squared. Under 18.5 is Underweight, under 25 is Normal, under 30 is Overweight, otherwise Obese."
   ],
   "id": "t02-108"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "weight = 70\n",
    "height = 1.75\n",
    "\n",
    "bmi = round(weight / (height ** 2), 1)\n",
    "print(\"BMI:\", bmi)\n",
    "\n",
    "if bmi < 18.5:\n",
    "    print(\"Underweight\")\n",
    "elif bmi < 25:\n",
    "    print(\"Normal\")\n",
    "elif bmi < 30:\n",
    "    print(\"Overweight\")\n",
    "else:\n",
    "    print(\"Obese\")"
   ],
   "id": "t02-109"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: because we go from the lowest limit upward, each `elif` already knows the earlier ones failed, so we only need one `<` check per line. `round(x, 1)` keeps one decimal place."
   ],
   "id": "t02-110"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 13. Leap year\n",
    "\n",
    "A year is a leap year if it is divisible by 4, except century years (like 1900), which must be divisible by 400."
   ],
   "id": "t02-111"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "year = 2024\n",
    "\n",
    "if year % 400 == 0:\n",
    "    print(\"Leap year\")\n",
    "elif year % 100 == 0:\n",
    "    print(\"Not a leap year\")\n",
    "elif year % 4 == 0:\n",
    "    print(\"Leap year\")\n",
    "else:\n",
    "    print(\"Not a leap year\")"
   ],
   "id": "t02-112"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A shorter version with logical operators:"
   ],
   "id": "t02-113"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "year = 2024\n",
    "\n",
    "if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:\n",
    "    print(\"Leap year\")\n",
    "else:\n",
    "    print(\"Not a leap year\")"
   ],
   "id": "t02-114"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: tests: `2000` gives Leap, `1900` gives Not leap, `2023` gives Not leap. The order of checks matters: strictest rule first."
   ],
   "id": "t02-115"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 14. Triangle checker\n",
    "\n",
    "Three sides make a triangle only if each pair of sides adds up to more than the third. Then classify: equilateral (all equal), isosceles (two equal), scalene (none equal)."
   ],
   "id": "t02-116"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 5\n",
    "b = 5\n",
    "c = 8\n",
    "\n",
    "if a + b > c and a + c > b and b + c > a:\n",
    "    if a == b and b == c:\n",
    "        print(\"Equilateral triangle\")\n",
    "    elif a == b or b == c or a == c:\n",
    "        print(\"Isosceles triangle\")\n",
    "    else:\n",
    "        print(\"Scalene triangle\")\n",
    "else:\n",
    "    print(\"Not a triangle\")"
   ],
   "id": "t02-117"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: first question: is it a triangle at all? Only then do we ask which type (nested `if`). Tests: `3, 3, 3` gives Equilateral, `3, 4, 5` gives Scalene, `1, 2, 5` gives Not a triangle."
   ],
   "id": "t02-118"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Level 3: Medium-Hard"
   ],
   "id": "t02-119"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 15. Rock, Paper, Scissors judge\n",
    "\n",
    "Decide the winner between two players. Rock beats scissors, scissors beats paper, paper beats rock. Ignore capital letters and reject invalid choices."
   ],
   "id": "t02-120"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "p1 = \"Rock\"\n",
    "p2 = \"scissors\"\n",
    "\n",
    "p1 = p1.lower()\n",
    "p2 = p2.lower()\n",
    "\n",
    "if (p1 != \"rock\" and p1 != \"paper\" and p1 != \"scissors\") or \\\n",
    "   (p2 != \"rock\" and p2 != \"paper\" and p2 != \"scissors\"):\n",
    "    print(\"Invalid choice\")\n",
    "elif p1 == p2:\n",
    "    print(\"It's a tie!\")\n",
    "elif (p1 == \"rock\" and p2 == \"scissors\") or \\\n",
    "     (p1 == \"scissors\" and p2 == \"paper\") or \\\n",
    "     (p1 == \"paper\" and p2 == \"rock\"):\n",
    "    print(\"Player 1 wins!\")\n",
    "else:\n",
    "    print(\"Player 2 wins!\")"
   ],
   "id": "t02-121"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: we clean the input, validate it, check for a tie, then list the three ways Player 1 can win. If none of them is true, Player 2 must have won. The `\\` at the end of a line lets a long condition continue on the next line. Tests: `rock, lizard` gives Invalid, `Paper, paper` gives a tie."
   ],
   "id": "t02-122"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 16. Quadratic equation solver\n",
    "\n",
    "For ax² + bx + c = 0, the discriminant is d = b² - 4ac. If d > 0 there are two real solutions, if d = 0 there is one, and if d < 0 there are none."
   ],
   "id": "t02-123"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 1\n",
    "b = -3\n",
    "c = 2\n",
    "\n",
    "if a == 0:\n",
    "    print(\"Not a quadratic equation\")\n",
    "else:\n",
    "    d = b ** 2 - 4 * a * c\n",
    "\n",
    "    if d > 0:\n",
    "        x1 = (-b + d ** 0.5) / (2 * a)\n",
    "        x2 = (-b - d ** 0.5) / (2 * a)\n",
    "        print(\"Two roots:\", x1, \"and\", x2)\n",
    "    elif d == 0:\n",
    "        print(\"One root:\", -b / (2 * a))\n",
    "    else:\n",
    "        print(\"No real roots\")"
   ],
   "id": "t02-124"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: we first guard against `a = 0` (which would cause division by zero), then use the discriminant to choose the case. `d ** 0.5` is the square root. Tests: `1, 2, 1` gives One root: -1.0, `1, 0, 1` gives No real roots."
   ],
   "id": "t02-125"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 17. Date validator\n",
    "\n",
    "Check whether a given day/month/year is a real date. Remember that February has 29 days only in leap years."
   ],
   "id": "t02-126"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "day = 29\n",
    "month = 2\n",
    "year = 2023\n",
    "\n",
    "if month < 1 or month > 12 or day < 1:\n",
    "    print(\"Invalid date\")\n",
    "else:\n",
    "    if month == 2:\n",
    "        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:\n",
    "            max_day = 29\n",
    "        else:\n",
    "            max_day = 28\n",
    "    elif month == 4 or month == 6 or month == 9 or month == 11:\n",
    "        max_day = 30\n",
    "    else:\n",
    "        max_day = 31\n",
    "\n",
    "    if day <= max_day:\n",
    "        print(\"Valid date\")\n",
    "    else:\n",
    "        print(\"Invalid date\")"
   ],
   "id": "t02-127"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: step 1: reject impossible months and days. Step 2: work out the maximum number of days for that month (using the leap-year rule for February). Step 3: compare the day with that maximum. Tests: `29, 2, 2024` is Valid, `31, 4, 2025` is Invalid, `31, 12, 2025` is Valid, `15, 13, 2025` is Invalid."
   ],
   "id": "t02-128"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Problem 18. Online shop total\n",
    "\n",
    "Rules:\n",
    "\n",
    "- Subtotal of 200 or more gets a 15% discount. 100 or more gets 10%. Below 100 gets none.\n",
    "- Members get an extra 5% on top.\n",
    "- Shipping is free if the amount after the discount is 75 or more. Otherwise shipping is 6.99."
   ],
   "id": "t02-129"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "subtotal = 120\n",
    "is_member = True\n",
    "\n",
    "if subtotal >= 200:\n",
    "    discount_percent = 15\n",
    "elif subtotal >= 100:\n",
    "    discount_percent = 10\n",
    "else:\n",
    "    discount_percent = 0\n",
    "\n",
    "if is_member:\n",
    "    discount_percent = discount_percent + 5\n",
    "\n",
    "discount = subtotal * discount_percent / 100\n",
    "after_discount = subtotal - discount\n",
    "\n",
    "if after_discount >= 75:\n",
    "    shipping = 0\n",
    "else:\n",
    "    shipping = 6.99\n",
    "\n",
    "total = after_discount + shipping\n",
    "\n",
    "print(\"Discount percent:\", discount_percent)\n",
    "print(\"Shipping:\", shipping)\n",
    "print(\"Total:\", round(total, 2))"
   ],
   "id": "t02-130"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Why: real programs often use several separate decisions in sequence, where each result feeds the next one. Tests: subtotal `50`, member gives total 54.49 (with shipping), and subtotal `250`, non-member gives total 212.5."
   ],
   "id": "t02-131"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 10. Summary\n",
    "\n",
    "| Concept | What it does | Example |\n",
    "|---|---|---|\n",
    "| `if` | Runs a block only when the condition is True | `if age >= 18:` |\n",
    "| `else` | Runs when the `if` condition is False | `else:` |\n",
    "| `elif` | Checks another condition (only one block in the chain runs) | `elif score >= 80:` |\n",
    "| Condition | A question with a True/False answer | `x > 5` |\n",
    "| Indentation | 4 spaces; shows which lines belong to the block | `    print(\"Hi\")` |\n",
    "| Nested `if` | An `if` inside another `if` | second question after the first |\n",
    "| `and` / `or` / `not` | Combine or flip conditions | `a > 1 and b < 5` |\n",
    "| Chained comparison | Range check | `10 <= x < 20` |\n",
    "| Truthy/falsy | Non-boolean values used as conditions | `0` and `\"\"` are False |\n",
    "| One-line if/else | Short decision in one line | `\"adult\" if age >= 18 else \"minor\"` |\n",
    "| `pass` | Empty placeholder block | `pass` |\n",
    "\n",
    "Golden rules: (1) don't forget the colon, (2) indent by 4 spaces, (3) use `==` to compare, (4) put the strictest condition first in an `elif` chain, and (5) test the boundary values.\n",
    "\n",
    "Next: the practice notebook (topic-02-practice.ipynb), then Topic 3: loops and functions."
   ],
   "id": "t02-132"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
