{ "cells": [ { "cell_type": "markdown", "id": "8fede8e2", "metadata": {}, "source": [ "# Day 2 โ€” Loops, Functions & Defensive Programming\n", "### Summer Coding & Cybersecurity Camp\n", "\n", "Yesterday we *broke* a calculator. Today we learn how to build programs that\n", "**refuse to break** โ€” the heart of secure, professional code.\n", "\n", "**By the end of today you can:**\n", "- Repeat actions with `for` and `while` loops\n", "- Store collections in **lists** and **dictionaries**\n", "- Write reusable **functions**\n", "- Catch errors with `try / except` so programs fail *gracefully*\n", "- Keep asking until the user gives **valid** input (input validation)" ] }, { "cell_type": "markdown", "id": "53640051", "metadata": {}, "source": [ "## 1. `while` loops โ€” repeat until a condition changes" ] }, { "cell_type": "code", "execution_count": null, "id": "f85b5dfc", "metadata": {}, "outputs": [], "source": [ "count = 1\n", "while count <= 5:\n", " print(\"Countdown:\", count)\n", " count = count + 1\n", "print(\"Liftoff! ๐Ÿš€\")" ] }, { "cell_type": "markdown", "id": "b3fe800e", "metadata": {}, "source": [ "## 2. `for` loops and `range()`" ] }, { "cell_type": "code", "execution_count": null, "id": "d8d97560", "metadata": {}, "outputs": [], "source": [ "for i in range(3): # 0, 1, 2\n", " print(\"Attempt number\", i + 1)\n", "\n", "for letter in \"code\":\n", " print(letter)" ] }, { "cell_type": "markdown", "id": "ce3ea78e", "metadata": {}, "source": [ "## 3. Lists โ€” ordered collections" ] }, { "cell_type": "code", "execution_count": null, "id": "2041f2cd", "metadata": {}, "outputs": [], "source": [ "tasks = [\"learn python\", \"write secure code\", \"have fun\"]\n", "tasks.append(\"eat snacks\")\n", "\n", "print(\"Number of tasks:\", len(tasks))\n", "for t in tasks:\n", " print(\"-\", t)" ] }, { "cell_type": "markdown", "id": "a5de4a33", "metadata": {}, "source": [ "## 4. Dictionaries โ€” labeled data (key โ†’ value)\n", "Dictionaries are everywhere in security: storing usernames mapped to data, settings,\n", "configuration, etc." ] }, { "cell_type": "code", "execution_count": null, "id": "94300ddb", "metadata": {}, "outputs": [], "source": [ "user = {\"name\": \"Sam\", \"role\": \"student\", \"logins\": 0}\n", "\n", "print(user[\"name\"])\n", "user[\"logins\"] = user[\"logins\"] + 1 # update a value\n", "print(\"Login count:\", user[\"logins\"])" ] }, { "cell_type": "markdown", "id": "28b5c696", "metadata": {}, "source": [ "## 5. Functions โ€” package code so you can reuse it\n", "A function takes **inputs** (parameters), does work, and `return`s a result.\n", "Reusable functions are also *easier to secure*, because you fix a bug in **one** place." ] }, { "cell_type": "code", "execution_count": null, "id": "02d0e68d", "metadata": {}, "outputs": [], "source": [ "def double(number):\n", " return number * 2\n", "\n", "print(double(10))\n", "print(double(7))" ] }, { "cell_type": "markdown", "id": "6f425ed7", "metadata": {}, "source": [ "## 6. ๐Ÿ” The fix: `try / except`\n", "Remember yesterday's crash? `try / except` lets us *attempt* something risky and\n", "catch the error instead of letting the whole program die." ] }, { "cell_type": "code", "execution_count": null, "id": "5e3ac49a", "metadata": {}, "outputs": [], "source": [ "text = input(\"Enter a number: \")\n", "\n", "try:\n", " value = int(text)\n", " print(\"Great, you entered:\", value)\n", "except ValueError:\n", " print(\"โš ๏ธ That wasn't a whole number โ€” but I didn't crash!\")" ] }, { "cell_type": "markdown", "id": "9f3a1b2e", "metadata": {}, "source": [ "## 7. ๐Ÿ” Input validation: keep asking until it's valid\n", "Professional programs don't trust the first thing typed. They **loop** until the\n", "input is acceptable. This single pattern prevents a huge class of bugs and attacks." ] }, { "cell_type": "code", "execution_count": null, "id": "386cb502", "metadata": {}, "outputs": [], "source": [ "def get_valid_age():\n", " while True:\n", " text = input(\"Enter your age (0-120): \")\n", " try:\n", " age = int(text)\n", " except ValueError:\n", " print(\"Please type digits only.\")\n", " continue\n", " if 0 <= age <= 120:\n", " return age # only escapes the loop when valid\n", " print(\"That age is out of range. Try again.\")\n", "\n", "age = get_valid_age()\n", "print(\"Validated age:\", age)" ] }, { "cell_type": "markdown", "id": "234a8608", "metadata": {}, "source": [ "---\n", "## ๐Ÿงช LAB 2A โ€” Number Guessing Game (that never crashes)\n", "Write a game that:\n", "1. Picks a secret number (use the code given)\n", "2. Repeatedly asks the user to guess\n", "3. Says \"too high\" / \"too low\" until correct\n", "4. **Validates** input โ€” typing `abc` should NOT crash it\n", "\n", "Fill in the `TODO`s." ] }, { "cell_type": "code", "execution_count": null, "id": "b9bc86e2", "metadata": {}, "outputs": [], "source": [ "import random\n", "secret = random.randint(1, 20)\n", "print(\"I'm thinking of a number from 1 to 20.\")\n", "\n", "# TODO: loop until the user guesses correctly\n", "# - use try/except to handle non-numbers\n", "# - tell them too high / too low\n" ] }, { "cell_type": "markdown", "id": "f9358fe8", "metadata": {}, "source": [ "## ๐Ÿงช LAB 2B โ€” Validator Toolbox\n", "Write **two functions**:\n", "- `is_valid_username(name)` โ†’ returns `True` if the name is 3โ€“15 characters and\n", " only letters/numbers (hint: `name.isalnum()`), else `False`\n", "- `get_valid_number(prompt)` โ†’ keeps asking until the user types a real number, then returns it\n", "\n", "Test them at the bottom." ] }, { "cell_type": "code", "execution_count": null, "id": "f3d02b2b", "metadata": {}, "outputs": [], "source": [ "# LAB 2B โ€” your code here\n", "def is_valid_username(name):\n", " # TODO\n", " pass\n", "\n", "def get_valid_number(prompt):\n", " # TODO\n", " pass\n" ] }, { "cell_type": "markdown", "id": "d86e2a90", "metadata": {}, "source": [ "## ๐Ÿงช LAB 2C โ€” To-Do List Manager\n", "Build a tiny menu program using a **list**:\n", "- `1` Add a task `2` Show all tasks `3` Quit\n", "- Use a `while True` loop and validate the menu choice\n", "\n", "This combines loops, lists, and input validation โ€” everything from today!" ] }, { "cell_type": "code", "execution_count": null, "id": "e9ce831c", "metadata": {}, "outputs": [], "source": [ "# LAB 2C โ€” your code here\n", "tasks = []\n", "# TODO: menu loop\n" ] }, { "cell_type": "markdown", "id": "b5910c71", "metadata": {}, "source": [ "## ๐Ÿ CHALLENGE โ€” Make It Unbreakable\n", "Take any program from today and try every nasty input you can think of:\n", "empty Enter, letters, huge numbers, symbols. Add validation until **nothing** crashes it.\n", "Keep a \"bug log\" of what you found and fixed.\n", "\n", "---\n", "### โœ… Solutions (try first!)" ] }, { "cell_type": "code", "execution_count": null, "id": "10661f28", "metadata": {}, "outputs": [], "source": [ "# --- LAB 2A solution ---\n", "import random\n", "secret = random.randint(1, 20)\n", "print(\"I'm thinking of a number from 1 to 20.\")\n", "\n", "while True:\n", " guess_text = input(\"Your guess: \")\n", " try:\n", " guess = int(guess_text)\n", " except ValueError:\n", " print(\"Please enter a whole number.\")\n", " continue\n", " if guess == secret:\n", " print(\"๐ŸŽ‰ You got it!\")\n", " break\n", " elif guess < secret:\n", " print(\"Too low.\")\n", " else:\n", " print(\"Too high.\")" ] }, { "cell_type": "code", "execution_count": null, "id": "7a3aa866", "metadata": {}, "outputs": [], "source": [ "# --- LAB 2B solution ---\n", "def is_valid_username(name):\n", " return 3 <= len(name) <= 15 and name.isalnum()\n", "\n", "def get_valid_number(prompt):\n", " while True:\n", " try:\n", " return float(input(prompt))\n", " except ValueError:\n", " print(\"Not a number โ€” try again.\")\n", "\n", "print(is_valid_username(\"Sam99\")) # True\n", "print(is_valid_username(\"a b\")) # False\n", "print(is_valid_username(\"xy\")) # False" ] }, { "cell_type": "code", "execution_count": null, "id": "df53561d", "metadata": {}, "outputs": [], "source": [ "# --- LAB 2C solution ---\n", "tasks = []\n", "while True:\n", " print(\"\\n1) Add 2) Show 3) Quit\")\n", " choice = input(\"Choose: \")\n", " if choice == \"1\":\n", " tasks.append(input(\"New task: \"))\n", " print(\"Added!\")\n", " elif choice == \"2\":\n", " if not tasks:\n", " print(\"(no tasks yet)\")\n", " for i, t in enumerate(tasks, start=1):\n", " print(i, \"-\", t)\n", " elif choice == \"3\":\n", " print(\"Bye!\")\n", " break\n", " else:\n", " print(\"Pick 1, 2, or 3.\")" ] }, { "cell_type": "markdown", "id": "760cc38e", "metadata": {}, "source": [ "### ๐Ÿ“ Day 2 recap\n", "- `for` / `while` loops repeat work; lists & dicts store collections\n", "- functions make code reusable and easier to secure\n", "- ๐Ÿ” `try / except` + validation loops = programs that **fail gracefully**\n", " instead of crashing. Tomorrow: protecting *data* โ€” passwords, hashing, and secrets." ] } ], "metadata": { "colab": { "provenance": [], "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }