From 5b5c178a64b3aac1501527c858e0c3b9da8885c7 Mon Sep 17 00:00:00 2001 From: Arnav210 Date: Mon, 14 Sep 2026 12:24:47 -0700 Subject: [PATCH 01/43] Update rendering issues in Jarvis3000 capstone page --- .../unit_01/2025-09-21-1.1-algorithms.ipynb | 923 ---------- .../2025-09-21-1.10-class_methods.ipynb | 387 ----- ...25-09-21-1.10-class_methods_homework.ipynb | 99 -- .../unit_01/2025-09-21-1.11-math_class.ipynb | 549 ------ .../2025-09-21-1.11-math_classhw.ipynb | 341 ---- .../2025-09-21-1.12-classes_and_objects.ipynb | 241 --- .../unit_01/2025-09-21-1.12-hw.ipynb | 100 -- .../unit_01/2025-09-21-1.14-Backup.ipynb | 1521 ----------------- ...callinginstances-homework-innovators.ipynb | 496 ------ ...-21-1.14-callinginstances-innovators.ipynb | 652 ------- .../2025-09-21-1.15-java-objects.ipynb | 467 ----- .../unit_01/2025-09-21-1.2-variables.ipynb | 532 ------ .../unit_01/2025-09-21-1.3-output.ipynb | 592 ------- .../unit_01/2025-09-21-1.4-input.ipynb | 536 ------ .../unit_01/2025-09-21-1.5-data_casting.ipynb | 750 -------- .../2025-09-21-1.6-operators-innovators.ipynb | 339 ---- ...025-09-21-1.7-grinders-apis-homework.ipynb | 128 -- .../2025-09-21-1.7-grinders-apis.ipynb | 586 ------- ...9-21-1.8-documentation-with-comments.ipynb | 797 --------- .../unit_01/2025-09-21-1.8.ipynb | 797 --------- ...thod_Signatures-Homework-applicators.ipynb | 264 --- ...21-1.9-method_signatures-applicators.ipynb | 291 ---- .../unit_01/2025-09-21-2.1.ipynb | 31 - .../unit_01/2025-09-21-2.10.ipynb | 141 -- .../unit_01/2025-09-21-2.11.ipynb | 86 - .../unit_01/2025-09-21-2.12.ipynb | 188 -- .../unit_01/2025-09-21-2.2.ipynb | 31 - .../unit_01/2025-09-21-2.3.ipynb | 144 -- .../unit_01/2025-09-21-2.4.ipynb | 138 -- .../unit_01/2025-09-21-2.5.ipynb | 31 - .../unit_01/2025-09-21-2.6.ipynb | 31 - .../unit_01/2025-09-21-2.7.ipynb | 289 ---- .../unit_01/2025-09-21-2.8.ipynb | 128 -- .../unit_01/2025-09-21-2.9.ipynb | 31 - .../unit_01/2025-09-21-3.1.ipynb | 31 - .../unit_01/2025-09-21-3.2.ipynb | 31 - .../unit_01/2025-09-21-3.3.ipynb | 445 ----- .../unit_01/2025-09-21-3.4.ipynb | 31 - .../unit_01/2025-09-21-3.5.ipynb | 538 ------ .../unit_01/2025-09-21-3.6.ipynb | 31 - .../unit_01/2025-09-21-3.7.ipynb | 31 - .../unit_01/2025-09-21-3.8.ipynb | 31 - .../unit_01/2025-09-21-3.9.ipynb | 608 ------- .../unit_01/2025-09-21-4.1.ipynb | 31 - .../unit_01/2025-09-21-4.10.ipynb | 31 - .../unit_01/2025-09-21-4.11.ipynb | 830 --------- .../unit_01/2025-09-21-4.12.ipynb | 830 --------- .../unit_01/2025-09-21-4.2.ipynb | 31 - .../unit_01/2025-09-21-4.3.ipynb | 283 --- .../unit_01/2025-09-21-4.4.ipynb | 225 --- .../unit_01/2025-09-21-4.5.ipynb | 31 - .../unit_01/2025-09-21-4.6.ipynb | 31 - .../unit_01/2025-09-21-4.7.ipynb | 31 - .../unit_01/2025-09-21-4.8.ipynb | 658 ------- .../unit_01/2025-09-21-4.9.ipynb | 658 ------- .../unit_01/2025-09-21-u1quiz.ipynb | 198 --- .../unit_01/2025-09-21-u2quiz.ipynb | 31 - .../unit_01/2025-09-21-u3quiz.ipynb | 31 - .../unit_01/2025-09-21-u4quiz.ipynb | 31 - .../2025-10-12-1.13-homeworkGrinders.ipynb | 137 -- ...5-10-12-1.13-object_creationGrinders.ipynb | 774 --------- .../2025-10-19-1.3-output-homework.ipynb | 169 -- .../2024-11-09-lesson_outline.ipynb | 214 --- ...-09-29-functions_tinkerers_js_lesson.ipynb | 1047 ------------ ...02-conditionals_constellators_lesson.ipynb | 223 --- .../JavaScriptLessons/2026-01-07-arrays.ipynb | 399 ----- .../2026-01-09-data_abstraction.ipynb | 408 ----- .../2026-01-13-iterations_lesson.ipynb | 407 ----- .../2026-01-16-json_lesson.ipynb | 407 ----- .../2026-01-20-booleans-lessons.ipynb | 249 --- .../2026-01-20-math-exp.ipynb | 345 ---- .../2026-01-27-Strings.ipynb | 215 --- .../2026-02-19-variables.ipynb | 344 ---- .../2026-1-14-Nested-Conditionals.ipynb | 208 --- .../2026-1-27-ClassesAndMethods-Lesson.ipynb | 217 --- .../Jarvis3000/2026-09-01-jarvis-capstone.md | 1 + .../2026-09-01-jarvis-research-1.md | 20 +- .../2026-09-01-jarvis-research-2.md | 64 +- .../2026-09-01-jarvis-research-3.md | 38 +- .../2026-09-01-jarvis-research-4.md | 28 +- .../Jarvis3000/2026-09-01-jarvis-technical.md | 44 +- _sass/capstone/jarvis.scss | 15 +- 82 files changed, 106 insertions(+), 24262 deletions(-) delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.1-algorithms.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.10-class_methods.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.10-class_methods_homework.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.11-math_class.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.11-math_classhw.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.12-classes_and_objects.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.12-hw.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-Backup.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-callinginstances-homework-innovators.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-callinginstances-innovators.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.15-java-objects.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.2-variables.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.3-output.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.4-input.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.5-data_casting.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.6-operators-innovators.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.7-grinders-apis-homework.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.7-grinders-apis.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.8-documentation-with-comments.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.8.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.9-Method_Signatures-Homework-applicators.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.9-method_signatures-applicators.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.1.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.10.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.11.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.12.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.2.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.3.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.4.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.5.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.6.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.7.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.8.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.9.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.1.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.2.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.3.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.4.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.5.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.6.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.7.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.8.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.9.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.1.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.10.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.11.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.12.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.2.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.3.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.4.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.5.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.6.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.7.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.8.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.9.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u1quiz.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u2quiz.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u3quiz.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u4quiz.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-12-1.13-homeworkGrinders.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-12-1.13-object_creationGrinders.ipynb delete mode 100644 _notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-19-1.3-output-homework.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2024-11-09-lesson_outline.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2025-09-29-functions_tinkerers_js_lesson.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2025-10-02-conditionals_constellators_lesson.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-01-07-arrays.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-01-09-data_abstraction.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-01-13-iterations_lesson.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-01-16-json_lesson.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-01-20-booleans-lessons.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-01-20-math-exp.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-01-27-Strings.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-02-19-variables.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-1-14-Nested-Conditionals.ipynb delete mode 100644 _notebooks/CSSE/JavaScriptLessons/2026-1-27-ClassesAndMethods-Lesson.ipynb diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.1-algorithms.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.1-algorithms.ipynb deleted file mode 100644 index f6d9faf5b4..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.1-algorithms.ipynb +++ /dev/null @@ -1,923 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "f32c7e6a", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Algorithms]\n", - "lesson_language: Java\n", - "lesson_topic: Algorithms\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Introduction to Algorithms, Programming, and Compilers\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_1\n", - "author: Pranav, Rohan, Samhita\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "c36735b1", - "metadata": {}, - "source": [ - "# Cell 1: Markdown\n", - "\n", - "# Introduction to Algorithms, Programming, and Compilers\n", - "## Please Navigate to 2025-09-21-1.1.ipynb\n", - "\n", - "### Get ready to practice with Algorithims, Compilers and More!\n", - "\n", - "## What is an Algorithm?\n", - "\n", - "An **algorithm** is a step-by-step process to complete a task or solve a problem. Think of it like a recipe: each instruction must be followed in order to get the desired result.\n", - "\n", - "### Real-World Example: Making a Sandwich\n", - "\n", - "1. Get two slices of bread\n", - "2. Spread peanut butter on one slice\n", - "3. Spread jelly on the other slice\n", - "4. Put the slices together\n", - "5. Cut in half\n", - "\n", - "Notice how each step is clear and in a specific order. That's an algorithm!" - ] - }, - { - "cell_type": "markdown", - "id": "4a0f4a63", - "metadata": {}, - "source": [ - "\n", - "\n", - "
\n", - "
\n", - "

Store Closing Algorithm Challenge

\n", - "

Drag and drop the steps into the correct order

\n", - " \n", - "
\n", - "

How to Play:

\n", - "
    \n", - "
  1. Drag steps from the left column to the position slots on the right
  2. \n", - "
  3. Arrange them in the correct logical order for closing a store
  4. \n", - "
  5. Click \"Check Answer\" to see if you got it right
  6. \n", - "
  7. Use \"Clear All\" to start over or \"Reset & Shuffle\" for a new challenge
  8. \n", - "
\n", - "
\n", - " \n", - "
\n", - "
\n", - "

Available Steps

\n", - "
\n", - "
\n", - " \n", - "
\n", - "

Your Order

\n", - "
\n", - "
\n", - "
\n", - " \n", - "
\n", - " \n", - " \n", - " \n", - "
\n", - " \n", - "
\n", - "
\n", - "
\n", - "\n", - "" - ] - }, - { - "cell_type": "markdown", - "id": "24378c18", - "metadata": {}, - "source": [ - "## Why Algorithms Matter in Programming\n", - "\n", - "In programming, algorithms tell the computer exactly what to do. The more detailed and precise your algorithm, the better your program will work.\n", - "\n", - "### Example: Login System Algorithm\n", - "\n", - "```\n", - "1. Get username from user\n", - "2. Get password from user\n", - "3. Check if username exists in database\n", - "4. If username doesn't exist → show error message\n", - "5. If username exists → compare password\n", - "6. If password matches → grant access\n", - "7. If password doesn't match → show error message\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8fd66d9a", - "metadata": {}, - "outputs": [], - "source": [ - "import java.util.HashMap;\n", - "import java.util.Map;\n", - "\n", - "public class LoginSystem {\n", - " // Simple user database\n", - " private static Map userDatabase = new HashMap<>();\n", - "\n", - " static {\n", - " userDatabase.put(\"alice\", \"password123\");\n", - " userDatabase.put(\"bob\", \"securepass\");\n", - " userDatabase.put(\"charlie\", \"mypass456\");\n", - " }\n", - "\n", - " // Login algorithm\n", - " public static boolean login(String username, String password) {\n", - " // Step 3: Check if username exists\n", - " if (!userDatabase.containsKey(username)) {\n", - " // Step 4: Handle user not found\n", - " System.out.println(\"❌ Error: Username not found\");\n", - " return false;\n", - " }\n", - "\n", - " // Step 5-7: Compare password\n", - " if (userDatabase.get(username).equals(password)) {\n", - " System.out.println(\"✅ Login successful!\");\n", - " return true;\n", - " } else {\n", - " System.out.println(\"❌ Error: Incorrect password\");\n", - " return false;\n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " System.out.println(\"Test 1: Correct login\");\n", - " login(\"alice\", \"password123\");\n", - "\n", - " System.out.println(\"\\nTest 2: Wrong password\");\n", - " login(\"alice\", \"wrongpass\");\n", - "\n", - " System.out.println(\"\\nTest 3: User doesn't exist\");\n", - " login(\"david\", \"anypass\");\n", - " }\n", - "}\n", - "LoginSystem.main(null);" - ] - }, - { - "cell_type": "markdown", - "id": "2b1cdd09", - "metadata": {}, - "source": [ - "## Designing Good Algorithms\n", - "\n", - "**Key Principle**: Each task needs clear, detailed instructions.\n", - "\n", - "### ❌ Bad Algorithm Example:\n", - "```\n", - "1. Prepare for school\n", - "2. Go to school\n", - "```\n", - "\n", - "### ✅ Good Algorithm Example:\n", - "```\n", - "1. Wake up at 7:00 AM\n", - "2. Brush teeth\n", - "3. Take a shower\n", - "4. Get dressed in school uniform\n", - "5. Eat breakfast\n", - "6. Pack backpack with homework and lunch\n", - "7. Leave house at 7:45 AM\n", - "8. Walk to bus stop\n", - "9. Take bus to school\n", - "```\n", - "\n", - "The second algorithm is better because it's **specific** and **detailed**." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0c141f08", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "# Algorithm: Store user information\n", - "age = 16\n", - "name = \"Alice\"\n", - "is_student = True\n", - "\n", - "print(f\"Name: {name}\")\n", - "print(f\"Age: {age}\")\n", - "print(f\"Is a student: {is_student}\")\n", - "\n", - "# Try changing the values and run again!\n", - "# age = 17\n", - "# name = \"Bob\"" - ] - }, - { - "cell_type": "markdown", - "id": "8e93c947", - "metadata": {}, - "source": [ - "### 2. Methods/Functions - Reusable Algorithms\n", - "\n", - "Functions let you write an algorithm once and use it many times!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3e94c974", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Calculator:\n", - " \"\"\"A calculator class with reusable algorithms\"\"\"\n", - " \n", - " def add(self, a, b):\n", - " \"\"\"Algorithm: Add two numbers\"\"\"\n", - " return a + b\n", - " \n", - " def max(self, a, b):\n", - " \"\"\"Algorithm: Find the larger number\"\"\"\n", - " if a > b:\n", - " return a\n", - " else:\n", - " return b\n", - " \n", - " def multiply(self, a, b):\n", - " \"\"\"Algorithm: Multiply two numbers\"\"\"\n", - " result = 0\n", - " for i in range(b):\n", - " result = self.add(result, a)\n", - " return result\n", - "\n", - "# Create calculator and test it\n", - "calc = Calculator()\n", - "\n", - "print(\"Addition: 5 + 3 =\", calc.add(5, 3))\n", - "print(\"Maximum: max(10, 7) =\", calc.max(10, 7))\n", - "print(\"Multiplication: 4 × 3 =\", calc.multiply(4, 3))\n", - "\n", - "# Try your own calculations!\n", - "# print(calc.add(100, 250))" - ] - }, - { - "cell_type": "markdown", - "id": "53974ca0", - "metadata": {}, - "source": [ - "## What is a Compiler?\n", - "\n", - "A **compiler** translates code that humans can read into machine code that computers can execute.\n", - "\n", - "### The Process:\n", - "```\n", - "Your Code → Compiler → Bytecode → Virtual Machine → Running Program\n", - "```\n", - "\n", - "**Note:** Python is an interpreted language (runs line-by-line), while Java uses a compiler. But the concept is the same: translating human-readable code into something the computer can execute!\n", - "\n", - "**Example:**\n", - "```python\n", - "# You write this:\n", - "print(\"Hello, World!\")\n", - "\n", - "# Python interpreter executes it directly\n", - "# Output: Hello, World!\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c801c60d", - "metadata": {}, - "outputs": [], - "source": [ - "# Let's see what's \"under the hood\" of Python code!\n", - "import dis\n", - "\n", - "def greet(name):\n", - " message = f\"Hello, {name}!\"\n", - " return message\n", - "\n", - "# This shows the bytecode Python generates\n", - "print(\"Python bytecode for greet() function:\")\n", - "print(\"=\" * 50)\n", - "dis.dis(greet)\n", - "\n", - "print(\"\\n\" + \"=\" * 50)\n", - "print(\"When you call the function:\")\n", - "result = greet(\"Alice\")\n", - "print(result)" - ] - }, - { - "cell_type": "markdown", - "id": "37f750d0", - "metadata": {}, - "source": [ - "## Homework Hacks\n", - "\n", - "### Hack 1: Create Your Own Algorithm\n", - "Write a detailed algorithm for one of these activities:\n", - "- Getting ready for a basketball game\n", - "- Making a pizza from scratch \n", - "- Setting up a new phone\n", - "\n", - "**Requirements:**\n", - "- At least 8 steps\n", - "- Each step must be specific and clear\n", - "- Steps must be in logical order\n", - "\n", - "\"\"\"\n", - "### Example Response:\n", - "\n", - "**Activity chosen:** [Write your activity here]\n", - "\n", - "**Algorithm:**\n", - "1. [Your first step]\n", - "2. [Your second step]\n", - "3. [Your third step]\n", - "4. [Continue...]\n", - "\"\"\"" - ] - }, - { - "cell_type": "markdown", - "id": "ab6f814a", - "metadata": {}, - "source": [ - "### Hack 2: Identify the Bug\n", - "\n", - "This algorithm has steps in the wrong order. Fix it:\n", - "\n", - "```\n", - "Algorithm: Send an Email\n", - "1. Click \"Send\"\n", - "2. Open email application\n", - "3. Type the message\n", - "4. Log into your account\n", - "5. Enter recipient's email address\n", - "6. Write subject line\n", - "```\n", - "\n", - "### Example Response:\n", - "\n", - "**Corrected Algorithm: Send an Email**\n", - "1. [Your corrected step 1]\n", - "2. [Your corrected step 2]\n", - "3. [Your corrected step 3]\n", - "4. [Continue...]\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "110a03f8", - "metadata": {}, - "source": [ - "### Hack 3: Code the Algorithm\n", - "\n", - "Convert this algorithm into working Python code:\n", - "\n", - "```\n", - "Algorithm: Grade Calculator\n", - "1. Get three test scores from user\n", - "2. Add them together\n", - "3. Divide by 3 to get average\n", - "4. If average >= 90, grade is A\n", - "5. If average >= 80, grade is B\n", - "6. If average >= 70, grade is C\n", - "7. If average >= 60, grade is D\n", - "8. Otherwise, grade is F\n", - "9. Display the grade\n", - "```\n", - "\n", - "### Example Response" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "acec3f25", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "def calculate_grade(score1, score2, score3):\n", - " \"\"\"\n", - " Calculate letter grade from three test scores\n", - " \n", - " Args:\n", - " score1, score2, score3: Test scores (integers)\n", - " \n", - " Returns:\n", - " grade: Letter grade (string)\n", - " \"\"\"\n", - " # TODO: Your code here!\n", - " # Step 1: Add the three scores together\n", - " \n", - " # Step 2: Calculate the average\n", - " \n", - " # Step 3: Determine the letter grade using if-elif-else\n", - " \n", - " # Step 4: Return the grade\n", - " \n", - " pass # Remove this when you add your code\n", - "\n", - "# Test your function!\n", - "print(\"Test 1:\", calculate_grade(95, 92, 88)) # Should be 'A'\n", - "print(\"Test 2:\", calculate_grade(85, 80, 82)) # Should be 'B'\n", - "print(\"Test 3:\", calculate_grade(75, 70, 72)) # Should be 'C'\n", - "print(\"Test 4:\", calculate_grade(65, 60, 62)) # Should be 'D'\n", - "print(\"Test 5:\", calculate_grade(55, 50, 52)) # Should be 'F'" - ] - }, - { - "cell_type": "markdown", - "id": "2044255d", - "metadata": {}, - "source": [ - "## Congratulations!\n", - "\n", - "You've completed the Introduction to Algorithms lesson. Make sure to:\n", - "1. Complete all 3 homework hacks\n", - "2. Test your code by running all cells\n", - "3. Experiment with the interactive examples" - ] - }, - { - "cell_type": "markdown", - "id": "269ea4d7", - "metadata": {}, - "source": [ - "## Important: Read Below\n", - "Submit your accomplishment of this lesson by following instructions inside the notebook aswell as running the practices for the hacks.\n", - "Make sure that you submit your screenshots into an issue and then submit that issue in the google form:\n", - "[Link to Google Form](https://forms.gle/72QrAcqm6U35iKh59)\n", - "Homework is Due in 3 Days. " - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.3" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.10-class_methods.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.10-class_methods.ipynb deleted file mode 100644 index 14b60139f0..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.10-class_methods.ipynb +++ /dev/null @@ -1,387 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "498ed049", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Class-Methods]\n", - "lesson_language: Java\n", - "lesson_topic: Class-Methods\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Calling Class Methods\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_10\n", - "author: Trevor, Kush, Elliot, Aranya, Travis, Alex\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "e1e8d5e0", - "metadata": {}, - "source": [ - "## What is a \"Class Method?\"" - ] - }, - { - "cell_type": "markdown", - "id": "explanation_cell", - "metadata": {}, - "source": [ - ">**A class method (or static method in Java) belongs to the class itself, not to any specific object.**\n", - "\n", - "*(You can call these methods directly using the class name, without needing to create an object first.)*\n", - "\n", - "Key characteristics of static methods:\n", - "\n", - "- They are declared with the `static` keyword.\n", - "- They can be called using the syntax: `ClassName.methodName()`.\n", - "- They cannot use instance variables or instance methods directly (because they don't carry the state of the object).\n", - "- They are useful for utility functions or operations that are not tied to the state of a particular object." - ] - }, - { - "cell_type": "markdown", - "id": "example_title_cell", - "metadata": {}, - "source": [ - "### Printer Example" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "code_example_cell", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello, World!\n" - ] - }, - { - "ename": "CompilationException", - "evalue": "", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m\u001b[0m\u001b[1m\u001b[30m\u001b[41mPrinter.explode\u001b[0m\u001b[1m\u001b[30m(); // This will NOT work!\u001b[0m", - "\u001b[1m\u001b[31mnon-static method explode() cannot be referenced from a static context\u001b[0m", - "" - ] - } - ], - "source": [ - "class Printer {\n", - " // This IS a CLASS METHOD. It can be called WITHOUT creating an instance.\n", - " public static void print(String message) {\n", - " System.out.println(message);\n", - " }\n", - "\n", - " // This is NOT a CLASS METHOD. You need an instance to call it.\n", - " public void explode() {\n", - " System.out.println(\"Boom\");\n", - " }\n", - "}\n", - "\n", - "Printer.print(\"Hello, World!\"); // This will work!\n", - "Printer.explode(); // This will NOT work!" - ] - }, - { - "cell_type": "markdown", - "id": "b22650c4", - "metadata": {}, - "source": [ - "### Printer Example\n", - "This example demonstrates that a **static (class) method** can be called without creating an object, while an **instance method** requires one. \n", - "`Printer.print()` works because it’s static, but `Printer.explode()` causes an error since it’s an instance method and needs an object of `Printer` to be called." - ] - }, - { - "cell_type": "markdown", - "id": "d56e6618", - "metadata": {}, - "source": [ - "### Dude example" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bafc9591", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Dude {\n", - " String name;\n", - "\n", - " public Dude(String name) {\n", - " this.name = name;\n", - " }\n", - "\n", - " public static void SayName() {\n", - " System.out.println(\"My name is \" + name); // This will NOT work! cause name is an instance variable.\n", - " }\n", - "}\n", - "\n", - "// This will not compile since sayAnotherName is a STATIC (CLASS) METHOD and cannot access the INSTANCE variable 'name'." - ] - }, - { - "cell_type": "markdown", - "id": "b2afb93c", - "metadata": {}, - "source": [ - "### Dude Example\n", - "This shows that **static methods cannot access instance variables**. \n", - "The method `SayName()` tries to use `name`, which belongs to an instance, not the class itself. To fix this, `SayName()` must be non-static or receive `name` as a parameter.\n" - ] - }, - { - "cell_type": "markdown", - "id": "1634a795", - "metadata": {}, - "source": [ - "### Bro example" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "56f7808d", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Bro {\n", - " String name;\n", - " static String classicBroSaying = \"Sup bro?\";\n", - "\n", - " public Bro(String name) {\n", - " this.name = name;\n", - " }\n", - "\n", - " public void sayMyName() {\n", - " System.out.println(\"My name is \" + name); // This will work!\n", - " }\n", - "\n", - " public static void sayClassicBroSaying() {\n", - " System.out.println(classicBroSaying); // This will work too!\n", - " }\n", - "}\n", - "\n", - "Bro kush = new Bro(\"kush\");\n", - "kush.sayMyName(); // This will work!\n", - "\n", - "Bro.sayClassicBroSaying(); // This will work! because the classicBroSaying variable is STATIC.\n", - "Bro.sayMyName(); // This will NOT work! because sayMyName is NOT a STATIC method." - ] - }, - { - "cell_type": "markdown", - "id": "75498ee1", - "metadata": {}, - "source": [ - "### Bro Example\n", - "This example contrasts how static and instance members behave together. \n", - "`classicBroSaying` is static, meaning it belongs to the class and can be used in a static method. \n", - "`name` is an instance variable, so only instance methods like `sayMyName()` can access it. \n", - "You call static methods with the class name, but instance methods with an object.\n" - ] - }, - { - "cell_type": "markdown", - "id": "5170425b", - "metadata": {}, - "source": [ - "## Popcorn Hack: Which is an instance method or static method\n", - "\n", - "### What to do\n", - "You’ve learned that **static methods** belong to the *class* and **instance methods** belong to the *object*.\n", - "\n", - "Look at the code below and decide which lines will work — and which will cause an error. \n", - "Then fix the wrong ones." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "15afd140", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "ename": "CompilationException", - "evalue": "", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41msayHi\u001b[0m\u001b[1m\u001b[30m();\u001b[0m", - "\u001b[1m\u001b[31mnon-static method sayHi() cannot be referenced from a static context\u001b[0m", - "" - ] - } - ], - "source": [ - "class Bro {\n", - " String name;\n", - " static String catchphrase = \"Sup bro?\";\n", - "\n", - " public Bro(String name) {\n", - " this.name = name;\n", - " }\n", - "\n", - " public void sayHi() {\n", - " System.out.println(\"Hey, I'm \" + name);\n", - " }\n", - "\n", - " public static void sayCatchphrase() {\n", - " System.out.println(catchphrase);\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " // Will this work?\n", - " sayCatchphrase();\n", - "\n", - " // What about this one?\n", - " sayHi();\n", - "\n", - " Bro alex = new Bro(\"Alex\");\n", - " alex.sayHi();\n", - " alex.sayCatchphrase();\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "85d597df", - "metadata": {}, - "source": [ - "### Chart for the Bro Example\n", - "\n", - "| | Static Variable | Non-Static Variable |\n", - "|-------------------|-------------|---------------|\n", - "| **In static (Class) method** | ✅ | ❌ |\n", - "| **In instance method** | ✅ | ✅ |" - ] - }, - { - "cell_type": "markdown", - "id": "6a646ea1", - "metadata": {}, - "source": [ - "Real-Life Example: Bank Account\n" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "800b0628", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class BankAccount {\n", - " String owner;\n", - " double balance;\n", - " static double interestRate = 0.05; // shared by all accounts\n", - "\n", - " public BankAccount(String owner, double balance) {\n", - " this.owner = owner;\n", - " this.balance = balance;\n", - " }\n", - "\n", - " // Instance method → affects a single account\n", - " public void deposit(double amount) {\n", - " balance += amount;\n", - " System.out.println(owner + \" deposited $\" + amount + \". New balance: $\" + balance);\n", - " }\n", - "\n", - " // Instance method → shows this account’s balance\n", - " public void showBalance() {\n", - " System.out.println(owner + \"'s current balance: $\" + balance);\n", - " }\n", - "\n", - " // Static method → shared across all accounts\n", - " public static void setInterestRate(double newRate) {\n", - " interestRate = newRate;\n", - " System.out.println(\"New interest rate set to \" + (interestRate * 100) + \"% for all accounts.\");\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " BankAccount alex = new BankAccount(\"Alex\", 500);\n", - " BankAccount brooke = new BankAccount(\"Brooke\", 1000);\n", - "\n", - " alex.deposit(200);\n", - " brooke.deposit(300);\n", - "\n", - " alex.showBalance();\n", - " brooke.showBalance();\n", - "\n", - " BankAccount.setInterestRate(0.07); // static call through the class\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "c2fa0669", - "metadata": {}, - "source": [ - "### Bank Account Example\n", - "This example shows how static members represent shared data or behavior across all objects. \n", - "Each `BankAccount` object has its own `balance`, but all accounts share the same `interestRate`. \n", - "\n", - "The `deposit()` and `showBalance()` methods are **instance methods** because they work on a single account’s data. \n", - "The `setInterestRate()` method is **static** because it changes a value shared by every account. \n", - "\n", - "\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "java (JJava/j!)", - "language": "java", - "name": "jbang-jjava" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "17.0.16+8" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.10-class_methods_homework.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.10-class_methods_homework.ipynb deleted file mode 100644 index 439493f28e..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.10-class_methods_homework.ipynb +++ /dev/null @@ -1,99 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "498ed049", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Class-Methods]\n", - "lesson_language: Java\n", - "lesson_topic: Class-Methods\n", - "lesson_part: interactive\n", - "lesson_type: homework\n", - "toc: true\n", - "title: Calling Class Methods Homework\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_10/homework\n", - "author: Trevor, Kush, Elliot, Aranya, Travis, Alex\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "3a4007b3", - "metadata": {}, - "source": [ - "# Homework: Ultimate Battle\n", - "\n", - "---\n", - "\n", - "## Scenario\n", - "\n", - "You are programming a game where 2 objects of your choosing (e.g., Robots, Dinosaurs, People) battle. Each object has health and power.\n", - "\n", - "---\n", - "\n", - "## Instructions\n", - "\n", - "1. **Create a class** representing your object with:\n", - "\n", - " **Instance variables:** \n", - " - `String name` \n", - " - `int power` \n", - " - `int health` \n", - " - `MAKE YOUR OWN`\n", - "\n", - " **Static variables:**\n", - " - `double fightDuration`\n", - "\n", - " **Instance methods:** \n", - " - `void attack()`\n", - " - `void printStatus()`\n", - " - `MAKE YOUR OWN`\n", - "\n", - " **Class methods:** \n", - " - `static int strongerFighter()`\n", - " - `static void beginBattle()`\n", - " - `MAKE YOUR OWN`\n", - "\n", - "2. **In `main`:** \n", - " - Create two objects. \n", - " - Use instance methods to attack and print status. \n", - " - Use static methods to compare, print a fact, and start the battle." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "73c91681", - "metadata": {}, - "outputs": [], - "source": [ - "// Code Here" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "java (JJava/j!)", - "language": "java", - "name": "jbang-jjava" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "17.0.16+0" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.11-math_class.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.11-math_class.ipynb deleted file mode 100644 index beb5d71a7b..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.11-math_class.ipynb +++ /dev/null @@ -1,549 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "a9b42124", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Math-Class]\n", - "lesson_language: Java\n", - "lesson_topic: Math-Class\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Math Class\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_11\n", - "author: Gurshawn, Anvay, Akshay\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "033c842e", - "metadata": {}, - "source": [ - "## The Problem: Building a Game Without Math Class\n", - "\n", - "Imagine you're creating a simple RPG game and you need to:\n", - "- Calculate a player's damage: 10 × (1.5level)\n", - "- Find the distance between the player and an enemy\n", - "- Generate random loot drops\n", - "- Round numbers for displaying stats\n", - "\n", - "**Without the Math class, you'd have to write your own code for all of this!** That would be hundreds of lines of complicated algorithms.\n", - "\n", - "**With the Math class?** Just a few simple method calls! \n", - "\n", - "### Think About This:\n", - "- Have you ever used the x² or √ button on a calculator?\n", - "- When might you need to generate a random number in a program?\n", - "- Why would we want to round 47.8 to 48?\n", - "\n", - "Let's learn how Java's Math class makes all of this easy!" - ] - }, - { - "cell_type": "markdown", - "id": "4f107a63", - "metadata": {}, - "source": [ - "## What is the Math Class?\n", - "\n", - "The **Math Class** is a special tool built into Java that lets you do complex math operations easily.\n", - "\n", - "### College Board Essential Knowledge (1.11.A.1):\n", - "- The Math class is part of the `java.lang` package\n", - "- You don't need to import it - it's **automatically available** in every Java program\n", - "- It contains only **static methods** (you call them using `Math.methodName()`)\n", - "\n", - "Think of it like having a scientific calculator built right into your code!" - ] - }, - { - "cell_type": "markdown", - "id": "e3cebf2d", - "metadata": {}, - "source": [ - "## Learning Objective (College Board 1.11.A)\n", - "\n", - "**By the end of this lesson, you will be able to:**\n", - "> Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced\n", - "\n", - "In simple terms: You'll learn to use Math class methods in your code and understand what they return!\n", - "\n", - "**What you'll master:**\n", - "1. Using Math.abs() to get absolute values\n", - "2. Using Math.pow() to calculate powers\n", - "3. Using Math.sqrt() to find square roots\n", - "4. Using Math.random() to generate random numbers\n", - "5. Manipulating random values to create specific ranges" - ] - }, - { - "cell_type": "markdown", - "id": "733ddb87", - "metadata": {}, - "source": [ - "## Important Math Class Methods (College Board 1.11.A.2)\n", - "\n", - "These are the methods you NEED to know for the AP CSA exam:\n", - "\n", - "| Method | What It Does | Example |\n", - "|--------|--------------|---------|\n", - "| `Math.abs(int x)` | Returns the absolute value of an integer | `Math.abs(-5)` returns `5` |\n", - "| `Math.abs(double x)` | Returns the absolute value of a double | `Math.abs(-7.5)` returns `7.5` |\n", - "| `Math.pow(double base, double exponent)` | Returns base raised to the power of exponent | `Math.pow(2, 3)` returns `8.0` |\n", - "| `Math.sqrt(double x)` | Returns the square root of x | `Math.sqrt(25)` returns `5.0` |\n", - "| `Math.random()` | Returns a random number from 0.0 (inclusive) to 1.0 (exclusive) | `Math.random()` might return `0.537` |\n", - "\n", - "### Key Points to Remember:\n", - "1. All these methods are **static** - call them with `Math.methodName()`\n", - "2. Most return `double` values\n", - "3. `Math.random()` always returns a value where **0.0 ≤ value < 1.0**\n", - "4. You can manipulate `Math.random()` to get different ranges (we'll learn this!)\n" - ] - }, - { - "cell_type": "markdown", - "id": "8aa9c8a9", - "metadata": {}, - "source": [ - "## Let's See Them in Action!\n", - "\n", - "Now let's write code using each of these methods. Follow along and run the code yourself!\n" - ] - }, - { - "cell_type": "markdown", - "id": "48b5f0a5", - "metadata": {}, - "source": [ - "### Example 1: Math.abs() - Absolute Value\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a9426589", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Math.abs() removes the negative sign from a number\n", - "\n", - "int playerHealth = 75;\n", - "int enemyHealth = 120;\n", - "int difference = playerHealth - enemyHealth; // This is -45\n", - "\n", - "System.out.println(\"Raw difference: \" + difference);\n", - "System.out.println(\"Absolute difference: \" + Math.abs(difference));\n", - "\n", - "// Use case: Find out WHO has more health, not if it's positive or negative\n", - "System.out.println(\"\\nThe health gap is \" + Math.abs(difference) + \" HP\");\n" - ] - }, - { - "cell_type": "markdown", - "id": "0b326845", - "metadata": {}, - "source": [ - "### Example 2: Math.pow() - Powers/Exponents\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2755a530", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Math.pow(base, exponent) calculates base^exponent\n", - "\n", - "// Example: Calculate damage that increases with level\n", - "double baseDamage = 10.0;\n", - "int level = 5;\n", - "\n", - "// Damage formula: baseDamage * (1.5^level)\n", - "double totalDamage = baseDamage * Math.pow(1.5, level);\n", - "\n", - "System.out.println(\"Base Damage: \" + baseDamage);\n", - "System.out.println(\"At level \" + level + \", damage is: \" + totalDamage);\n", - "\n", - "// Another example: 2^10\n", - "System.out.println(\"\\n2 to the power of 10 = \" + Math.pow(2, 10));\n" - ] - }, - { - "cell_type": "markdown", - "id": "5a43a307", - "metadata": {}, - "source": [ - "### Example 3: Math.sqrt() - Square Root\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dfc5f563", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Math.sqrt() finds the square root\n", - "\n", - "// Use case: Distance formula (Pythagorean theorem)\n", - "// Distance = √((x2-x1)² + (y2-y1)²)\n", - "\n", - "double playerX = 3.0;\n", - "double playerY = 4.0;\n", - "double enemyX = 0.0;\n", - "double enemyY = 0.0;\n", - "\n", - "// Calculate distance\n", - "double distance = Math.sqrt(Math.pow(playerX - enemyX, 2) + Math.pow(playerY - enemyY, 2));\n", - "\n", - "System.out.println(\"Player is at (\" + playerX + \", \" + playerY + \")\");\n", - "System.out.println(\"Enemy is at (\" + enemyX + \", \" + enemyY + \")\");\n", - "System.out.println(\"Distance between them: \" + distance + \" units\");\n" - ] - }, - { - "cell_type": "markdown", - "id": "20ae2222", - "metadata": {}, - "source": [ - "### Example 4: Math.random() - Random Numbers\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9ea01cbb", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Math.random() returns a value: 0.0 <= value < 1.0\n", - "// This means it can be 0.0, but will NEVER be exactly 1.0\n", - "\n", - "System.out.println(\"Basic random number: \" + Math.random());\n", - "System.out.println(\"Another one: \" + Math.random());\n", - "System.out.println(\"And another: \" + Math.random());\n", - "\n", - "// These will all be different numbers between 0.0 and 1.0\n", - "// Examples: 0.374, 0.891, 0.025, etc.\n" - ] - }, - { - "cell_type": "markdown", - "id": "74c1fb9c", - "metadata": {}, - "source": [ - "## The MOST Important Part: Manipulating Math.random()\n", - "\n", - "**College Board Essential Knowledge (1.11.A.3):**\n", - "> The values returned from `Math.random()` can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range\n", - "\n", - "This is crucial for the AP exam! Let's learn how to create random numbers in ANY range you want.\n" - ] - }, - { - "cell_type": "markdown", - "id": "19409094", - "metadata": {}, - "source": [ - "### Step-by-Step: Creating Random Integers in a Range\n", - "\n", - "**Goal: Get a random integer from min to max (inclusive)**\n", - "\n", - "**Formula:**\n", - "```java\n", - "(int)(Math.random() * (max - min + 1)) + min\n", - "```\n", - "\n", - "Let's break this down!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7d126e8c", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Example: Random number from 1 to 6 (like a dice roll)\n", - "\n", - "int min = 1;\n", - "int max = 6;\n", - "\n", - "// Step 1: Math.random() gives us 0.0 to 0.999...\n", - "// Step 2: Multiply by (max - min + 1) = 6, gives us 0.0 to 5.999...\n", - "// Step 3: Cast to int, gives us 0 to 5\n", - "// Step 4: Add min, gives us 1 to 6\n", - "\n", - "int diceRoll = (int)(Math.random() * (max - min + 1)) + min;\n", - "\n", - "System.out.println(\"You rolled a: \" + diceRoll);\n", - "\n", - "// Try it a few more times!\n", - "System.out.println(\"Roll 2: \" + (int)(Math.random() * 6) + 1);\n", - "System.out.println(\"Roll 3: \" + (int)(Math.random() * 6) + 1);\n", - "System.out.println(\"Roll 4: \" + (int)(Math.random() * 6) + 1);\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "685b9cc1", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Another example: Random damage from 50 to 100\n", - "\n", - "int minDamage = 50;\n", - "int maxDamage = 100;\n", - "\n", - "int damage = (int)(Math.random() * (maxDamage - minDamage + 1)) + minDamage;\n", - "\n", - "System.out.println(\"Damage dealt: \" + damage);\n", - "\n", - "// Generate 5 random damage values\n", - "System.out.println(\"\\n5 Attacks:\");\n", - "for (int i = 1; i <= 5; i++) {\n", - " int randomDamage = (int)(Math.random() * 51) + 50; // 51 because (100-50+1)=51\n", - " System.out.println(\"Attack \" + i + \": \" + randomDamage + \" damage\");\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "3884da91", - "metadata": {}, - "source": [ - "## Popcorn Hack #1: Power Level Calculator\n", - "\n", - "**Your Task:** Create a program that calculates a character's power level.\n", - "\n", - "**Requirements:**\n", - "- Base power = 100\n", - "- Power formula: `basePower * (1.2)^level`\n", - "- Ask user for their level (or hard-code level = 10)\n", - "- Use `Math.pow()` to calculate final power\n", - "- Print the result\n", - "\n", - "**Example Output:**\n", - "```\n", - "Level: 10\n", - "Base Power: 100\n", - "Final Power: 619.17 (approximately)\n", - "```\n" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "809a6b26", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Level: 10\n", - "Base Power: 100.0\n", - "Final Power: 619.17 (approximately)\n" - ] - }, - { - "data": { - "text/plain": [ - "java.io.PrintStream@77e81102" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "// YOUR CODE HERE for Popcorn Hack #1\n", - "\n", - "double basePower = 100;\n", - "int level = 10; // you can change or input this later if needed\n", - "double finalPower = basePower * Math.pow(1.2, level);\n", - "\n", - "System.out.println(\"Level: \" + level);\n", - "System.out.println(\"Base Power: \" + basePower);\n", - "System.out.printf(\"Final Power: %.2f (approximately)%n\", finalPower);" - ] - }, - { - "cell_type": "markdown", - "id": "7f2711dd", - "metadata": {}, - "source": [ - "## Popcorn Hack #2: Loot Drop Simulator\n", - "\n", - "**Your Task:** Create a simple loot drop system that generates random items.\n", - "\n", - "**Requirements:**\n", - "- Generate a random item rarity (1-100)\n", - " - 1-60: Common (worth 10-30 gold)\n", - " - 61-85: Rare (worth 31-70 gold)\n", - " - 86-100: Legendary (worth 71-100 gold)\n", - "- Use `Math.random()` to generate the rarity number\n", - "- Use `Math.random()` again to generate gold value within the range\n", - "- Print what you got!\n", - "\n", - "**Example Output:**\n", - "```\n", - "Loot Drop!\n", - "Rarity Roll: 73\n", - "You got: RARE item\n", - "Gold Value: 54\n", - "```\n", - "\n", - "**Hint:** You'll need to use if-else statements with your random numbers!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4ce3745c", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// YOUR CODE HERE for Popcorn Hack #2\n", - "\n", - "System.out.println(\"Loot Drop!\");\n", - "\n", - "// Generate a random rarity roll between 1 and 100\n", - "int rarityRoll = (int)(Math.random() * 100) + 1;\n", - "System.out.println(\"Rarity Roll: \" + rarityRoll);\n", - "\n", - "String rarity;\n", - "int goldValue;\n", - "\n", - "// Determine rarity and gold range\n", - "if (rarityRoll <= 60) {\n", - " rarity = \"COMMON\";\n", - " goldValue = (int)(Math.random() * (30 - 10 + 1)) + 10; // 10–30\n", - "} else if (rarityRoll <= 85) {\n", - " rarity = \"RARE\";\n", - " goldValue = (int)(Math.random() * (70 - 31 + 1)) + 31; // 31–70\n", - "} else {\n", - " rarity = \"LEGENDARY\";\n", - " goldValue = (int)(Math.random() * (100 - 71 + 1)) + 71; // 71–100\n", - "}\n", - "\n", - "// Print results\n", - "System.out.println(\"You got: \" + rarity + \" item\");\n", - "System.out.println(\"Gold Value: \" + goldValue);" - ] - }, - { - "cell_type": "markdown", - "id": "58465895", - "metadata": {}, - "source": [ - "## Quick Summary - What You Learned\n", - "\n", - "### Key Methods to Remember:\n", - "1. **Math.abs(x)** - Makes any number positive\n", - "2. **Math.pow(base, exp)** - Calculates powers (like 2³)\n", - "3. **Math.sqrt(x)** - Finds square roots\n", - "4. **Math.random()** - Generates random numbers (0.0 to 1.0)\n", - "\n", - "### The Important Formula:\n", - "**Random integer from min to max (inclusive):**\n", - "```java\n", - "(int)(Math.random() * (max - min + 1)) + min\n", - "```\n", - "\n", - "### College Board Key Points:\n", - " Math class is in java.lang (automatically available) \n", - " All methods are static \n", - " Math.random() returns: 0.0 ≤ value < 1.0 \n", - " You can manipulate random() to get any range you want\n", - "\n", - "---\n", - "\n", - "## Homework Checklist\n", - "\n", - "### What to Submit:\n", - "\n", - "1. **Popcorn Hack #1**: Power Level Calculator \n", - "2. **Popcorn Hack #2**: Loot Drop Simulator \n", - "\n", - "\n", - "### Before You Submit:\n", - "- [ ] Both popcorn hacks are complete and run without errors\n", - "- [ ] Your code has comments explaining what it does\n", - "- [ ] You've tested your code with different values\n", - "- [ ] You completed the homework assignment\n", - "\n", - "\n", - "---\n", - "\n", - "\n", - "**Questions?** Ask in class or on Slack!\n", - "\n", - "**Pro Tip:** The random number formula is VERY commonly tested on the AP exam. Make sure you understand it!" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "java (JJava/j!)", - "language": "java", - "name": "jbang-jjava" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "17.0.16+8" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.11-math_classhw.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.11-math_classhw.ipynb deleted file mode 100644 index b65a7eb1b5..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.11-math_classhw.ipynb +++ /dev/null @@ -1,341 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "985dbac9", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Math-Class]\n", - "lesson_language: Java\n", - "lesson_topic: Math-Class\n", - "lesson_part: interactive\n", - "lesson_type: homework\n", - "toc: true\n", - "title: Math Class Homework\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_11_hw\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "25cb951c", - "metadata": {}, - "source": [ - "## Homework Checklist\n", - "- 2 Popcorn Hacks\n", - "- MCQ\n", - "- Homework Hack" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "99cb0432", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "int n = (int) Math.pow(2, 3.0 / 2);\n", - "System.out.println(n);" - ] - }, - { - "cell_type": "markdown", - "id": "4567a280", - "metadata": {}, - "source": [ - "What is printed?\n", - "\n", - "A. 2\n", - "B. 3\n", - "C. 4\n", - "D. It does not compile" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b49bc34c", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "int r = (int) (Math.random() * 6) + 5;" - ] - }, - { - "cell_type": "markdown", - "id": "4ae4b0ed", - "metadata": {}, - "source": [ - "Which statement best describes the values produced by:\n", - "A. An int from 5 to 10, inclusive\n", - "B. An int from 5 to 11, inclusive\n", - "C. An int from 6 to 10, inclusive\n", - "D. An int from 6 to 11, inclusive" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a75c1ce2", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "long a = Math.round(-3.5);\n", - "double b = Math.floor(-3.1);\n", - "double c = Math.ceil(-3.1);\n", - "int x = (int) a + (int) b + (int) c;\n" - ] - }, - { - "cell_type": "markdown", - "id": "3c8f86a8", - "metadata": {}, - "source": [ - "What is the value of x after executing:\n", - "A. -10\n", - "B. -9\n", - "C. -8\n", - "D. -7" - ] - }, - { - "cell_type": "markdown", - "id": "72eb9a30", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "source": [ - "Which expression correctly computes the Euclidean distance between points (x1, y1) and (x2, y2)?\n", - "A.\n", - "\n", - "Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2))\n", - "\n", - "\n", - "B.\n", - "\n", - "Math.pow((x2 - x1) + (y2 - y1), 2)\n", - "\n", - "\n", - "C.\n", - "\n", - "Math.abs((x2 - x1) + (y2 - y1))\n", - "\n", - "\n", - "D.\n", - "\n", - "Math.sqrt(Math.pow(x2 + x1, 2) + Math.pow(y2 + y1, 2))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "36ced226", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "int a = (int) Math.sqrt(26);\n", - "int b = (int) Math.sqrt(26);\n", - "System.out.println(a * b);\n" - ] - }, - { - "cell_type": "markdown", - "id": "cc73b5d5", - "metadata": {}, - "source": [ - "What is printed?\n", - "A. 5\n", - "B. 25\n", - "C. 26\n", - "D. 27" - ] - }, - { - "cell_type": "markdown", - "id": "f8ed5a34", - "metadata": {}, - "source": [ - "## Homework Hack: Game Stats Calculator\n", - "\n", - "You're creating a simple game and need to write methods to handle player statistics. Complete the following methods using Math class methods you learned in the lesson.\n", - "\n", - "### Part A: Health Difference Calculator\n", - "\n", - "Write a method that calculates the absolute difference between two players' health values.\n", - "\n", - "**Method signature:**\n", - "```java\n", - "public static int healthDifference(int player1Health, int player2Health)\n", - "```\n", - "\n", - "**Requirements:**\n", - "- Use `Math.abs()` to ensure the result is always positive\n", - "- Return the absolute difference between the two health values\n", - "\n", - "**Examples:**\n", - "- `healthDifference(75, 120)` → `45`\n", - "- `healthDifference(100, 80)` → `20`\n", - "- `healthDifference(50, 50)` → `0`\n", - "\n", - "### Part B: Attack Damage Calculator\n", - "\n", - "Write a method that calculates attack damage using a base damage and a power multiplier.\n", - "\n", - "**Method signature:**\n", - "```java\n", - "public static double calculateDamage(double baseDamage, double powerLevel)\n", - "```\n", - "\n", - "**Requirements:**\n", - "- Use `Math.pow()` to calculate: `baseDamage * (1.5 ^ powerLevel)`\n", - "- Return the total damage as a double\n", - "\n", - "**Examples:**\n", - "- `calculateDamage(10.0, 2)` → `22.5`\n", - "- `calculateDamage(15.0, 3)` → `50.625`\n", - "\n", - "### Part C: Distance Detector\n", - "\n", - "Write a method that calculates the distance between a player and an enemy using the distance formula.\n", - "\n", - "**Method signature:**\n", - "```java\n", - "public static double findDistance(int playerX, int playerY, int enemyX, int enemyY)\n", - "```\n", - "\n", - "**Requirements:**\n", - "- Use the distance formula: √((x2-x1)² + (y2-y1)²)\n", - "- Use `Math.pow()` for squaring\n", - "- Use `Math.sqrt()` for the square root\n", - "\n", - "**Examples:**\n", - "- `findDistance(0, 0, 3, 4)` → `5.0`\n", - "- `findDistance(1, 1, 4, 5)` → `5.0`\n", - "\n", - "### Part D: Random Loot Generator\n", - "\n", - "Write a method that generates a random loot value within a specific range.\n", - "\n", - "**Method signature:**\n", - "```java\n", - "public static int generateLoot(int minValue, int maxValue)\n", - "```\n", - "\n", - "**Requirements:**\n", - "- Use `Math.random()` and the formula from the lesson\n", - "- Return a random integer from minValue to maxValue (inclusive)\n", - "- Formula: `(int)(Math.random() * (max - min + 1)) + min`\n", - "\n", - "**Examples:**\n", - "- `generateLoot(10, 50)` → random number from 10 to 50\n", - "- `generateLoot(100, 100)` → `100`\n", - "- `generateLoot(1, 6)` → random number from 1 to 6 (like a dice roll)\n" - ] - }, - { - "cell_type": "markdown", - "id": "ce351acd", - "metadata": {}, - "source": [ - "### Hints to Help You:\n", - "\n", - "**For Part A (Health Difference):**\n", - "- Remember: `Math.abs()` makes any negative number positive\n", - "- Just subtract the two health values and use `Math.abs()` on the result\n", - "\n", - "**For Part B (Attack Damage):**\n", - "- Remember: `Math.pow(base, exponent)` calculates base^exponent\n", - "- The formula is: baseDamage × (1.5)^powerLevel\n", - "- Don't forget `Math.pow()` returns a double\n", - "\n", - "**For Part C (Distance):**\n", - "- Use the Pythagorean theorem: distance = √((x2-x1)² + (y2-y1)²)\n", - "- Square the differences using `Math.pow(difference, 2)`\n", - "- Then use `Math.sqrt()` on the sum\n", - "\n", - "**For Part D (Random Loot):**\n", - "- Use the exact formula from the lesson: `(int)(Math.random() * (max - min + 1)) + min`\n", - "- Make sure to include the `+1` to make the max inclusive!\n", - "\n", - "---\n", - "\n", - "## What to Submit:\n", - "\n", - "1. ✅ Complete **2 Popcorn Hacks** from the lesson (Power Level Calculator & Loot Drop Simulator)\n", - "2. ✅ Answer all **5 MCQ questions** above\n", - "3. ✅ Complete all **4 parts (A-D)** of the Homework Hack\n", - "4. ✅ Submit the link to your blog in the form below\n", - "\n", - "**Grading:**\n", - "- Popcorn Hacks: 0.2 points\n", - "- MCQ: 0.30 points \n", - "- Homework Hack (Parts A-D): 0.50 points\n", - "\n", - "\n", - "## Due by Oct 17th\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "903a67b2", - "metadata": {}, - "source": [ - "## Submit Your Work\n", - "\n", - "Complete the form below to submit your MC answers and blog link:\n", - "\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "29a3c31f", - "metadata": {}, - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "17.0.16+8-Ubuntu-0ubuntu124.04.1" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.12-classes_and_objects.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.12-classes_and_objects.ipynb deleted file mode 100644 index a820c6318e..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.12-classes_and_objects.ipynb +++ /dev/null @@ -1,241 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "c40f7c2e", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Classes-and-Objects]\n", - "lesson_language: Java\n", - "lesson_topic: Classes-and-Objects\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Classes & Objects\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_12\n", - "author: Kush, Trevor, Elliot, Aranya, Travis, Alex\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "ed26d857", - "metadata": {}, - "source": [ - "# AP CSA: Classes & Objects\n", - "\n", - "**Goal:** Understand the relationship between classes and objects, how reference variables work, and that all Java classes ultimately extend `Object`.\n" - ] - }, - { - "cell_type": "markdown", - "id": "2f35f0b8", - "metadata": {}, - "source": [ - "## 1) Class vs. Object\n", - "**Class** = blueprint or template. **Object** = one specific instance built from that blueprint." - ] - }, - { - "cell_type": "markdown", - "id": "f38d83b3", - "metadata": {}, - "source": [ - "### Description\n", - "A class defines **attributes** (instance variables) and **behaviors** (methods). Creating an object with `new` allocates memory and returns a **reference** to that object." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0fa10987", - "metadata": { - "language": "java" - }, - "outputs": [], - "source": [ - "// Example: simple class + object\n", - "class Dog {\n", - " String name;\n", - " int age;\n", - " void bark() {\n", - " System.out.println(name + \" says woof!\");\n", - " }\n", - "}\n", - "\n", - "class Main1 {\n", - " public static void main(String[] args) {\n", - " Dog myDog = new Dog(); // object created\n", - " myDog.name = \"Alo\";\n", - " myDog.age = 3;\n", - " myDog.bark();\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "be296283", - "metadata": {}, - "source": [ - "## 2) Reference Variables\n", - "Variables of reference type store the **address (reference)** of an object, not the object itself." - ] - }, - { - "cell_type": "markdown", - "id": "6b8782c5", - "metadata": {}, - "source": [ - "### Description\n", - "Two variables can reference the **same** object. Assigning one reference to another does **not** make a copy of the object. They both will point to the same thing." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b7a7a8b8", - "metadata": { - "language": "java" - }, - "outputs": [], - "source": [ - "// Example: references point to the same object\n", - "class Main2 {\n", - " public static void main(String[] args) {\n", - " Dog d1 = new Dog();\n", - " d1.name = \"Kai\";\n", - " \n", - " Dog d2 = d1; // both refer to the same Dog\n", - " d2.name = \"Kairo\"; // changes seen via d1 too\n", - " \n", - " System.out.println(d1.name); // prints Kairo\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "2c247267", - "metadata": {}, - "source": [ - "**Key Point**: When Phone p2 = p1;, a second variable is created that points to the same phone object. Changes through one variable affect the other as well." - ] - }, - { - "cell_type": "markdown", - "id": "4657ce41", - "metadata": {}, - "source": [ - "## 3) All Classes Are Subclasses of `Object`\n", - "`Object` is Java's ultimate superclass. Every class directly or indirectly extends it." - ] - }, - { - "cell_type": "markdown", - "id": "29f36da8", - "metadata": {}, - "source": [ - "### Description\n", - "Because of this, every object has methods like `toString()`, `equals(Object)`, and `getClass()` automatically (even if they weren't programmed)." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d06ae7f2", - "metadata": { - "language": "java" - }, - "outputs": [], - "source": [ - "// Example: methods from Object\n", - "class Main3 {\n", - " public static void main(String[] args) {\n", - " Dog x = new Dog();\n", - " System.out.println(x.getClass().getName()); // prints class name\n", - " System.out.println(x.toString()); // default toString from Object\n", - " System.out.println(x instanceof Object); // true\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "f48872b6", - "metadata": {}, - "source": [ - "**Key Point**: All Java objects inherit from Object, so they all have these built-in methods available." - ] - }, - { - "cell_type": "markdown", - "id": "19bd390c", - "metadata": {}, - "source": [ - "## 🍿 Popcorn Hack (one cell)\n", - "**Task:** Complete the code below.\n", - "\n", - "1. Finish the `Book` class by adding a `printInfo()` method that prints title and pages.\n", - "2. In `Main`, create **one** `Book` object, set its fields, and call `printInfo()`.\n", - "\n", - "> Keep it short—this is a quick check that you can define a class and create an instance." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4e33f513", - "metadata": { - "language": "java" - }, - "outputs": [], - "source": [ - "// TODO: Finish and run in your Java environment\n", - "class Book {\n", - " String title;\n", - " int pages;\n", - " \n", - " // TODO: write printInfo() to show: Title: , Pages: <pages>\n", - "}\n", - "\n", - "class MainPopcorn {\n", - " public static void main(String[] args) {\n", - " // TODO: make one Book, set its fields, and call printInfo()\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "83ae5606", - "metadata": {}, - "source": [ - "## Quick Self-Check (concepts)\n", - "1. In one sentence, explain **class vs. object**.\n", - "2. What does a **reference variable** store?\n", - "3. Name one method every object has because it extends **`Object`**." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "name": "python", - "version": "3.x" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.12-hw.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.12-hw.ipynb deleted file mode 100644 index a5480d9706..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.12-hw.ipynb +++ /dev/null @@ -1,100 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "b8d8b69f", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Classes-and-Objects]\n", - "lesson_language: Java\n", - "lesson_topic: Classes-and-Objects\n", - "lesson_part: interactive\n", - "lesson_type: homework\n", - "toc: true\n", - "title: 1.12 Homework\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_12/homework\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "4aba089c", - "metadata": {}, - "source": [ - "# Homework\n", - "---\n", - "# Scenario\n", - "\n", - "Its your first day of class when Mr. Mortenson asks you to identify all the students and list some characteristics about them. Create a class to use as a template to create student objects and create 3 imaginary students.\n", - "---\n", - "\n", - "# Instructions\n", - "1. **Create a class**\n", - " - **Instance variables:** \n", - " - `String name` \n", - " - `int grade` \n", - " - `int pets` \n", - " - `int siblings`\n", - " - `MAKE YOUR OWN`\n", - "\n", - "2. **In `main`:** \n", - " - Create three student objects. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bd9502da", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "//Code Here" - ] - }, - { - "cell_type": "markdown", - "id": "a4f5f575", - "metadata": {}, - "source": [ - "# New Scenario\n", - "\n", - "You find out that one of the students that you created an object for goes by a nickname. Using your knowledge of reference variables, create another object that references back to the same student.\n", - "---\n", - "\n", - "# Instructions\n", - "1. **Use your previous code**\n", - "\n", - "\n", - "2. **In `main`:** \n", - " - Create a reference variable with a different name that points to the same student. \n", - " - Output the instance attributes of this student\n" - ] - }, - { - "cell_type": "markdown", - "id": "0913155e", - "metadata": {}, - "source": [ - "//Code Here" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-Backup.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-Backup.ipynb deleted file mode 100644 index e39d13c4ec..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-Backup.ipynb +++ /dev/null @@ -1,1521 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Calling-Instance-Methods]\n", - "lesson_language: Java\n", - "lesson_topic: Calling-Instance-Methods\n", - "lesson_part: reference\n", - "lesson_type: backup\n", - "toc: true\n", - "title: Calling Instance Methods Backup\n", - "permalink: /csa/unit_01/1_14_backup\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Example\n", - "\n", - "Here is an example of creating a Student class in Java. It contains instance variables that define the characteristics of a student." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "public class Student {\n", - "\n", - " // instance variables\n", - " String name;\n", - " String teacher;\n", - " int period;\n", - " \n", - " // constructor\n", - " public Student(String name, String teacher, int period) {\n", - " this.name = name;\n", - " this.teacher = teacher;\n", - " this.period = period;\n", - " }\n", - " }" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Now, using our class, we can create student objects by initializing two students" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "Student grace = new Student(\"Grace\", \"Mr. Mort\", 3);\n", - "Student alice = new Student(\"Alice\", \"Mr. Mort\", 1);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can printout information about each student" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Grace\n" - ] - } - ], - "source": [ - "System.out.println(grace.name);" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n" - ] - } - ], - "source": [ - "System.out.println(alice.period);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Learning Objectives\n", - "\n", - "- Explain the relationship between a class and an object.\n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "A class in object-oriented programming serves as a blueprint or template, defining the structure and behavior of objects. Objects, on the other hand, are instances of a class, representing real-world entities or concepts in code. Each object created from a class inherits its attributes and methods, allowing multiple objects to share a common structure while having their own unique data and behaviors.\n", - "\n", - "</details>\n", - "\n", - "#### Essential Knowledge\n", - "\n", - "- An object is a specific instance of a class with defined attributes.\n", - "- A class is the formal implementation, or blueprint, of the attributes and behaviors of an object. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Unit 2.2- Creating and Storing Objects (Instantiation)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "So, after we learned about **classes**, how are **objects** actually made?\n", - "\n", - "Using our previous code, we can see created our constructor using \n", - "```\n", - "public Student(String name, String teacher, int period) {\n", - " this.name = name;\n", - " this.teacher = teacher;\n", - " this.period = period;\n", - " }\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Student {\n", - "\n", - " // instance variables\n", - " String name;\n", - " String teacher;\n", - " int period;\n", - " \n", - " // constructor\n", - " public Student(String name, String teacher, int period) {\n", - " this.name = name;\n", - " this.teacher = teacher;\n", - " this.period = period;\n", - " }\n", - " }" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The **Student** is the name of the class. The first letter is capitalized according to Java naming conventions (camel-case naming conventions). Then, using the **new** keyword, we call the constructor to make a new **Student**. Inside the parentheses, we have the parameter list, where the values and characteristics of the object are entered." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```\n", - "Student grace = new Student(\"Grace\", \"Mr. Mort\", 3);\n", - "```\n", - "\n", - "The **parameters** in this case are \"Grace\", \"Mr. Mort\", and 3. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Constructor Overloads\n", - "\n", - "A class can have multiple constructors, however, the number of parameters must be different or the order must be different. This is an example of **overloading** the constructor.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```\n", - "// Constructor 1\n", - "Student(String name, String teacher, int period)\n", - "\n", - "\n", - "// Constructor 2\n", - "Student(String teacher, String name, int period)\n", - "```\n", - "\n", - "This two constructors are not allowed. For example, if we call\n", - "\n", - "```\n", - "Student(\"Grace\", \"Mr. Mort\", 3);\n", - "```\n", - "\n", - "we would not know whether Grace or Mr. Mort is the student." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "However, constructors with different data types or different number of parameters are allowed when overloading. Here are some examples...\n", - "\n", - "```\n", - "Student(String name, String teacher, int period)\n", - "Student(String name, String teacher)\n", - "Student()\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Null Objects" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "Student rachit = null;" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Null basically states that no object exists, and it is not stored in memory. You cannot call methods on an object that is declared as null since null objects do not have any information or characteristics set to that object. This will create a NullPointerException" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Learning Objectives\n", - "\n", - "- Identify, using its signature, the correct constructor being called.\n", - "* Note: Method Signature in java is defined as the structure of a method that is designed by the programmer\n", - "\n", - "```\n", - "public class Student {\n", - "\n", - " // instance variables\n", - " String name;\n", - " String teacher;\n", - " int period;\n", - " \n", - " // constructor\n", - " public Student(String name, String teacher, int period) {\n", - " this.name = name;\n", - " this.teacher = teacher;\n", - " this.period = period;\n", - " }\n", - " }\n", - "```\n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "```\n", - "Student(\"Grace\", \"Mr. Mort\", 3);\n", - "```\n", - "\n", - "- For creating objects: (a) Create objects by calling constructors without parameters. (b) Create objects by calling constructors with parameters.\n", - "- Define variables of the correct types to represent reference data.\n", - "\n", - "</details>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Unit 2.3- Calling a Void Method" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**method**: code that is called in order to achieve a task\n", - "- can be void or non-void, static or non-static\n", - "\n", - "**void method**: do not return a value but instead change other things. These include changing characteristics of an object or printing text to the console. Here is an example...\n", - "\n", - "```\n", - "public void methodName(parameterList)\n", - "```\n", - "\n", - "**static method**: general to the class and not tied to any particular object. The method is denoted by the Here is an example ...\n", - "\n", - "```\n", - "public static void add() {\n", - " count++;\n", - "}\n", - "\n", - "```\n", - "\n", - "To call a static method, we use dot notation, with the class name coming before the method separated by a dot as follows\n", - "\n", - "```\n", - "ClassName.add();\n", - "```\n", - "\n", - "**non-static method**: acts on a particular object. For example, printing a person's name is a non-static method, since each person has a different name. For example...\n", - "\n", - "```\n", - "public void printName() {\n", - " System.out.println(name);\n", - "}\n", - "```\n", - "\n", - "When calling a non-static method, we also use dot notation. But, instead of using the class name, we use the object name so we know what object the method acts on. Also, we don't need to do dot notation of ClassName.objectName.methodName() because an object already acts on a certain class, so using the class name is just redundant. We would use printName() as follows...\n", - "\n", - "```\n", - "objectName.printName();\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Run the main method and see what the each of the methods prints out" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "public class MyClass {\n", - "\n", - " // Static method\n", - " public static void staticMethod() {\n", - " System.out.println(\"This is a static method.\");\n", - " }\n", - "\n", - " // Non-static (instance) method\n", - " public void nonStaticMethod() {\n", - " System.out.println(\"This is a non-static method.\");\n", - " }\n", - "\n", - " // Method with void return type\n", - " public void methodWithVoidReturnType() {\n", - " System.out.println(\"This method has a void return type.\");\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " // Calling the static method\n", - " staticMethod();\n", - "\n", - " // Creating an object of MyClass\n", - " MyClass myObject = new MyClass();\n", - "\n", - " // Calling the non-static method on the object\n", - " myObject.nonStaticMethod();\n", - "\n", - " // Calling the method with void return type\n", - " myObject.methodWithVoidReturnType();\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Learning Objective\n", - "\n", - "- Call non-static void methods without parameters. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Unit 2.4- Calling a Void Method With Parameters" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The method signature for writing void method with parameters is the same as a constructor, with the name of the method followed by the parameters and their types in parentheses. For example, here is a method that prints the perimeter of a rectangle..." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [], - "source": [ - "public static void printRectanglePerimeter(double length, double width) {\n", - " System.out.println(2 * (length + width));\n", - " } " - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "8.0\n" - ] - } - ], - "source": [ - "printRectanglePerimeter(1.5, 2.5);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can also overload methods as well. This overloading of the method is acceptable because there are different numbers of parameters. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// If 2 parameters are given, we will calculate the perimeter by adding the length and width and doubling it\n", - "public static void printRectanglePerimeter(double length, double width) {\n", - " System.out.println(2 * (length + width));\n", - "}\n", - "\n", - "// If 1 parameter is given, we assume the shape is a square\n", - "public static void printRectanglePerimeter(double side) {\n", - " System.out.println(4 * side);\n", - "}\n", - "\n", - "// No shape exists, no perimeter is calculated\n", - "public static void printRectanglePerimeter() {\n", - " System.out.println(0);\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Unit 2.5- Calling a Non-Void Method\n", - "\n", - "**Void methods**: complete actions and represent tasks. They are used when you want a method to perform a task or operation without producing a result that needs to be used elsewhere in your program. Void methods are typically used for actions like printing a message, updating a data structure, or modifying the state of an object.\n", - "\n", - "Format for a non-void method:\n", - "```\n", - "public (static) dataType methodName(parameterListOptional)\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Which method in this class is a non-void method? Edit the cell below to call the Calculator method." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Sum: 8\n" - ] - } - ], - "source": [ - "public class Calculator {\n", - " // A non-void method that adds two numbers and returns the result\n", - " public int add(int a, int b) {\n", - " return a + b;\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " Calculator calculator = new Calculator();\n", - "\n", - " // Calling the non-void method and capturing the result\n", - " int sum = calculator.add(5, 3);\n", - "\n", - " // Printing the result\n", - " System.out.println(\"Sum: \" + sum); // Output: Sum: 8\n", - " }\n", - "}\n", - "Calculator.main(null)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 2.6 String Objects: Concatenation, Literals, and More\n", - "\n", - "Guess what's crazy? String literals are not actually primitives, they are considered objects! String literals are part of the aptly named String class included in Java and have a set of methods that come along with it. We'll see what we can do with the String class in the next topic!\n", - "\n", - "There are two ways to make strings: using a preinitialized string or by using a constructor. " - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello World!\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello World!\n" - ] - } - ], - "source": [ - "String preInt = \"Hello World!\"; // How we usually initialize strings\n", - "System.out.println(preInt);\n", - "\n", - "// Using a constructor:\n", - "String newString = new String(\"Hello World!\");\n", - "System.out.println(newString);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Escape Characters\n", - "Sometimes, you want to put a quote in a string. However, you quickly find out that the opening quotation in the quote marks the \"end\" of the string and you can't type out your quote unless you want the program to crash. What can you do?" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "![Alt text](https://media.discordapp.net/attachments/1010780182476496908/1159224994707021945/image.png?ex=65303f68&is=651dca68&hm=d8ba25c57cc1d41eb20fd2f3621f2ae0472efb874dba76d7078415c0d0b34613&=&width=2268&height=622)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Challenge: Display the background of the quote while displaying the quote in one line: \"Give me liberty or give me death!\" - Patrick Henry." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "This is a famous quote written by Patrick Henry in the Virginia Convention: \n", - "\"Give me liberty or give me death!\"\n" - ] - } - ], - "source": [ - "System.out.println(\"This is a famous quote written by Patrick Henry in the Virginia Convention: \\n\\\"Give me liberty or give me death!\\\"\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### String Concatenation\n", - "\n", - "When we combine two strings together, we call that string concatenation. We use the '+' operator to concatenate two strings. " - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "I amhungry\n" - ] - } - ], - "source": [ - "System.out.println(\"I am\" + \"hungry\");" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Notice how there is no space between am and hungry. This is because the java '+' operator does not add a space, but instead, joins the strings together without adding anything in between. To fix this, we add a space in between." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "I am hungry\n" - ] - } - ], - "source": [ - "System.out.println(\"I am\" + \" \" + \"hungry\");" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "However, when we want to use variables with our strings, we can also use the '+=' operator to concatenate our strings. The '+' operator still works, however." - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello World\n", - "Hello World\n" - ] - } - ], - "source": [ - "String a1 = \"Hello \";\n", - "String a2 = \"World\";\n", - "System.out.println(a1 + a2);\n", - "System.out.println(a1 += a2);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Can you guess what happens when we try to change a string object?" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "s1 refers to Java\n", - "s2 refers to Hello\n", - "s3 refers to Hello\n", - "newS3 refers to Hello Scaler\n" - ] - } - ], - "source": [ - "String s1 = \"Hello\"; // String literal\n", - "String s2 = \"Hello\"; // String literal\n", - "String s3 = s1; // same reference\n", - "\n", - "//Changing the value of s1\n", - "s1 = \"Java\";\n", - "\n", - "//Updating with concat() operation\n", - "s2.concat(\" World\");\n", - "\n", - "//The concatenated String will be created as a new instance and an object should refer to that instance to get the concatenated value.\n", - "String newS3 = s3.concat(\" Scaler\");\n", - "\n", - "System.out.println(\"s1 refers to \" + s1);\n", - "System.out.println(\"s2 refers to \" + s2);\n", - "System.out.println(\"s3 refers to \" + s3);\n", - "System.out.println(\"newS3 refers to \" + newS3);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The strings are immutable! This is because immutable strings allows Java to be safe in multithread applications (no changes that were not supposed to happen at that time in the program), and it makes the string object very efficient, as the strings are stored in a \"string pool\" that Java uses, which allows strings to only be created once but used over and over again if the same string object is created multiple times." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "One last cool thing about strings is that primitive types change to string objects when concatenated. You have been doing this all the time, but here is the proof!" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Here is the key: 0.5\n" - ] - } - ], - "source": [ - "String message = \"Here is the key: \";\n", - "double key = 0.5;\n", - "\n", - "System.out.println(message + key)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 2.7 String Methods\n", - "\n", - "#### Intro to External Libraries and APIs\n", - "There is a lot you can do with the factory version of Java, however, just like Python and many other languages, there are many new things you can do with the Java external libraries and APIs (application program interfaces). \n", - "All Java classes, libraries, and APIs come with documentation, which lists the methods of the class and also how to use the class and its methods. Here is the official Java documentation for the String class:\n", - "\n", - "[Java Docs](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html)\n", - "\n", - "Courtesy of Java." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### About the String Class\n", - "__The String class is a class in the java.lang package that comes when you install Java on your computer.__\n", - "### Accessing Substrings\n", - "With strings, we can access substrings and characters in the string. A substring is a string that is included within a larger string, and a character is a substring with a length of 1. First, we need to figure out the length of a string, which is the number of characters in the string. To do this, we use the following method:" - ] - }, - { - "cell_type": "code", - "execution_count": 34, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "9\n" - ] - } - ], - "source": [ - "String str = \"Kaiden Do\";\n", - "System.out.println(str.length())" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "We can also get a index for the strings. For example, if we take \"Kaiden Do\"...\n", - "\n", - "| Index | Character |\n", - "| --- | --- |\n", - "| 0 | K |\n", - "| 1 | a |\n", - "| 2 | i |\n", - "| 3 | d |\n", - "| 4 | e |\n", - "| 5 | n |\n", - "| 6 | |\n", - "| 7 | D |\n", - "| 8 | o |" - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Kaiden\n", - "Do\n" - ] - } - ], - "source": [ - "String str = \"Kaiden Do\";\n", - "System.out.println(str.substring(0, 6)); // Range is [_,_)\n", - "System.out.println(str.substring(7, 9)); // Range is [_,_)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "How would we get the nth character of a string? Write a program to find it with an integer n that you can change to get the nth character in the cell below." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "P\n" - ] - } - ], - "source": [ - "String str = \"Pizza is yummy\";\n", - "int n = 1;\n", - "System.out.println(str.substring(n - 1, n));" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Question: If we have a string, what is its lower bound index and what is its upper bound index, if the string length is equal to the variable 'str'?\n", - "\n", - "Answer: \n", - "\n", - "Lower Bound Index: 0 \n", - "\n", - "Upper Bound Index: str - 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Question: What is the error for an out of bound string? Display it in the cell below." - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [ - { - "ename": "EvalException", - "evalue": "Range [0, 1000) out of bounds for length 5", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1m\u001b[31mjava.lang.StringIndexOutOfBoundsException: Range [0, 1000) out of bounds for length 5\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:52)\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:213)\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions$4.apply(Preconditions.java:210)\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:98)\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromToIndex(Preconditions.java:112)\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/jdk.internal.util.Preconditions.checkFromToIndex(Preconditions.java:349)\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/java.lang.String.checkBoundsBeginEnd(String.java:4608)\u001b[0m", - "\u001b[1m\u001b[31m\tat java.base/java.lang.String.substring(String.java:2720)\u001b[0m", - "\u001b[1m\u001b[31m\tat .(#21:1)\u001b[0m" - ] - } - ], - "source": [ - "String str = \"Hello\";\n", - "System.out.println(str.substring(0, 1000))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To do a ctrl-F search through a string, we can use the following process:" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "246\n" - ] - } - ], - "source": [ - "String str = \"He stared out the window at the snowy field. He'd been stuck in the house for close to a month and his only view of the outside world was through the window. There wasn't much to see. It was mostly just the field with an occasional bird or small animal who ventured into the field. As he continued to stare out the window, he wondered how much longer he'd be shackled to the steel bar inside the house.\";\n", - "System.out.println(str.indexOf(\"animal\"))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As you can see, the first instance of animal starts at the index of 246." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "To compare two strings to each other, we use two functions:" - ] - }, - { - "cell_type": "code", - "execution_count": 48, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Does string 1 equal string 2? True or false: true\n", - "Does string 1 equal string 2? True or false: false\n" - ] - } - ], - "source": [ - "// To check if a string is equal to another string:\n", - "String str1 = \"I am hungry\";\n", - "String str2 = \"I am hungry\";\n", - "System.out.println(\"Does string 1 equal string 2? True or false: \" + str1.equals(str2));\n", - "String str2 = \"I am not hungry\";\n", - "System.out.println(\"Does string 1 equal string 2? True or false: \" + str1.equals(str2));" - ] - }, - { - "cell_type": "code", - "execution_count": 55, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "-6\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0\n", - "1\n" - ] - } - ], - "source": [ - "// To compare the lengths of the strings\n", - "\n", - "// Case 1: String 1 is shorter than string 2\n", - "String str1 = \"I am hungry\";\n", - "String str2 = \"I am not hungry\";\n", - "System.out.println(str1.compareTo(str2)); // Returns less than 0\n", - "\n", - "// Case 2: String 1 is equal string 2\n", - "String str1 = \"I am hungry\";\n", - "String str2 = \"I am hungry\";\n", - "System.out.println(str1.compareTo(str2)); // Returns 0\n", - "\n", - "// Case 3: String 1 is longer than string 2\n", - "String str1 = \"I am hungry\";\n", - "String str2 = \"Hello!\";\n", - "System.out.println(str1.compareTo(str2)); // Returns greater than 0" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "compareTo() returns the difference of first unmatched character in the two compared strings. If no unmatch is found, and one string comes out as shorter than other one, then the length difference is returned. It also checks to see if a string comes before or after another string alphabetically." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 2.8 Wrapper Classes: Integer and Double\n", - "You probably know what an integer is (if you don't see me after class immediatley!), and you probably know what a double is (again, if you don't see me after class immediatley!).\n", - "\n", - "\n", - "<details>\n", - "<summary>But did you know...</summary>\n", - "<br>\n", - "Integers and Doubles are classes called <strong>wrapper classes</strong>!\n", - "</details>\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Why would we want to do this? Answer the question in this cell.\n", - "\n", - "Maybe we want to pass a variable as an integer but the program only accepts objects." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<details>\n", - "<summary>Answer</summary>\n", - "<br>\n", - "These classes convert primitive data types (int/double) to a reference data type (object). We convert these because different data structures in java require different types of variables, some of which are only objects. By parsing the values of the primitive data to an object, we can send values to methods and structures that only take object values, like ArrayList, for example. \n", - "</details>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### The integer Wrapper Class\n", - "The Integer class in Java is a wrapper class for the primitive data type int. It provides several methods that can be used to perform operations on int values. The constructor looks like this:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "Integer(int value)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "An example of this running is:" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "metadata": {}, - "outputs": [], - "source": [ - "Integer hungerRating = new Integer(5); // Send to an Object\n", - "int hungerRatingNum = hungerRating.intValue(); // Turn back into a primitive" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "An example of it being utilized is:" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "metadata": {}, - "outputs": [ - { - "ename": "CompilationException", - "evalue": "", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mArrayList<\u001b[0m\u001b[1m\u001b[30m\u001b[41mint\u001b[0m\u001b[1m\u001b[30m> list = new ArrayList<int>(); // This will cause a compile-time error\u001b[0m", - "\u001b[1m\u001b[31munexpected type\u001b[0m", - "\u001b[1m\u001b[31m required: reference\u001b[0m", - "\u001b[1m\u001b[31m found: int\u001b[0m", - "", - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mArrayList<int> list = new ArrayList<\u001b[0m\u001b[1m\u001b[30m\u001b[41mint\u001b[0m\u001b[1m\u001b[30m>(); // This will cause a compile-time error\u001b[0m", - "\u001b[1m\u001b[31munexpected type\u001b[0m", - "\u001b[1m\u001b[31m required: reference\u001b[0m", - "\u001b[1m\u001b[31m found: int\u001b[0m", - "" - ] - } - ], - "source": [ - "ArrayList<int> list = new ArrayList<int>(); // This will cause a compile-time error" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The above code will not work because ArrayList requires on object type, while we are passing a primitive type." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[5]\n" - ] - } - ], - "source": [ - "ArrayList<Integer> list = new ArrayList<Integer>();\n", - "list.add(5); // Autoboxing will automatically convert the int 5 to an Integer object\n", - "System.out.println(list)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code works because the 5 is being converted by the list.add, since the list uses integer objects. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Moreover, we can also get other data from the integer class, which is related to how Java functions." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Integer Min Value: -2147483648\n", - "Integer Max Value: 2147483647\n" - ] - } - ], - "source": [ - "System.out.println(\"Integer Min Value: \" + Integer.MIN_VALUE);\n", - "System.out.println(\"Integer Max Value: \" + Integer.MAX_VALUE);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "These numbers are the bounds of integers in java. For example, we can try going outside the range to see what happens." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "ename": "CompilationException", - "evalue": "", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mInteger pleaseBreak = new Integer(\u001b[0m\u001b[1m\u001b[30m\u001b[41m\u001b[0m\u001b[1m\u001b[30m2147483648);\u001b[0m", - "\u001b[1m\u001b[31minteger number too large\u001b[0m", - "" - ] - } - ], - "source": [ - "Integer pleaseBreak = new Integer(2147483648)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Double Wrapper Classes\n", - "\n", - "Double wrapper classes are basically the same thing as integer classes, however, they deal with double varaiables instead of integer variables. You write it like this:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "Double(Double Value)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here is an example of using Double object:" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "// My actual height in real life (in feet)\n", - "Double height = new Double(6.6); // Send to an Object\n", - "double primitiveHeight = height.doubleValue(); // Turn back into a primitive" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "And here is an example of when it works and when it does not." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "ename": "CompilationException", - "evalue": "", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mArrayList<\u001b[0m\u001b[1m\u001b[30m\u001b[41mdouble\u001b[0m\u001b[1m\u001b[30m> list = new ArrayList<double>(); // This will cause a compile-time error\u001b[0m", - "\u001b[1m\u001b[31munexpected type\u001b[0m", - "\u001b[1m\u001b[31m required: reference\u001b[0m", - "\u001b[1m\u001b[31m found: double\u001b[0m", - "", - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30mArrayList<double> list = new ArrayList<\u001b[0m\u001b[1m\u001b[30m\u001b[41mdouble\u001b[0m\u001b[1m\u001b[30m>(); // This will cause a compile-time error\u001b[0m", - "\u001b[1m\u001b[31munexpected type\u001b[0m", - "\u001b[1m\u001b[31m required: reference\u001b[0m", - "\u001b[1m\u001b[31m found: double\u001b[0m", - "" - ] - } - ], - "source": [ - "ArrayList<double> list = new ArrayList<double>(); // This will cause a compile-time error" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Again, the ArrayList needs an object type, but we are passing a primitive type." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "true" - ] - }, - "execution_count": 6, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "ArrayList<Double> list = new ArrayList<Double>();\n", - "list.add(3.14); // Autoboxing will automatically convert the double 3.14 to a Double object" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This code works because the 3.14 is being converted by the list.add, since the list uses double objects. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Autoboxing\n", - "Autoboxing is when Java automatically changes a basic data type into its object form. The Java compiler does this for us. Think of it as putting the data into a box. Java can also unbox an object, which is the exact opposite of autoboxing. When an Integer object is assigned to a primitive int type, Java will automatically use the primitive int version of the number and assign it to the int variable." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [], - "source": [ - "// Boxing\n", - "int a = 5;\n", - "Integer b = a;" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [], - "source": [ - "// Unboxing\n", - "Integer x = new Integer(10);\n", - "int y = x;" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 2.9 Using the Math Class\n", - "\n", - "Java has a built in math class called __Math__? It is a part of the java.lang class." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5\n" - ] - } - ], - "source": [ - "System.out.println(Math.abs(-5)) // Absolute Value" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "25.0\n" - ] - } - ], - "source": [ - "System.out.println(Math.pow(5, 2)) // Power: base, exponent" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5.0\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5.0\n" - ] - } - ], - "source": [ - "// Two ways to calculate square roots\n", - "System.out.println(Math.pow(25, 0.5)); // Allows for different roots\n", - "System.out.println(Math.sqrt(25)) // Square Root" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Finally, arguably the most important class in math: The random class! Many purposes, especially in game development. What is one purpose? " - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0\n" - ] - } - ], - "source": [ - "System.out.println((int)Math.random()) // Always returns zero because the range of math.random is [0, 1)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In the cell below, experiment and try to figure out a way to call Math.random and impliment bounds, with your bounds being integer bounds of a and b." - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "26\n" - ] - } - ], - "source": [ - "// Intended Solution\n", - "\n", - "int a = 0;\n", - "int b = 60;\n", - "System.out.println((int)((double)Math.random() * (b-a) + a))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Hacks!\n", - "Note: This is due __Monday__! Write your hacks in a Jupyter Notebook and then DM them to us over slack by Monday Morning at 8:00 AM. For full credit, all criteria in the hacks must be completed and show some originality. \n", - "\n", - "## Hack 1: (0.25)\n", - "Create a void method that takes an integer input and adds it to an ArrayList. Then, add a non-void method that is able to call a certain index from the ArrayList.\n", - "\n", - "## Hack 2: (0.25)\n", - "Create a simple guessing game with random numbers in math, except the random number is taken to a random exponent (also includes roots), and the person has to find out what the root and exponent is (with hints!). Use at least one static and one non-static method in your class.\n", - "\n", - "## Hack 3: (0.25)\n", - "Create a class of your choosing that has multiple parameters of different types (int, boolean, String, double) and put 5 data values in that list. Show that you can access the information by givng some samples.\n", - "\n", - "\n", - "## Hack 4: (0.25)\n", - "Using your preliminary knowlege of loops, use a for loop to iterate through a person's first and last name, seperated by a space, and create methods to call a person's first name and a person's last name by iterating through the string.\n", - "\n", - "Total: 1/1" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "20.0.2+9-78" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-callinginstances-homework-innovators.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-callinginstances-homework-innovators.ipynb deleted file mode 100644 index e0c8528e73..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-callinginstances-homework-innovators.ipynb +++ /dev/null @@ -1,496 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "bc117346", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Calling-Instance-Methods]\n", - "lesson_language: Java\n", - "lesson_topic: Calling-Instance-Methods\n", - "lesson_part: interactive\n", - "lesson_type: homework\n", - "toc: true\n", - "title: Homework for Calling Instance Methods\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_14_homework\n", - "author: Risha, Aadi, Neil\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "259f9f01", - "metadata": {}, - "source": [ - "Example Class:\n", - "\n", - "```java\n", - "// Suppose we have a class:\n", - "public class Dog {\n", - " private String name;\n", - " public Dog(String name) {\n", - " this.name = name;\n", - " }\n", - " public void bark() {\n", - " System.out.println(name + \" says: Woof!\");\n", - " }\n", - "}\n", - "\n", - "// To use it:\n", - "Dog d = new Dog(\"Fido\"); // create an instance\n", - "d.bark(); // call the instance method on d\n", - "```\n", - "\n", - "## Popcorn Hack #1\n", - "\n", - "- Add another property to the dog class for `breed`.\n", - "- Add another method to the dog class that prints \"My dog `name` is a `breed`!\"\n", - "- Create a new object of this class and call the method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "29ee7d7f", - "metadata": {}, - "outputs": [], - "source": [ - "// Work by [Your Name Here]\n", - "\n", - "public class Dog {\n", - "\n", - " // ADD CODE HERE\n", - "}\n", - "\n", - "// To use it:\n", - "// ADD CODE HERE" - ] - }, - { - "cell_type": "markdown", - "id": "2280d528", - "metadata": {}, - "source": [ - "Example Class 2: \n", - "\n", - "```java\n", - "public class Counter {\n", - " private int count;\n", - " public void add(int x) {\n", - " count += x;\n", - " }\n", - " public int getCount() {\n", - " return count;\n", - " }\n", - "}\n", - "\n", - "// Use it:\n", - "Counter c = new Counter();\n", - "c.add(5);\n", - "int val = c.getCount(); // returns 5\n", - "```\n", - "\n", - "## Popcorn Hack #2\n", - "\n", - "- Add on to the previous counter class and add three more methods for subtraction, multiplication, and division.\n", - "\n", - "- Call all five methods outside of the class." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "53e562e0", - "metadata": {}, - "outputs": [], - "source": [ - "// Work by [Your Name Here]\n", - "\n", - "public class Counter {\n", - " private int count;\n", - " \n", - " // ADD CODE HERE\n", - "}\n", - "\n", - "// Use it:\n", - "// ADD CODE HERE" - ] - }, - { - "cell_type": "markdown", - "id": "eae24a6e", - "metadata": {}, - "source": [ - "--- \n", - "\n", - "## MC Hacks\n", - "\n", - "### Question 1\n", - "\n", - "Consider the following class:\n", - "```java\n", - "public class BankAccount {\n", - " private double balance;\n", - " \n", - " public BankAccount(double initialBalance) {\n", - " balance = initialBalance;\n", - " }\n", - " \n", - " public void deposit(double amount) {\n", - " balance += amount;\n", - " }\n", - " \n", - " public double getBalance() {\n", - " return balance;\n", - " }\n", - "}\n", - "```\n", - "\n", - "Which of the following code segments will compile without error:\n", - "\n", - "A)\n", - "```java\n", - "BankAccount.deposit(50.0);\n", - "double total = BankAccount.getBalance();\n", - "```\n", - "\n", - "B)\n", - "```java\n", - "BankAccount account = new BankAccount(100.0);\n", - "account.deposit(50.0);\n", - "double total = account.getBalance();\n", - "```\n", - "\n", - "C)\n", - "```java\n", - "BankAccount account = new BankAccount(100.0);\n", - "double total = account.deposit(50.0);\n", - "```\n", - "\n", - "D)\n", - "```java\n", - "BankAccount account;\n", - "account.deposit(50.0);\n", - "double total = account.getBalance();\n", - "```\n", - "\n", - "E)\n", - "```java\n", - "double total = getBalance();\n", - "BankAccount account = new BankAccount(total);\n", - "```\n", - "\n", - "### Question 2\n", - "\n", - "What is printed as a result of executing the following code?\n", - "\n", - "```java\n", - "public class Rectangle {\n", - " private int length;\n", - " private int width;\n", - " \n", - " public Rectangle(int l, int w) {\n", - " length = l;\n", - " width = w;\n", - " }\n", - " \n", - " public int getArea() {\n", - " return length * width;\n", - " }\n", - " \n", - " public void scale(int factor) {\n", - " length *= factor;\n", - " width *= factor;\n", - " }\n", - "}\n", - "\n", - "Rectangle rect = new Rectangle(3, 4);\n", - "rect.scale(2);\n", - "System.out.println(rect.getArea());\n", - "```\n", - "\n", - "A) 12\n", - "\n", - "B) 24\n", - "\n", - "C) 48\n", - "\n", - "D) 96\n", - "\n", - "E) Nothing is printed; the code does not compile\n", - "\n", - "### Question 3\n", - "\n", - "Which of the following best describes when a `NullPointerException` will occur when calling an instance method?\n", - "\n", - "A) When the method is declared as `void`\n", - "\n", - "B) When the method is called on a reference variable that has not been initialized to an object\n", - "\n", - "C) When the method's parameters do not match the arguments provided\n", - "\n", - "D) When the method is called from outside the class\n", - "\n", - "E) When the method attempts to return a value but is declared as `void`\n", - "\n", - "### Question 4\n", - "\n", - "Which of the following code segments will NOT compile?\n", - "```java\n", - "public class Temperature {\n", - " private double celsius;\n", - " \n", - " public Temperature(double c) {\n", - " celsius = c;\n", - " }\n", - " \n", - " public double getFahrenheit() {\n", - " return celsius * 9.0 / 5.0 + 32;\n", - " }\n", - " \n", - " public void setCelsius(double c) {\n", - " celsius = c;\n", - " }\n", - "}\n", - "```\n", - "\n", - "A)\n", - "```java\n", - "Temperature temp = new Temperature(0);\n", - "System.out.println(temp.getFahrenheit());\n", - "```\n", - "\n", - "B)\n", - "```java\n", - "Temperature temp = new Temperature(100);\n", - "temp.setCelsius(25);\n", - "```\n", - "\n", - "C)\n", - "```java\n", - "Temperature temp = new Temperature(20);\n", - "double f = temp.getFahrenheit();\n", - "```\n", - "\n", - "D)\n", - "```java\n", - "Temperature temp = new Temperature(15);\n", - "int result = temp.setCelsius(30);\n", - "```\n", - "\n", - "E)\n", - "```java\n", - "Temperature temp = new Temperature(0);\n", - "temp.setCelsius(100);\n", - "double f = temp.getFahrenheit();\n", - "```\n", - "\n", - "### Question 5\n", - "\n", - "Consider the following class:\n", - "```java\n", - "public class Book {\n", - " private String title;\n", - " private int pages;\n", - " \n", - " public Book(String t, int p) {\n", - " title = t;\n", - " pages = p;\n", - " }\n", - " \n", - " public String getTitle() {\n", - " return title;\n", - " }\n", - " \n", - " public int getPages() {\n", - " return pages;\n", - " }\n", - " \n", - " public void addPages(int additional) {\n", - " pages += additional;\n", - " }\n", - "}\n", - "```\n", - "\n", - "Assume that the following code segment appears in a class other than Book:\n", - "\n", - "```java\n", - "Book novel = new Book(\"Java Basics\", 200);\n", - "novel.addPages(50);\n", - "/* missing code */\n", - "```\n", - "\n", - "Which of the following can replace /* missing code */ so that the value 250 is printed?\n", - "\n", - "A) `System.out.println(pages);`\n", - "\n", - "B) `System.out.println(novel.pages);`\n", - "\n", - "C) `System.out.println(Book.getPages());`\n", - "\n", - "D) `System.out.println(novel.getPages());`\n", - "\n", - "E) `System.out.println(getPages());`" - ] - }, - { - "cell_type": "markdown", - "id": "55a1dd38", - "metadata": {}, - "source": [ - "---\n", - "## Homework: Assignment Overview\n", - "\n", - "**Due:** 10/16/2025 \n", - "**Points:** 1\n", - "\n", - "In this assignment, you'll demonstrate your understanding of instance methods by creating a `Student` class that tracks grades and calculates statistics. You'll practice creating student objects, adding grades, calculating averages, and generating grade reports—all using instance methods that operate on each student's individual data.\n", - "\n", - "## Requirements\n", - "Your program must include:\n", - "- A `Student` class with at least 3 instance variables (name, total points, number of assignments)\n", - "- A constructor that initializes the student's name and sets initial values\n", - "- At least 2 void instance methods that modify the student's grades (`addGrade`, `printReport`)\n", - "- At least 2 non-void instance methods that return calculated values (`getAverage`, `getLetterGrade`)\n", - "- A main method that creates at least 2 Student instances and demonstrates all methods working independently\n", - "\n", - "## Homework Hack: Student Grade Tracker\n", - "\n", - "Create a `Student` class that manages a student's grades throughout a semester.\n", - "\n", - "**Required Instance Variables:**\n", - "- `String name` - the student's name\n", - "- `int totalPoints` - sum of all grade points earned\n", - "- `int numAssignments` - count of assignments completed\n", - "\n", - "**Required Instance Methods:**\n", - "- `addGrade(int points)` - void method that adds a grade and updates totals\n", - "- `getAverage()` - returns the student's current average as a double\n", - "- `getLetterGrade()` - returns a String letter grade (A, B, C, D, F) based on average\n", - "- `printReport()` - void method that displays a formatted report of the student's performance\n", - "\n", - "**Grading Scale:**\n", - "- A: 90-100\n", - "- B: 80-89\n", - "- C: 70-79\n", - "- D: 60-69\n", - "- F: below 60\n", - "\n", - "## Sample Output\n", - "\n", - "Here's an example of what your output should look like:\n", - "\n", - "```\n", - "=== Student Grade Tracker System ===\n", - "\n", - "Creating student: Emma Rodriguez\n", - "Student created successfully!\n", - "\n", - "--- Adding Grades for Emma ---\n", - "Adding grade: 95 points\n", - "Adding grade: 88 points\n", - "Adding grade: 92 points\n", - "Adding grade: 85 points\n", - "\n", - "--- Emma's Grade Report ---\n", - "Student Name: Emma Rodriguez\n", - "Total Points: 360\n", - "Assignments Completed: 4\n", - "Current Average: 90.0\n", - "Letter Grade: A\n", - "Status: Excellent work!\n", - "\n", - "========================================\n", - "\n", - "Creating student: James Wilson\n", - "Student created successfully!\n", - "\n", - "--- Adding Grades for James ---\n", - "Adding grade: 78 points\n", - "Adding grade: 82 points\n", - "Adding grade: 75 points\n", - "\n", - "--- James's Grade Report ---\n", - "Student Name: James Wilson\n", - "Total Points: 235\n", - "Assignments Completed: 3\n", - "Current Average: 78.33\n", - "Letter Grade: C\n", - "Status: Keep working hard!\n", - "\n", - "========================================\n", - "\n", - "Final Summary:\n", - "Emma Rodriguez - Average: 90.0 (A)\n", - "James Wilson - Average: 78.33 (C)\n", - "```\n", - "\n", - "## Submission Instructions\n", - "Create a section on your personal blog documenting your completed Student Grade Tracker. Insert the rubric provided below and self-grade yourself with comments as to why you think you deserved that grade. Add screenshots/proof of your code as proof that you fulfilled all the rubric requirements in your blog along with a screenshot of the output (similar to the one provided above). \n", - "\n", - "After updating your blog, please submit a personal blog link of your completed assignment to the google form link inserted in the 'CSA Sign Up Sheet - Team Teach - Trimester 1' spreadsheet.\n", - "\n", - "## Grading Rubric\n", - "\n", - "| Criteria | Percent Weight | Description |\n", - "|----------|---------------|-------------|\n", - "| **Functionality** | 40% | Program runs without errors, creates multiple Student objects, correctly adds grades, calculates averages, and assigns letter grades |\n", - "| **Method Implementation** | 30% | Includes all required methods (addGrade, getAverage, getLetterGrade, printReport) that properly access/modify instance variables |\n", - "| **Code Quality** | 20% | Clean code with meaningful variable names, proper constructor, and helpful comments explaining method purposes |\n", - "| **Output & Presentation** | 10% | Clear, well-formatted output showing multiple students with different grades and formatted reports |\n", - "\n", - "## Tips for Getting Started\n", - "- Review the Counter example from the lesson notes—your Student class will work similarly\n", - "- Start by creating the Student class with the three instance variables\n", - "- Write your constructor to initialize the name and set totalPoints and numAssignments to 0\n", - "- Implement `addGrade()` first—it should add to totalPoints and increment numAssignments\n", - "- Test each method before moving to the next one\n", - "- Remember: Test your hack multiple times and add updates in small increments in case you run into an error\n", - "\n", - "## Tips for Success\n", - "1. **Start simple** - Get your constructor and `addGrade()` working first before tackling calculations\n", - "2. **Watch for division** - When calculating average, make sure to cast to double: `(double)totalPoints / numAssignments`\n", - "3. **Test with multiple students** - Create at least 2 Student objects with different grades to show independence\n", - "4. **Comment your code** - Explain what each method does, especially your letter grade logic\n", - "\n", - "## Bonus Challenges (Optional for Extra Credit)\n", - "Want to go above and beyond? Try adding:\n", - "- A `getHighestGrade()` method that tracks and returns the best individual grade (you'll need to store individual grades, not just the total)\n", - "- A `getLowestGrade()` method for the lowest individual grade\n", - "- A `dropLowestGrade()` method that removes the lowest grade from calculations\n", - "- A `compareTo(Student other)` method that compares two students' averages\n", - "- Weighted grades—allow some assignments to be worth more points than others\n", - "- A `reset()` method that clears all grades and starts fresh\n", - "- Error checking to prevent negative grades or invalid input\n", - "\n", - "**Good luck!**\n", - "\n", - "---\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "java (JJava/j!)", - "language": "java", - "name": "jbang-jjava" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "21.0.8+9-Ubuntu-0ubuntu124.04.1" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-callinginstances-innovators.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-callinginstances-innovators.ipynb deleted file mode 100644 index 115861991b..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.14-callinginstances-innovators.ipynb +++ /dev/null @@ -1,652 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "bc117346", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Calling-Instance-Methods]\n", - "lesson_language: Java\n", - "lesson_topic: Calling-Instance-Methods\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Calling Instance Methods\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_14\n", - "author: Risha, Aadi, Neil\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "9188b761", - "metadata": {}, - "source": [ - "## Overview of Classes, Objects and Methods: A Cookie Analogy\n", - "\n", - "Class = blueprint\n", - "\n", - "- A class is like a recipe. A `Cookie` recipe says what ingredients exist and what steps to follow\n", - "\n", - "Object = Thing made from blueprint\n", - "\n", - "- Each cookie baked with `new Cookie(...)` is its own entity with its own chocolate chips\n", - "\n", - "Method = Action\n", - "\n", - "- Methods are the verbs associated with the object/things the object can do (i.e. `breakInHalf()`, `burn`, or `melt`)\n", - "- A static/class method belongs to the blueprint, not one cookie (i.e. `Cookie.getOvenTemperature()` does not depend on any particular cookie. It is true for all cookies)" - ] - }, - { - "cell_type": "markdown", - "id": "59676d5b", - "metadata": {}, - "source": [ - "## What is an instance method?\n", - "\n", - "An **instance method** is a method (function) defined in a class that operates on a particular instance (object) of that class.\n", - "\n", - "- It can access that object’s instance variables (its state) and perform actions using or modifying them.\n", - "- To use an instance method, you first need an object (an instance), then you call the method via that object.\n", - "\n", - "Continuing with the cookie analogy:\n", - "\n", - "**Instance Method:** action specific cookie can do\n", - "\n", - "- It needs a particular cookie to run (because it uses that cookie’s data).\n", - "- It can read/change that cookie’s fields using `this`.\n", - "- You call it on an object, like `myCookie.addChips(3);`\n", - "\n", - "Compared to a static method, which would only include blueprint-level info (i.e. `public static int ovenTempF() { return 350; }` )" - ] - }, - { - "cell_type": "markdown", - "id": "4cfe67c0", - "metadata": {}, - "source": [ - "## Static/class methods vs. instance methods\n", - "\n", - "| Kind | Called on | Can access | Typical use |\n", - "|----------------|-------------------|-----------------------------|-------------------------------------|\n", - "| Static/Class method | the class itself | only static/class variables | behavior common to all objects |\n", - "| Instance method| a specific object | that object’s instance variables | behavior specific to that one object |\n", - "\n", - "\n", - "In other words:\n", - "\n", - "| Feature | Instance method | Class (`static`) method |\n", - "|-------------------------------------------|-----------------------------------------|-------------------------------------------------|\n", - "| How you call it | `myCookie.addChips(2)` | `Cookie.ovenTempF()` |\n", - "| Has a `this`? | Yes (`this` = that cookie) | No (`this` is illegal) |\n", - "| Can read/change per-object fields? | Yes | No (unless given an object as a parameter) |\n", - "| Common uses | Behaviors tied to one object’s state | Utilities, factory methods, class-wide info |\n", - "| Inheritance behavior | Can be overridden (polymorphism) | Can’t be overridden (only hidden / shadowed) |" - ] - }, - { - "cell_type": "markdown", - "id": "f8f90c13", - "metadata": {}, - "source": [ - "### Visual: Calling Instance Methods\n" - ] - }, - { - "cell_type": "markdown", - "id": "500189bb", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "source": [ - "```mermaid\n", - "sequenceDiagram\n", - " participant Main\n", - " participant c as Counter\n", - "\n", - " Main->>Counter: new Counter()\n", - " activate c\n", - " Main->>c: add(5)\n", - " c-->>Main: (void)\n", - " Main->>c: getCount()\n", - " c-->>Main: 5\n", - " deactivate c\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "c0666752", - "metadata": {}, - "source": [ - "## Syntax of calling an instance method:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4b07c3d9", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Fido says: Woof!\n" - ] - } - ], - "source": [ - "// Suppose we have a class:\n", - "public class Dog {\n", - " private String name;\n", - " public Dog(String name) {\n", - " this.name = name;\n", - " }\n", - " public void bark() {\n", - " System.out.println(name + \" says: Woof!\");\n", - " }\n", - "}\n", - "\n", - "// To use it:\n", - "Dog d = new Dog(\"Fido\"); // create an instance\n", - "d.bark(); // call the instance method on d" - ] - }, - { - "cell_type": "markdown", - "id": "8cb65c99", - "metadata": {}, - "source": [ - "- `d.bark();` invokes the `bark` method on the object `d`.\n", - "\n", - "Inside `bark`, `this.name` refers to `d`’s /`name`." - ] - }, - { - "cell_type": "markdown", - "id": "83e12942", - "metadata": {}, - "source": [ - "## Popcorn Hack #1\n", - "\n", - "- Add another property to the dog class for `breed`.\n", - "- Add another method to the dog class that prints \"My dog `name` is a `breed`!\"\n", - "- Create a new object of this class and call the method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d06eb4f1", - "metadata": {}, - "outputs": [], - "source": [ - "public class Dog {\n", - "\n", - " // ADD CODE HERE\n", - "}\n", - "\n", - "// To use it:\n", - "// ADD CODE HERE" - ] - }, - { - "cell_type": "markdown", - "id": "965887ba", - "metadata": {}, - "source": [ - "If the method takes parameters, you provide arguments:" - ] - }, - { - "cell_type": "markdown", - "id": "caa09136", - "metadata": {}, - "source": [ - "```java\n", - "public class Counter {\n", - " private int count;\n", - " public void add(int x) {\n", - " count += x;\n", - " }\n", - " public int getCount() {\n", - " return count;\n", - " }\n", - "}\n", - "\n", - "// Use it:\n", - "Counter c = new Counter();\n", - "c.add(5);\n", - "int val = c.getCount(); // returns 5\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "c1985ac2", - "metadata": {}, - "source": [ - "- ```c.add(5);``` — calls method ```add``` on ```c``` with argument ```5```.\n", - "- ```c.getCount()```; — calls method that returns an ```int```." - ] - }, - { - "cell_type": "markdown", - "id": "66522e74", - "metadata": {}, - "source": [ - "## Popcorn Hack #2\n", - "\n", - "- Add on to the previous counter class and add three more methods for subtraction, multiplication, and division.\n", - "\n", - "- Call all five methods outside of the class." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b81314b8", - "metadata": {}, - "outputs": [], - "source": [ - "public class Counter {\n", - " private int count;\n", - " \n", - " // ADD CODE HERE\n", - "}\n", - "\n", - "// Use it:\n", - "// ADD CODE HERE" - ] - }, - { - "cell_type": "markdown", - "id": "45c5bc95", - "metadata": {}, - "source": [ - "## Key points & common errors\n", - "\n", - "1. Must have an object reference\n", - "\n", - "- You can’t call an instance method from the class name (unless you have a static context). E.g., ```Dog.bark()```; is invalid (unless ```bark``` is static), because ```bark``` needs a specific object.\n", - "\n", - "2. Return values vs void methods\n", - "\n", - "- A method declared ```void``` doesn’t return anything; you just call it for its side effects (e.g. ```d.bark();```).\n", - "- A non-void method returns a value; you can use that value in expressions, assign it to variables, etc. (e.g. ```int x = c.getCount();```).\n", - "\n", - "3. Passing arguments\n", - "\n", - "- If a method requires parameters, you must supply arguments of matching types when calling.\n", - "\n", - "4. Chaining (optional / advanced)\n", - "\n", - "- If a method returns an object (or the same object), you can chain calls. \n", - "- E.g. ```obj.method1().method2();``` but this is only applicable when the return types line up." - ] - }, - { - "cell_type": "markdown", - "id": "e4c6dc8a", - "metadata": {}, - "source": [ - "## Example: Turtle House\n", - "\n", - "Suppose you have a ```Turtle``` class that can move and draw:" - ] - }, - { - "cell_type": "markdown", - "id": "3798fbb7", - "metadata": {}, - "source": [ - "```java\n", - "public class Turtle {\n", - " private int x, y;\n", - " public void forward(int distance) {\n", - " // move the turtle forward by distance\n", - " }\n", - " public void turnLeft(int degrees) {\n", - " // rotate turtle direction\n", - " }\n", - " public void drawHouse() {\n", - " // uses forward and turnLeft to draw a house\n", - " forward(50);\n", - " turnLeft(90);\n", - " forward(50);\n", - " // etc.\n", - " }\n", - "}\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "cc3469b8", - "metadata": {}, - "source": [ - "You might use it like:" - ] - }, - { - "cell_type": "markdown", - "id": "f1635e34", - "metadata": {}, - "source": [ - "```java\n", - "Turtle t = new Turtle();\n", - "t.drawHouse(); // high-level call, internally calls forward, turnLeft, etc.\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "83efc1de", - "metadata": {}, - "source": [ - "Here, ```drawHouse``` is an instance method that, when invoked on ```t```, calls other instance methods (```forward```, ```turnLeft```) on the same object (implicitly ```this.forward(...)```s, etc.)." - ] - }, - { - "cell_type": "markdown", - "id": "451f2908", - "metadata": {}, - "source": [ - "### Important Rules to Keep in Mind (AP Test-Specific):\n", - "\n", - "1. You must create an object before calling its instance methods. You cannot call an instance method directly on the class name (e.g., ```Dog.bark()``` won't work unless bark is static).\n", - "2. The object reference cannot be ```null```. If you try to call an instance method on a null reference, you'll get a ```NullPointerException``` at runtime.\n", - "3. Arguments must match parameter types exactly (or be compatible through widening conversion). The number, order, and types of arguments must match the method signature.\n", - "4. ```void``` methods don't return values. You cannot assign the result of a ```void``` method to a variable or use it in an expression (e.g., ```int x = d.bark()```; is invalid if ```bark``` is ```void```).\n", - "5. Method calls are evaluated left-to-right. When chaining methods (e.g., ```obj.method1().method2()```), Java evaluates from left to right, and each method must return an appropriate object for the next call.\n", - "6. Instance methods can call other instance methods of the same class directly (without needing ```this.```), and they implicitly operate on the same object.\n", - "7. Parameter names in the method definition don't matter when calling. When you call ```c.add(5)```, the actual argument ```5``` gets passed to whatever the parameter is named in the method definition.\n" - ] - }, - { - "cell_type": "markdown", - "id": "51d1dcba", - "metadata": {}, - "source": [ - "## Bonus Example!" - ] - }, - { - "cell_type": "markdown", - "id": "4e35b36c", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "```java\n", - "// Define the Joke class\n", - "class Joke {\n", - " private String setup;\n", - " private String punchline;\n", - "\n", - " public Joke(String setup, String punchline) {\n", - " this.setup = setup;\n", - " this.punchline = punchline;\n", - " }\n", - "\n", - " public void tellJoke() {\n", - " System.out.println(setup);\n", - " System.out.println(punchline);\n", - " }\n", - "}\n", - "\n", - "// Create and run a joke\n", - "Joke myJoke = new Joke(\"Why don’t programmers like nature?\",\n", - " \"Because it has too many bugs!\");\n", - "\n", - "myJoke.tellJoke();\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "77a2ded7", - "metadata": {}, - "source": [ - "## MC Hacks\n", - "\n", - "### Question 1\n", - "\n", - "Consider the following class:\n", - "```java\n", - "public class BankAccount {\n", - " private double balance;\n", - " \n", - " public BankAccount(double initialBalance) {\n", - " balance = initialBalance;\n", - " }\n", - " \n", - " public void deposit(double amount) {\n", - " balance += amount;\n", - " }\n", - " \n", - " public double getBalance() {\n", - " return balance;\n", - " }\n", - "}\n", - "```\n", - "\n", - "Which of the following code segments will compile without error:\n", - "\n", - "A)\n", - "```java\n", - "BankAccount.deposit(50.0);\n", - "double total = BankAccount.getBalance();\n", - "```\n", - "\n", - "B)\n", - "```java\n", - "BankAccount account = new BankAccount(100.0);\n", - "account.deposit(50.0);\n", - "double total = account.getBalance();\n", - "```\n", - "\n", - "C)\n", - "```java\n", - "BankAccount account = new BankAccount(100.0);\n", - "double total = account.deposit(50.0);\n", - "```\n", - "\n", - "D)\n", - "```java\n", - "BankAccount account;\n", - "account.deposit(50.0);\n", - "double total = account.getBalance();\n", - "```\n", - "\n", - "E)\n", - "```java\n", - "double total = getBalance();\n", - "BankAccount account = new BankAccount(total);\n", - "```\n", - "\n", - "### Question 2\n", - "\n", - "What is printed as a result of executing the following code?\n", - "\n", - "```java\n", - "public class Rectangle {\n", - " private int length;\n", - " private int width;\n", - " \n", - " public Rectangle(int l, int w) {\n", - " length = l;\n", - " width = w;\n", - " }\n", - " \n", - " public int getArea() {\n", - " return length * width;\n", - " }\n", - " \n", - " public void scale(int factor) {\n", - " length *= factor;\n", - " width *= factor;\n", - " }\n", - "}\n", - "\n", - "Rectangle rect = new Rectangle(3, 4);\n", - "rect.scale(2);\n", - "System.out.println(rect.getArea());\n", - "```\n", - "\n", - "A) 12\n", - "\n", - "B) 24\n", - "\n", - "C) 48\n", - "\n", - "D) 96\n", - "\n", - "E) Nothing is printed; the code does not compile\n", - "\n", - "### Question 3\n", - "\n", - "Which of the following best describes when a `NullPointerException` will occur when calling an instance method?\n", - "\n", - "A) When the method is declared as `void`\n", - "\n", - "B) When the method is called on a reference variable that has not been initialized to an object\n", - "\n", - "C) When the method's parameters do not match the arguments provided\n", - "\n", - "D) When the method is called from outside the class\n", - "\n", - "E) When the method attempts to return a value but is declared as `void`\n", - "\n", - "### Question 4\n", - "\n", - "Which of the following code segments will NOT compile?\n", - "```java\n", - "public class Temperature {\n", - " private double celsius;\n", - " \n", - " public Temperature(double c) {\n", - " celsius = c;\n", - " }\n", - " \n", - " public double getFahrenheit() {\n", - " return celsius * 9.0 / 5.0 + 32;\n", - " }\n", - " \n", - " public void setCelsius(double c) {\n", - " celsius = c;\n", - " }\n", - "}\n", - "```\n", - "\n", - "A)\n", - "```java\n", - "Temperature temp = new Temperature(0);\n", - "System.out.println(temp.getFahrenheit());\n", - "```\n", - "\n", - "B)\n", - "```java\n", - "Temperature temp = new Temperature(100);\n", - "temp.setCelsius(25);\n", - "```\n", - "\n", - "C)\n", - "```java\n", - "Temperature temp = new Temperature(20);\n", - "double f = temp.getFahrenheit();\n", - "```\n", - "\n", - "D)\n", - "```java\n", - "Temperature temp = new Temperature(15);\n", - "int result = temp.setCelsius(30);\n", - "```\n", - "\n", - "E)\n", - "```java\n", - "Temperature temp = new Temperature(0);\n", - "temp.setCelsius(100);\n", - "double f = temp.getFahrenheit();\n", - "```\n", - "\n", - "### Question 5\n", - "\n", - "Consider the following class:\n", - "```java\n", - "public class Book {\n", - " private String title;\n", - " private int pages;\n", - " \n", - " public Book(String t, int p) {\n", - " title = t;\n", - " pages = p;\n", - " }\n", - " \n", - " public String getTitle() {\n", - " return title;\n", - " }\n", - " \n", - " public int getPages() {\n", - " return pages;\n", - " }\n", - " \n", - " public void addPages(int additional) {\n", - " pages += additional;\n", - " }\n", - "}\n", - "```\n", - "\n", - "Assume that the following code segment appears in a class other than Book:\n", - "\n", - "```java\n", - "Book novel = new Book(\"Java Basics\", 200);\n", - "novel.addPages(50);\n", - "/* missing code */\n", - "```\n", - "\n", - "Which of the following can replace /* missing code */ so that the value 250 is printed?\n", - "\n", - "A) `System.out.println(pages);`\n", - "\n", - "B) `System.out.println(novel.pages);`\n", - "\n", - "C) `System.out.println(Book.getPages());`\n", - "\n", - "D) `System.out.println(novel.getPages());`\n", - "\n", - "E) `System.out.println(getPages());`" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "java (JJava/j!)", - "language": "java", - "name": "jbang-jjava" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "21.0.8+9-Ubuntu-0ubuntu124.04.1" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.15-java-objects.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.15-java-objects.ipynb deleted file mode 100644 index a14063275a..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.15-java-objects.ipynb +++ /dev/null @@ -1,467 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, String-Manipulation]\n", - "lesson_language: Java\n", - "lesson_topic: String-Manipulation\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: String Manipulation\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_15\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Java objects\n", - "- In Java, objects are essentially instances of classes. They represent real-world entities or concepts and contain both data and behaviors, facilitating organized and modular software design." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Common Types of Java Classes\n", - "In Java, classes are the fundamental building blocks of Object-Oriented Programming (OOP). They define the structure and behavior of objects, serving as templates or blueprints from which objects are created. Java programs typically consist of multiple classes, each designed to fulfill a specific role. One Java class that you should be familliar with is: \n", - "\n", - "\n", - "1. Utility Classes: Utility classes contain static methods that provide common utility functions. These classes are not meant to be instantiated, and they often involve operations such as mathematical calculations, string manipulation, or date formatting. The Math class is an example of a utility class.\n", - " - Java Arrays Class\n", - " - Java HashMap Class\n", - " - Java LinkedList Class" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import java.util.Arrays;\n", - "\n", - "public class ArraySortExample {\n", - " public static void main(String[] args) {\n", - " int[] numbers = {5, 2, 9, 1, 5, 6};\n", - " Arrays.sort(numbers);\n", - " System.out.println(Arrays.toString(numbers));\n", - " }\n", - "}\n", - "String[] words = {\"main\"};\n", - "ArraySortExample.main(words);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<img src=\"image-4.png\" alt=\"Alt text\" width=\"600\" height=\"500\">" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Java Objects\n", - "An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities. `Objects are the instances of a class that are created to use the attributes and methods of a class.` A typical Java program creates many objects, which as you know, interact by invoking methods. An object consists of : \n", - "\n", - "1. State: It is represented by attributes of an object. It also reflects the properties of an object.\n", - "2. Behavior: It is represented by the methods of an object. It also reflects the response of an object with other objects." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Declaring Objects \n", - "\n", - "When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.\n", - "\n", - "As we declare variables like (type name;). This notifies the compiler that we will use the name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variables , the type must be strictly a concrete class name. In general, we can’t create objects of an abstract class or an interface.\n", - "\n", - "### Initializing a Java Object \n", - "The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the class constructor. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Dog {\n", - " public String Name; \n", - " public int Age;\n", - "\n", - " public void Bark(int times) {\n", - " for (int i = 0; i < times; i++) {\n", - " System.out.println(\"Bark\"); \n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) { \n", - " Dog dog = new Dog();\n", - "\n", - " dog.Bark(5);\n", - " }\n", - "}\n", - "Dog.main(words);\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Calling a non-void method\n", - "It's possible to call a non-void method on an object so that it returns a value, the type of which is specified with the method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Dog {\n", - " public String Name; //instance variables\n", - " public int Age;\n", - "\n", - " public Dog(String name, int age) { //construction method\n", - " Name = name;\n", - " Age = age;\n", - " }\n", - "\n", - " public String getName() { //non-void method that returns a String\n", - " return Name;\n", - " }\n", - "\n", - " public static void main(String[] args) { //main code\n", - " Dog d = new Dog(\"Larry\", 4);\n", - " System.out.println(d.getName());\n", - " }\n", - "}\n", - "\n", - "Dog.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Popcorn Hacks\n", - "Modify the code below (the same code as above) to demonstrate one of the following:\n", - "- An additional Non-void method\n", - "- Multiple uses of the same Non-void method on different objects" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Dog {\n", - " public String Name; //instance variables\n", - " public int Age;\n", - "\n", - " public Dog(String name, int age) { //construction method\n", - " Name = name;\n", - " Age = age;\n", - " }\n", - "\n", - " public String getName() { //non-void method that returns a String\n", - " return Name;\n", - " }\n", - "\n", - " public static void main(String[] args) { //main code\n", - " Dog d = new Dog(\"Larry\", 4);\n", - " System.out.println(d.getName());\n", - " }\n", - "}\n", - "\n", - "Dog.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### String Objects\n", - "String objects are built-in objects in Java that you're probably pretty familiar with, but it also functions like a class, with the following properties:\n", - "- String objects can be initialized with the new keyword\n", - "- Method that acts upon String objects can't change the String itself, it is <b>inmmutable</b>. \n", - "- String objects can be concatenated using the + operator, creating a new string that is the combination of the other two strings\n", - "- Escape sequences can be used to print characters that are otherwise unavailable, using the \"\\\" (backslash) symbol\n", - " - \\\" creates a double quote\n", - " - \\\\\\\\ creates a regular backslash (I actually had to use 4 backslashes for this since markdown also recognizes this combination)\n", - " - \\n creates a newline\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Strings_demo {\n", - " public static void main(String[] args) { //main code\n", - " String s1 = \"hello\"; // The way you are probably used to for string objects\n", - " String s2 = new String(\"hello\"); // an alternate method to create the same string variable\n", - " System.out.println(s1);// these two println statements should print the same thing\n", - " System.out.println(s2);\n", - "\n", - " String s3 = s1+s2; // s3 is a concatenation of s1 and s2\n", - " System.out.println(s3);\n", - " System.out.println(s1); // the method doesn't actually change the String itself\n", - "\n", - " String s4 = new String(\"In order to type out a \\\\\\\\ string in Java String, you need 4 \\\\'s \\n You need 3 \\\\'s and 1 \\\" to type out a \\\\\\\"\"); // a demonstration of the escape sequences\n", - " System.out.println(s4);\n", - " }\n", - "}\n", - "Strings_demo.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Here are some of the String methods we use:\n", - "\n", - "|Syntax|Definition|\n", - "|-|-|\n", - "|String(String str)|Constructs a new String object with the same sequence of characters as str|\n", - "|int length()|Returns the number of characters in the String|\n", - "|String substring(int from, in to)|Returns the substring beginning at from to one before to|\n", - "|String substring(int from)|Returns the substring beginning at from to the end|\n", - "|int indexOf(String str)|Returns the first occurence of str, returns -1 if not found|\n", - "|boolean equals(String other)|Returns true if this is equal to other and vice versa|\n", - "|int compareTo(String other)|Returns a value <0 if this is less than other, 0 if they are equal and a value >- if this is greater than other|" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Strings_demo_2 {\n", - " public static void main(String[] args) { //main code\n", - " String s1 = \"hello\"; // Strings for demonstration\n", - " String s2 = new String(\"hihihellothere\"); // Construction using the method\n", - " System.out.println(s2.length());\n", - "\n", - " String s3 = s2.substring(4,9); // creating a substring of s1 from index 4 to 9-1\n", - " System.out.println(s3);\n", - " System.out.println(s1); // these should be the same\n", - "\n", - " System.out.println(s2.indexOf(s1)); //returns the first occurence of hello in hihihellothere (4)\n", - "\n", - " System.out.println(s2.equals(s1)); // returns if hello is the same as hihihellothere (it's not)\n", - " System.out.println(s2.compareTo(s1)); // compares hihihellothere to hello, since it greater since h=h and i>e, this returns a positive number\n", - " System.out.println(s1.compareTo(s2)); // the reversal of the above, returns a negative number\n", - " System.out.println(s3.equals(s1)); // returns if hello is the same as hello (it's)\n", - " System.out.println(s3.compareTo(s1)); // compares hello to hello, since they are the same, this returns a 0\n", - "\n", - " System.out.println(s1);// none of these methods affect the original strings, since Strings are immutatble\n", - " System.out.println(s2);\n", - " System.out.println(s3);\n", - " }\n", - "}\n", - "Strings_demo_2.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Popcorn Hacks\n", - "Using the methods above, create a method that is able to return the position of a substring in a string and use s.o.pl to prove it." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Wrapper Classes\n", - "You may remember the Wrapper classes from before, this will present two additional wrapper classes - Integer and Double\n", - "\n", - "- Integer (not int - notice the non-shortend word and capitalization)\n", - " - int is a primitive data type, and Integer is a wrapper class\n", - "\n", - "|Syntax|Definition|\n", - "|-|-|\n", - "|Integer(int value)|Constructs a new Integer object representing the value|\n", - "|Integer.MIN_VALUE|the minimum value represented by a int or Integer|\n", - "|Integer.MAX_VALUE|the maximum value represented by a int or Integer|\n", - "|int intValue()|Returns the value of Integer as int|\n", - "\n", - "- Double (not double)\n", - " - double is a primitive data type, Double is a wrapper class\n", - "\n", - "|Syntax|Definition|\n", - "|-|-|\n", - "|Double(double value)|Constructs a new Double object representing the value|\n", - "|double doubleValue()|Returns the value of the Double as a double|\n", - "\n", - "(not the most exciting thing I know)\n", - "\n", - "#### ok but why\n", - "In Java, Wrapper classes are used to convert between primitive data types (int, boolean) and only store a single value and Reference types (String, ArrayList).\n", - "It provides a way for us to use primitive datas as objects\n", - "\n", - "#### Autoboxing and Unboxing\n", - "As of Java 5.0, autoboxing and unboxing are added\n", - "\n", - "Autoboxing is the automatic process that Java compiler uses to convert primitive types and their respective Wrapper classes\n", - "\n", - "Unboxing is the opposite, comverting Wrapper classes to primitive types\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Unboxing_stream {\n", - " public static void main(String[] args) { //main code\n", - " int i1 = 10; // primitive data types\n", - " double d1 = 25.5;\n", - "\n", - " Integer I1 = new Integer(i1); // Construction of the Wrapper classes version (superior)\n", - " Double D1 = new Double(d1);\n", - "\n", - " System.out.println(i1); // The values correspond to their original values\n", - " System.out.println(I1);\n", - " System.out.println(d1);\n", - " System.out.println(D1);\n", - "\n", - " int i2 = I1.intValue()+5; //usage of the intValue function\n", - " System.out.println(i2);\n", - " double d2 = D1.intValue()-1.3; //usage of the doubleValue function\n", - " System.out.println(d2);\n", - "\n", - " System.out.println(Integer.MIN_VALUE); // the actual values of the MIN_VALUE and MAX_VALUE\n", - " System.out.println(Integer.MAX_VALUE);\n", - "\n", - " Integer I2 = i1; // autoboxing bypasses the need for contructor methods\n", - " Double D2 = d1;\n", - " System.out.println(I2);\n", - " System.out.println(D2);\n", - "\n", - " int i3 = I2+10; // unboxing without using any methods\n", - " double d3 = D2-1.3;\n", - " System.out.println(i3);\n", - " System.out.println(d3);\n", - " }\n", - "}\n", - "Unboxing_stream.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### the Math class\n", - "Talking about the java object here, math offers several useful method for mathmatical usages.\n", - "- Math methods are static, they belong to the class instead of an object and can be used without creating an object\n", - "- the Math class is already imported as part of java.lane.Math\n", - " - However, you can use the methods without using the Math prefix with the import command import static java.lang.Math.*\n", - "\n", - "|Syntax|Definition|\n", - "|-|-|\n", - "|static int abs(int x)|Returns the absolute value of a int|\n", - "|static double abs(double x)|Returns the absolute value of a double|\n", - "|static double pow(double base, double exponent)|Returns the value of base to the exponent power|\n", - "|static double random()|Returns a random double between 0.0 and 1.0|\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import static java.lang.Math.*; // implicit importation \n", - "\n", - "public class maths_demo {\n", - " public static void main(String[] args) { //main code\n", - " double a=12.5; // ints we will use\n", - " int b=-5;\n", - " int c=4;\n", - "\n", - " System.out.println(abs(a)); // prints the absolute values of a and b\n", - " System.out.println(abs(b)); // should have no effect on a but b should be turned to its opposite (the positive number)\n", - "\n", - " System.out.println(pow(b,c)); // prints the result of b to c\n", - "\n", - " System.out.println(random()*10>4); // returns true if a random number from 0 to 10 is greater than 4, this should return different values with different runs.\n", - " }\n", - "}\n", - "\n", - "maths_demo.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### Popcorn hacks\n", - "Create a variation of the number guessing game and try to use these methods in. Bonus points for creativity." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Hacks\n", - "> Complete all popcorn hacks\n", - "> ### [Quiz](https://docs.google.com/forms/d/e/1FAIpQLScr-jf31aGlkrNUrgu_xyyq29GOfruPDv7_YKKYyWpWqWH_9Q/viewform?usp=sf_link)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "21" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.2-variables.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.2-variables.ipynb deleted file mode 100644 index 3f42682d53..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.2-variables.ipynb +++ /dev/null @@ -1,532 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "462043ad", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "title: Variables and Data Types\n", - "layout: post\n", - "categories: [Java, Variables-and-Data-Types]\n", - "lesson_language: Java\n", - "lesson_topic: Variables-and-Data-Types\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "comments: true\n", - "permalink: /csa/unit_01/1_2\n", - "menu: nav/csa_units/csaunit1.html\n", - "description: Variables and Data Types\n", - "author: Shriya, Nikhil, Adi\n", - "Group: Curators\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "28ef4843", - "metadata": {}, - "source": [ - "# AP CSA Lesson 1.2 – Variables and Data Types\n", - "\n", - "---\n", - "\n", - "## Learning Objectives\n", - "- Understand what variables are and how they store data in memory.\n", - "- Learn the main primitive data types in Java (`int`, `double`, `boolean`, `char`).\n", - "- Differentiate between **primitive types** and **reference types** (like `String`).\n", - "- Practice declaring, assigning, and using variables.\n", - "- Gain hands-on experience with code demos, popcorn hacks, and homework challenges.\n", - "\n", - "---\n", - "\n", - "## Key Vocabulary\n", - "\n", - "<br>\n", - "\n", - "| Term | Definition | Example |\n", - "|-------------------|---------------------------------------------|-----------------------|\n", - "| **Variable** | Named storage location in memory for data. | `int age = 16;` |\n", - "| **Declaration** | Creating a variable with a type. | `double price;` |\n", - "| **Initialization**| Giving the variable a value at creation. | `double price = 4.99;`|\n", - "| **Assignment** | Giving a value later (after declaration). | `price = 5.99;` |\n", - "| **Primitive type**| Basic data types built into Java. | `int, double, boolean, char` |\n", - "| **Reference type**| Points to objects (more complex). | `String, Scanner` |\n", - "\n", - "- **Primitive types** don't have methods \n", - "- **Reference types** are objects and have methods associated with them\n", - "\n", - "---\n", - "\n", - "## Concept Overview\n", - "\n", - "### What is a Variable?\n", - "Think of a variable as a **labeled container** that stores data." - ] - }, - { - "cell_type": "markdown", - "id": "eefafb5c", - "metadata": {}, - "source": [ - "- You can store **numbers, text, or true/false values**.\n", - "- Java requires you to **specify the type** (what kind of data goes in the box).\n", - "\n", - "---\n", - "\n", - "### Java Data Types (AP CSA Focus)\n", - "\n", - "| Type | Meaning | Example | Notes |\n", - "|-----------|---------|---------|-------|\n", - "| `int` | Whole numbers | `int year = 2025;` | Range: about -2 billion → 2 billion |\n", - "| `double` | Decimal numbers | `double price = 4.99;` | More precise than `float` |\n", - "| `boolean` | True/False | `boolean done = false;` | Used for conditions |\n", - "| `char` | Single character | `char grade = 'A';` | Always single quotes |\n", - "| `String` | Text (sequence of chars) | `String name = \"Paul\";` | Not primitive (it’s a class) |\n", - "\n", - "---\n", - "\n", - "### Declaration vs Initialization vs Assignment" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "46c940ca", - "metadata": {}, - "outputs": [], - "source": [ - "int number; // declaration (creates variable)\n", - "number = 10; // assignment (stores 10 later)\n", - "int age = 16; // initialization (declaration + assignment)" - ] - }, - { - "cell_type": "markdown", - "id": "c03a906f", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4f3bdc16", - "metadata": {}, - "outputs": [], - "source": [ - "// Simple Variable Examples\n", - "public class VariableBasics {\n", - " public static void main(String[] args) {\n", - " // Step 1: Declare variables (create empty boxes)\n", - " int age;\n", - " double price;\n", - " \n", - " // Step 2: Put values in the boxes\n", - " age = 16;\n", - " price = 4.99;\n", - " \n", - " // Step 3: Create and fill boxes at the same time\n", - " String name = \"Alex\";\n", - " boolean isStudent = true;\n", - " \n", - " // Print the values\n", - " System.out.println(\"Name: \" + name);\n", - " System.out.println(\"Age: \" + age);\n", - " System.out.println(\"Price: $\" + price);\n", - " System.out.println(\"Is student: \" + isStudent);\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "3b7362b4", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## Final Variables (They Never Change!)\n", - "\n", - "Sometimes you want a variable that **never changes**. Use the word `final`.\n", - "\n", - "### Rules:\n", - "- Use `final` at the beginning\n", - "- Give it a value" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "43b61e7e", - "metadata": {}, - "outputs": [], - "source": [ - "// Final Variables - Values That Never Change\n", - "public class FinalVariables {\n", - " public static void main(String[] args) {\n", - " // These values will NEVER change\n", - " final int MAX_STUDENTS = 30;\n", - " final double TAX_RATE = 0.08;\n", - " final String SCHOOL = \"My High School\";\n", - " \n", - " System.out.println(\"Maximum students: \" + MAX_STUDENTS);\n", - " System.out.println(\"Tax rate: \" + TAX_RATE);\n", - " System.out.println(\"School: \" + SCHOOL);\n", - " \n", - " MAX_STUDENTS = 25; // ERROR! Can't change final variables\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "26915672", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## How to Pick the Right Type\n", - "\n", - "It's like choosing the right size box for different things:\n", - "\n", - "### For Numbers:\n", - "- **Whole numbers** (1, 2, 100) → use `int`\n", - "- **Decimal numbers** (1.5, 3.14) → use `double`\n", - "\n", - "### For Words and Letters:\n", - "- **One letter** ('A', 'B') → use `char`\n", - "- **Words or sentences** → use `String`\n", - "\n", - "### For Yes/No Questions:\n", - "- **True or False** → use `boolean`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "83ec952e", - "metadata": {}, - "outputs": [], - "source": [ - "// Picking the Right Data Type\n", - "public class DataTypeExamples {\n", - " public static void main(String[] args) {\n", - " // Student info - pick the best type for each\n", - " String studentName = \"Sarah\"; // Words → String\n", - " int grade = 10; // Whole number → int\n", - " double gpa = 3.8; // Decimal → double\n", - " char team = 'A'; // One letter → char\n", - " boolean hasPhone = true; // Yes/No → boolean\n", - " \n", - " // More examples\n", - " int numberOfPets = 2; // Counting → int\n", - " double temperature = 72.5; // Decimal → double\n", - " boolean isRaining = false; // True/False → boolean\n", - " \n", - " System.out.println(studentName + \" is in grade \" + grade);\n", - " System.out.println(\"GPA: \" + gpa + \", Team: \" + team);\n", - " System.out.println(\"Has phone: \" + hasPhone);\n", - " System.out.println(\"Pets: \" + numberOfPets);\n", - " System.out.println(\"Temperature: \" + temperature + \"°F\");\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "6b649527", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## Two Types of Variables\n", - "\n", - "### Primitive Types (Simple boxes):\n", - "- Store the actual value\n", - "- Basic types: `int`, `double`, `boolean`, `char`\n", - "- Can't be `null` (empty)\n", - "\n", - "### Reference Types (Fancy boxes):\n", - "- Point to more complex things\n", - "- Examples: `String`\n", - "- Can be `null` (by default)\n", - "- Have special actions (methods) you can use" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8661385d", - "metadata": {}, - "outputs": [], - "source": [ - "// Simple vs Fancy Variable Types\n", - "public class TypeComparison {\n", - " public static void main(String[] args) {\n", - " // Simple types (primitives) - store the actual value\n", - " int number1 = 5;\n", - " int number2 = 5;\n", - " System.out.println(\"Same number? \" + (number1 == number2)); // true\n", - " \n", - " // Fancy types (reference) - more complex\n", - " String word1 = \"Hello\";\n", - " String word2 = \"Hello\";\n", - " System.out.println(\"Same word? \" + word1.equals(word2)); // true\n", - " \n", - " // String can be empty (null), but int cannot\n", - " String emptyText = null;\n", - " System.out.println(\"Empty text: \" + emptyText);\n", - " \n", - " // This would cause an error:\n", - " // int emptyNumber = null; // NOT ALLOWED!\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "cc36ac7b", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 🍿 [Popcorn Hack] Practice #1: Your Favorite Things\n", - "\n", - "**Make variables for your favorite things:**\n", - "\n", - "1. Your favorite food (text)\n", - "2. Your age (whole number)\n", - "3. Your height in feet (decimal)\n", - "4. Do you like pizza? (True/False)\n", - "5. First letter of your favorite color\n", - "6. Your birth year (this never changes... what type of variable will you make it??)\n", - "\n", - "Answer is below:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cc9ff26e", - "metadata": {}, - "outputs": [], - "source": [ - "// Practice #1 - Try it yourself first!\n", - "public class MyFavoriteThings {\n", - " public static void main(String[] args) {\n", - " // Try writing your own code here first!\n", - " \n", - " // Sample answer:\n", - " String favoriteFood = \"Pizza\";\n", - " int myAge = 16;\n", - " double heightInFeet = 5.5;\n", - " boolean likesPizza = true;\n", - " char colorFirstLetter = 'B'; // Blue\n", - " final int BIRTH_YEAR = 2008; // Never changes\n", - " \n", - " System.out.println(\"Favorite food: \" + favoriteFood);\n", - " System.out.println(\"Age: \" + myAge);\n", - " System.out.println(\"Height: \" + heightInFeet + \" feet\");\n", - " System.out.println(\"Likes pizza: \" + likesPizza);\n", - " System.out.println(\"Favorite color starts with: \" + colorFirstLetter);\n", - " System.out.println(\"Born in: \" + BIRTH_YEAR);\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "6d6f87d8", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 🍿 [Popcorn Hack] Practice #2: Pick the Best Type\n", - "\n", - "**What type should you use for each of these?**\n", - "\n", - "1. Number of siblings\n", - "2. Your first name\n", - "3. Are you hungry?\n", - "4. Your favorite letter\n", - "5. Your height in inches\n", - "6. Number of days in a year (never changes)\n", - "\n", - "**Think about it, then check below!**" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4e608306", - "metadata": {}, - "outputs": [], - "source": [ - "\n", - "// Practice #2 - What type for each?\n", - "public class PickTheType {\n", - " public static void main(String[] args) {\n", - " // 1. Number of siblings → int (counting, whole number)\n", - " int siblings = 2;\n", - " \n", - " // 2. Your first name → String (text/words)\n", - " String firstName = \"Alex\";\n", - " \n", - " // 3. Are you hungry? → boolean (yes/no, true/false)\n", - " boolean isHungry = true;\n", - " \n", - " // 4. Your favorite letter → char (single letter)\n", - " char favoriteLetter = 'A';\n", - " \n", - " // 5. Your height in inches → double (might be decimal like 65.5)\n", - " // (Can also be int if your height is a whole number)\n", - " double heightInches = 65.5;\n", - " \n", - " // 6. Days in a year → final int (never changes, whole number)\n", - " final int DAYS_IN_YEAR = 365;\n", - " \n", - " System.out.println(\"Siblings: \" + siblings);\n", - " System.out.println(\"Name: \" + firstName);\n", - " System.out.println(\"Hungry: \" + isHungry);\n", - " System.out.println(\"Favorite letter: \" + favoriteLetter);\n", - " System.out.println(\"Height: \" + heightInches + \" inches\");\n", - " System.out.println(\"Days per year: \" + DAYS_IN_YEAR);\n", - " }\n", - "}\n", - "\n", - "// class method to run the java.\n", - "MyFavoriteThings.main(null);" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "964c684e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello from Java in Jupyter!\n", - "a + b = 12\n" - ] - } - ], - "source": [ - "// Test: Hello Java from Jupyter!\n", - "System.out.println(\"Hello from Java in Jupyter!\");\n", - "\n", - "// Try a simple calculation\n", - "int a = 5;\n", - "int b = 7;\n", - "System.out.println(\"a + b = \" + (a + b));" - ] - }, - { - "cell_type": "markdown", - "id": "d3f8abab", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 🏠 Homework Hack: Simple Grade Calculator\n", - "\n", - "**Make a program that calculates a student's grade:**\n", - "\n", - "### What you need to store:\n", - "1. Student's name (make this final)\n", - "2. Three test scores (whole numbers 0-100)\n", - "4. The class name (make this final)\n", - "\n", - "### What to calculate:\n", - "- Average of the three test scores\n", - "- Show what letter grade they earned" - ] - }, - { - "cell_type": "markdown", - "id": "0c847da7", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## Summary" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b879bc0f", - "metadata": {}, - "outputs": [], - "source": [ - "// Making Variables:\n", - "int age = 16; // Whole number\n", - "double price = 4.99; // Decimal number \n", - "boolean isReady = true; // True or false\n", - "char grade = 'A'; // One letter\n", - "String name = \"Alex\"; // Words/text" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "50c042cd", - "metadata": {}, - "outputs": [], - "source": [ - "// Final Variables (Never Change):\n", - "final int MAX_SCORE = 100;\n", - "final String SCHOOL = \"My School\";\n" - ] - }, - { - "cell_type": "markdown", - "id": "b33abcf0", - "metadata": {}, - "source": [ - "### Picking Types:\n", - "- **Counting things** → `int`\n", - "- **Money, measurements** → `double`\n", - "- **Yes/No questions** → `boolean`\n", - "- **One letter** → `char`\n", - "- **Names, sentences** → `String`\n", - "\n", - "### Remember:\n", - "- Use good names for your variables (`age` not `a`)\n", - "- Final variables use ALL_CAPS\n", - "- Strings need double quotes: `\"hello\"`\n", - "- Chars need single quotes: `'A'`\n", - "\n", - "**🎯 Now you know how to store information in Java! Complete the HW to test your skills.**" - ] - }, - { - "cell_type": "markdown", - "id": "33476191", - "metadata": {}, - "source": [ - "Submission form: https://forms.gle/EJaB8hb5kRYhrYd79" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "java (IJava/j!)", - "language": "java", - "name": "jbang-ijava" - }, - "language_info": { - "name": "java" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.3-output.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.3-output.ipynb deleted file mode 100644 index 91c33f6e74..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.3-output.ipynb +++ /dev/null @@ -1,592 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Expressions-and-Output]\n", - "lesson_language: Java\n", - "lesson_topic: Expressions-and-Output\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Expressions and Output\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_3\n", - "author: Ahaan, Arnav, Shaurya\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## CSA Unit 1.3 — Expressions and Output\n", - "\n", - "\n", - "\n", - "## Learning Objectives\n", - "- **1.3.A**: Develop code to generate output and determine the result that would be displayed.\n", - "- **1.3.B**: Develop code to utilize string literals and determine the result of using string literals.\n", - "- **1.3.C**: Develop code for arithmetic expressions and determine the result of these expressions.\n", - "\n", - "---\n", - "## Essential Knowledge\n", - "- **1.3.A.1**: `System.out.print` and `System.out.println` display information.\n", - " - `println` → prints + moves to a new line.\n", - " - `print` → prints but stays on the same line.\n", - " - `printf` → advanced formatting with placeholders.\n", - "- **1.3.B.1**: A literal is a fixed value (like `5`, `3.14`, or `\"Hello\"`).\n", - "- **1.3.B.2**: A string literal is text inside double quotes.\n", - "- **1.3.B.3**: Escape sequences let you control formatting:\n", - " - `\\\"` → double quote\n", - " - `\\\\` → backslash\n", - " - `\\n` → newline\n", - " - `\\t` → tab\n", - "- **1.3.C.1**: Arithmetic expressions use `int` and `double` with operators (`+`, `-`, `*`, `/`, `%`).\n", - "- **1.3.C.2**: Division with integers truncates toward zero. `%` gives the remainder." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Expressions in Java\n", - "\n", - "Expressions are combinations of **literals**, **variables**, and **operators** that Java evaluates to produce a value. \n", - "In Unit 1.3, we focus on **arithmetic expressions**.\n", - "\n", - "### Arithmetic Operators\n", - "- `+` → addition \n", - "- `-` → subtraction \n", - "- `*` → multiplication \n", - "- `/` → division \n", - "- `%` → modulus (remainder) " - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "10\n", - "4\n", - "21\n", - "2\n", - "1\n" - ] - } - ], - "source": [ - "System.out.println(7 + 3); // 10\n", - "System.out.println(7 - 3); // 4\n", - "System.out.println(7 * 3); // 21\n", - "System.out.println(7 / 3); // 2 (integer division)\n", - "System.out.println(7 % 3); // 1 (remainder)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Integer vs. Decimal Division\n", - "\n", - "- If both operands are int, the result is truncated (no decimals).\n", - "\n", - "- If at least one operand is a double, the result is a double." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2\n", - "2.3333333333333335\n", - "2.3333333333333335\n" - ] - } - ], - "source": [ - "System.out.println(7 / 3); // 2\n", - "System.out.println(7.0 / 3); // 2.333333...\n", - "System.out.println(7 / 3.0); // 2.333333..." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Operator Precedence\n", - "\n", - "Java uses order of operations (PEMDAS):\n", - "\n", - "- Parentheses ()\n", - "\n", - "- Multiplication *, Division /, Modulus %\n", - "\n", - "- Addition +, Subtraction -" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "14\n", - "20\n" - ] - } - ], - "source": [ - "System.out.println(2 + 3 * 4); // 14\n", - "System.out.println((2 + 3) * 4); // 20" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Combining Strings and Numbers\n", - "\n", - "Using + with a string triggers string concatenation." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Result: 53\n", - "Result: 8\n" - ] - } - ], - "source": [ - "System.out.println(\"Result: \" + 5 + 3); // Result: 53\n", - "System.out.println(\"Result: \" + (5 + 3)); // Result: " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Outputs" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Types of Output\n", - "- **System.out.print()** → prints text without newline.\n", - "- **System.out.println()** → prints text with newline.\n", - "- **System.out.printf()** → formatted printing (useful for decimals, alignment).\n", - "\n", - "👉 Think of output as the program talking back to the user. Clear formatting is key!" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello World!\n", - "Done\n" - ] - } - ], - "source": [ - "// Example: println vs print\n", - "System.out.print(\"Hello\");\n", - "System.out.print(\" World\");\n", - "System.out.println(\"!\"); // moves to new line\n", - "System.out.println(\"Done\");" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "She said: \"Java is fun!\"\n", - "Line1\n", - "Line2\n", - "C:\\Users\\Student\n", - "Column1\tColumn2\n" - ] - } - ], - "source": [ - "// Example: Escape Sequences\n", - "System.out.println(\"She said: \\\"Java is fun!\\\"\");\n", - "System.out.println(\"Line1\\nLine2\");\n", - "System.out.println(\"C:\\\\Users\\\\Student\");\n", - "System.out.println(\"Column1\\tColumn2\");\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hack 1" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<div>\n", - " <label for=\"frq1\">Recall as many key formatting tools as you can without refering to the above section and list them here. Then, explain what each of them does. Finally, write a line of code using as many of the tools as you can.</label><br>\n", - " <textarea id=\"frq1\" rows=\"5\" cols=\"80\"></textarea><br>\n", - " <button onclick=\"saveFRQ('frq1')\">💾 Save Answer</button>\n", - "</div>\n", - "<script>\n", - "function saveFRQ(id) {\n", - " let val = document.getElementById(id).value;\n", - " localStorage.setItem(id, val);\n", - " alert(\"Answer saved!\");\n", - "}\n", - "window.addEventListener(\"load\", () => {\n", - " document.querySelectorAll(\"textarea\").forEach(t => {\n", - " let saved = localStorage.getItem(t.id);\n", - " if (saved) t.value = saved;\n", - " });\n", - "});\n", - "</script>\n", - "<br>" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "a + b = 10\n", - "a - b = 4\n", - "a * b = 21\n", - "a / b = 2\n", - "a % b = 1\n", - "x / y = 2.3333333333333335\n" - ] - } - ], - "source": [ - "// Example: Arithmetic Expressions\n", - "int a = 7;\n", - "int b = 3;\n", - "System.out.println(\"a + b = \" + (a + b));\n", - "System.out.println(\"a - b = \" + (a - b));\n", - "System.out.println(\"a * b = \" + (a * b));\n", - "System.out.println(\"a / b = \" + (a / b)); // integer division\n", - "System.out.println(\"a % b = \" + (a % b));\n", - "\n", - "double x = 7.0;\n", - "double y = 3.0;\n", - "System.out.println(\"x / y = \" + (x / y)); // floating-point division" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Real-World Example — Menu.java\n", - "Menus use **expressions and output** to guide the user. This is a real-world example of combining literals, escape sequences, and arithmetic into meaningful display.\n", - "- **Output** gives users choices.\n", - "- **Expressions** let us count and customize menus.\n", - "- **Input (preview of Unit 1.4)** lets users interact with the program." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "==== Main Menu ====\n", - "1. Start Game\n", - "2. Instructions\n", - "3. Exit\n", - "Choose an option: You selected option: 1\n", - "There are 3 total options.\n" - ] - } - ], - "source": [ - "import java.util.Scanner;\n", - "\n", - "public class Menu {\n", - " public static void main(String[] args) {\n", - " Scanner sc = new Scanner(System.in);\n", - "\n", - " System.out.println(\"==== Main Menu ====\");\n", - " System.out.println(\"1. Start Game\");\n", - " System.out.println(\"2. Instructions\");\n", - " System.out.println(\"3. Exit\");\n", - "\n", - " System.out.print(\"Choose an option: \");\n", - " int choice = sc.nextInt();\n", - "\n", - " System.out.println(\"You selected option: \" + choice);\n", - "\n", - " int optionCount = 3;\n", - " System.out.println(\"There are \" + optionCount + \" total options.\");\n", - " }\n", - "}\n", - "\n", - "Menu.main(new String[]{});" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hack 2" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<div>\n", - " <label for=\"frq2\">What are the formatting tools used here and what is their purpose? How do they make the output cleaner/better?<</label><br>\n", - " <textarea id=\"frq2\" rows=\"5\" cols=\"80\"></textarea><br>\n", - " <button onclick=\"saveFRQ('frq2')\">💾 Save Answer</button>\n", - "</div>\n", - "<script>\n", - "function saveFRQ(id) {\n", - " let val = document.getElementById(id).value;\n", - " localStorage.setItem(id, val);\n", - " alert(\"Answer saved!\");\n", - "}\n", - "window.addEventListener(\"load\", () => {\n", - " document.querySelectorAll(\"textarea\").forEach(t => {\n", - " let saved = localStorage.getItem(t.id);\n", - " if (saved) t.value = saved;\n", - " });\n", - "});\n", - "</script>\n", - "<br>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Why Menu.java Matters\n", - "- Uses **output** to display instructions.\n", - "- Uses **expressions** to dynamically show option count.\n", - "- Uses **escape sequences** for clean formatting.\n", - "- Real-world: menus are everywhere (ATMs, games, apps, vending machines).\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Homework Hack 1\n", - "1. **Predict Output**: What will this print?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "System.out.print(\"AP \");\n", - "System.out.print(\"CSA \");\n", - "System.out.print(\"Rocks!\");" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "2. **Fix the Bug**: The following is supposed to print `C:\\Users\\Student`, but it fails. Correct it:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "System.out.println(\"C:\\Users\\Student\");" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "3. **Menu Hack**: Add a 4th option (`Settings`) to `Menu.java` and update `optionCount` accordingly." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "4. **Challenge**: Use `System.out.printf` to print pi with 2 decimals." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "System.out.printf(\"Pi = %.2f\\n\", Math.PI);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Homework Hack 2\n", - "- Expand `Menu.java` into a **calculator menu**:\n", - " 1. Print a menu with options: `Add`, `Subtract`, `Multiply`, `Divide`.\n", - " 2. Ask the user for two numbers.\n", - " 3. Use arithmetic expressions to compute and display the result.\n", - " 4. Example run:\n", - "```\n", - "==== Calculator Menu ====\n", - "1. Add\n", - "2. Subtract\n", - "3. Multiply\n", - "4. Divide\n", - "Choose an option: 1\n", - "Enter first number: 10\n", - "Enter second number: 5\n", - "Result: 15\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Homework Hack 3 Game \n", - "\n", - "Here is the game that you will also be playing, to test your understanding of the lesson. You will screenshot the game score and submit it to the 1.3 google form (this will alos include 1.4 content, submission is for both)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<a href=\"{{site.baseurl}}/csa/1_3_4/quiz\">1.3 and 1.4 Game</a>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Key Takeaways\n", - "- Output = communication from program to user.\n", - "- `print` vs `println` vs `printf` control formatting.\n", - "- Escape sequences handle special characters and formatting.\n", - "- Arithmetic expressions make output dynamic.\n", - "- `Menu.java` demonstrates real-world application of expressions + output." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "21.0.9+10-LTS" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.4-input.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.4-input.ipynb deleted file mode 100644 index dd48894a24..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.4-input.ipynb +++ /dev/null @@ -1,536 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Assignment-and-Input]\n", - "lesson_language: Java\n", - "lesson_topic: Assignment-and-Input\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Assignment Statements and Input\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_4\n", - "author: Nikhil, Xavier, Spencer\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "In this lesson, we explore two fundamental pillars of programming: **assignment statements** (how values flow into variables) and **input** (how programs receive data from users). Understanding these concepts is essential for writing interactive, dynamic programs.\n", - "\n", - "We'll start by learning the concepts through detailed explanations, then apply them in code examples with real-world scenarios, and finally reinforce understanding with interactive practice problems." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Learning Objectives\n", - "By the end of this lesson, you will be able to:\n", - "- **LO 1.4.A**: Develop code for assignment statements with expressions and determine the value stored in variables. \n", - "- **LO 1.4.B**: Develop code to read input using the Scanner class. \n", - "\n", - "You'll understand how data flows in programs, how to make them interactive, and common pitfalls to avoid when working with user input." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Essential Knowledge\n", - "- **1.4.A.1**: Every variable must be assigned a value before use. The value's type must match the declared type. Reference types can hold an object or `null`. \n", - "- **1.4.A.2**: The assignment operator `=` stores the result of the right-hand expression into the left-hand variable. \n", - "- **1.4.A.3**: Expressions are evaluated to a single value before assignment occurs. \n", - "- **1.4.B.1**: Input in Java is commonly handled by the `Scanner` class for reading keyboard data. " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<style>\n", - "/* Style for answer buttons and revealed text */\n", - "details summary {\n", - " color: white !important;\n", - " background-color: #333;\n", - " padding: 8px 12px;\n", - " border-radius: 4px;\n", - " cursor: pointer;\n", - " font-weight: bold;\n", - "}\n", - "\n", - "details summary:hover {\n", - " background-color: #555;\n", - "}\n", - "\n", - "details[open] summary {\n", - " background-color: #444;\n", - " margin-bottom: 10px;\n", - "}\n", - "\n", - "/* Force ALL content inside details to be white with maximum specificity */\n", - "details *, \n", - "details *::before, \n", - "details *::after,\n", - "details p,\n", - "details div,\n", - "details span,\n", - "details strong,\n", - "details em,\n", - "details code,\n", - "details pre,\n", - "details ul,\n", - "details li,\n", - "details text {\n", - " color: white !important;\n", - " background: inherit !important;\n", - "}\n", - "\n", - "/* Container styling */\n", - "details div, details p {\n", - " background-color: #2a2a2a !important;\n", - " padding: 10px;\n", - " border-radius: 4px;\n", - " margin-top: 5px;\n", - "}\n", - "\n", - "/* Override any inherited colors */\n", - "details[open] {\n", - " color: white !important;\n", - "}\n", - "\n", - "details[open] > *:not(summary) {\n", - " color: white !important;\n", - "}\n", - "</style>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Part 1: Assignment Statements\n", - "\n", - "### Understanding Variable Assignment\n", - "\n", - "In Java, variables are **named memory locations** that store values. Think of them as labeled boxes in the computer's memory. Before using a variable, you must:\n", - "\n", - "1. **Declare** it with a specific type (`int`, `double`, `String`, etc.)\n", - "2. **Assign** it a value using the `=` operator\n", - "\n", - "The assignment operator works **right to left**: it evaluates the expression on the right side first, then stores that result in the variable on the left." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// Declaration and initialization\n", - "int a = 5; // 'a' stores the integer 5\n", - "int b = 3; // 'b' stores the integer 3\n", - "int c = a + b; // Expression 'a + b' evaluates to 8, then stored in 'c'\n", - "\n", - "// Reassignment: old value is completely overwritten\n", - "int x = 10; // 'x' holds 10\n", - "x = 20; // 'x' now holds 20 (10 is gone)\n", - "x = x + 5; // Right side: x + 5 = 20 + 5 = 25, then stored back in x\n", - "\n", - "// Reference types and null\n", - "String name = null; // 'name' declared but points to no object\n", - "name = \"Ahaan\"; // 'name' now references a String object containing \"Ahaan\"" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Key Insight: Expression Evaluation\n", - "\n", - "The critical concept here is **order of operations**. Java always:\n", - "1. Evaluates the entire right-hand expression first\n", - "2. Then performs the assignment\n", - "\n", - "This is why `x = x + 5;` works: Java reads the current value of x, adds 5, then stores the result back into x." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack 1.1: Tracing Variable Values\n", - "**Question:** After executing this code, what is the value of `y`? Walk through each line.\n", - "```java\n", - "int x = 10;\n", - "x = 20;\n", - "int y = x;\n", - "```\n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "y is 20. Here's why:\n", - "- Line 1: x is assigned 10\n", - "- Line 2: x is reassigned to 20 (the 10 is overwritten) \n", - "- Line 3: The current value of x (which is 20) is copied into y\n", - "</details>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack 1.2: Type Safety\n", - "**Question:** What happens if you write `int count = \"hello\";`? Why does this fail, and why is this behavior actually helpful?\n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "This produces a compile-time error. Java is strongly-typed, meaning the type of the value must match the variable's declared type. An int can only hold integer values, not strings. This \"strictness\" prevents bugs—if Java allowed this, mathematical operations on count would fail unpredictably at runtime.\n", - "</details>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Part 2: Input with Scanner\n", - "\n", - "### Why Input Matters\n", - "Hardcoded values make programs static and inflexible. Real applications need to respond to user data dynamically. Java's `Scanner` class provides a robust mechanism for reading various data types from input streams.\n", - "\n", - "### Setting Up Scanner\n", - "Two steps are required:\n", - "\n", - "1. **Import** the class at the top of your file:\n", - "```java\n", - "import java.util.Scanner;\n", - "```\n", - "\n", - "2. **Instantiate** a Scanner object connected to standard input:\n", - "```java\n", - "Scanner sc = new Scanner(System.in);\n", - "```\n", - "\n", - "The `System.in` parameter connects the Scanner to your keyboard input stream." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Reading Different Data Types\n", - "Scanner provides type-specific methods for reading input:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import java.util.Scanner;\n", - "\n", - "public class InputDemo {\n", - " public static void main(String[] args) {\n", - " Scanner sc = new Scanner(System.in);\n", - " \n", - " // Reading a String (entire line)\n", - " System.out.print(\"Enter your name: \");\n", - " String name = sc.nextLine();\n", - " System.out.println(\"Hello, \" + name + \"!\");\n", - " \n", - " // Reading an integer\n", - " System.out.print(\"Enter your age: \");\n", - " int age = sc.nextInt();\n", - " System.out.println(\"You entered: \" + age);\n", - " \n", - " // Reading a double\n", - " System.out.print(\"Enter a decimal: \");\n", - " double value = sc.nextDouble();\n", - " System.out.println(\"Double that is: \" + (value * 2));\n", - " \n", - " sc.close(); // Always close to prevent resource leaks\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Scanner Methods Overview\n", - "\n", - "The Scanner class provides several methods for reading different types of input:\n", - "\n", - "- **`nextInt()`** - Reads the next integer value (e.g., `42`)\n", - "- **`nextDouble()`** - Reads the next decimal number (e.g., `3.14`)\n", - "- **`next()`** - Reads the next word up to whitespace (e.g., `\"Hello\"`)\n", - "- **`nextLine()`** - Reads an entire line including spaces (e.g., `\"Hello World\"`)\n", - "\n", - "### Critical Pitfall: The nextInt() / nextLine() Problem\n", - "\n", - "This is one of the most common stumbling blocks for Java beginners. Understanding it requires knowledge of how input buffers work.\n", - "\n", - "**The Problem:**\n", - "When you call `nextInt()`, `nextDouble()`, or `next()`, these methods read only their specific token (the integer, double, or word). Critically, they **do not consume the newline character** (`\\n`) that's created when the user presses Enter. This leftover newline sits in the input buffer.\n", - "\n", - "If you then call `nextLine()`, it immediately encounters this leftover newline, interprets it as an empty line, and returns an empty string without waiting for user input.\n", - "\n", - "**Visual Example:**\n", - "```\n", - "Input Buffer: [2][5][\\n][R][e][m][a][i][n][i][n][g]...\n", - " ↑\n", - "nextInt() reads \"25\" but leaves [\\n] behind\n", - "\n", - "nextLine() immediately consumes [\\n] and returns \"\"\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**The Solution:**\n", - "Insert an extra `sc.nextLine();` call immediately after `nextInt()` or `nextDouble()` to consume the leftover newline before reading a full line." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "Scanner sc = new Scanner(System.in);\n", - "\n", - "System.out.print(\"Enter your age: \");\n", - "int age = sc.nextInt();\n", - "\n", - "// FIX: Consume the leftover newline character\n", - "sc.nextLine();\n", - "\n", - "System.out.print(\"Enter your full name: \");\n", - "String fullName = sc.nextLine(); // Now waits for input correctly\n", - "\n", - "System.out.println(\"Hello, \" + fullName + \"! You are \" + age + \" years old.\");\n", - "sc.close();" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack 2.1: Input Validation\n", - "**Question:** What happens if a user types \"twenty\" when `nextInt()` expects a number? How would you make your program more robust?\n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "A java.util.InputMismatchException is thrown because nextInt() cannot parse non-numeric text. To make it robust:\n", - "- Use hasNextInt() to check if the next token is an integer before reading\n", - "- Or use nextLine() to read as String, then parse with Integer.parseInt() in a try-catch block\n", - "</details>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack 2.2: Token vs Line\n", - "**Question:** If a user enters \"San Diego\" when `next()` is called, what gets stored? What about with `nextLine()`?\n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "- next() stores only \"San\" because it reads until whitespace. \"Diego\" remains in the buffer.\n", - "- nextLine() stores \"San Diego\" because it reads everything until the newline character (Enter key).\n", - "</details>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Part 3: Complete Working Example\n", - "\n", - "Here's a comprehensive example demonstrating proper input handling:" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import java.util.Scanner;\n", - "\n", - "public class InputLesson {\n", - " public static void main(String[] args) {\n", - " System.out.println(\"=== User Information Program ===\\n\");\n", - " Scanner sc = new Scanner(System.in);\n", - "\n", - " // String input\n", - " System.out.print(\"Enter your full name: \");\n", - " String name = sc.nextLine();\n", - " \n", - " // Integer input\n", - " System.out.print(\"Enter your age: \");\n", - " int age = sc.nextInt();\n", - " \n", - " // Double input\n", - " System.out.print(\"Enter your GPA: \");\n", - " double gpa = sc.nextDouble();\n", - " \n", - " // Display results\n", - " System.out.println(\"\\n--- Summary ---\");\n", - " System.out.println(\"Name: \" + name);\n", - " System.out.println(\"Age: \" + age + \" (next year: \" + (age + 1) + \")\");\n", - " System.out.println(\"GPA: \" + gpa);\n", - " \n", - " sc.close();\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack 3: Code Trace\n", - "**Question:** Trace through the complete example. If the user enters \"Alice Wonderland\", 20, and 3.85, what is the exact output?\n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "=== User Information Program ===\n", - "\n", - "Enter your full name: Alice Wonderland\n", - "Enter your age: 20\n", - "Enter your GPA: 3.85\n", - "\n", - "--- Summary ---\n", - "Name: Alice Wonderland\n", - "Age: 20 (next year: 21)\n", - "GPA: 3.85\n", - "</details>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Quick Knowledge Check\n", - "\n", - "**Q1.** What is the value of `x` after this code executes?\n", - "```java\n", - "int x = 4;\n", - "x = x + 3;\n", - "```\n", - "A. 4 \n", - "B. 7 \n", - "C. 3 \n", - "D. null \n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "B. The expression x + 3 evaluates to 4 + 3 = 7, which is then stored in x.\n", - "</details>\n", - "\n", - "---\n", - "\n", - "**Q2:** Which statement(s) correctly declare and initialize a String variable?\n", - "\n", - "A. `String s = 5;` \n", - "B. `String s = null;` \n", - "C. `String s = \"Hello\";` \n", - "D. Both B and C \n", - "\n", - "<details>\n", - "<summary>Answer</summary>\n", - "\n", - "Both B and C are valid. null is a valid value for reference types, and \"Hello\" is a String literal.\n", - "</details>" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Homework Hacks: Pick One to Complete\n", - "\n", - "### Hack 1: Three-Number Average Calculator\n", - "**Task:** Modify the example program to:\n", - "- Prompt for three integers\n", - "- Calculate their average (watch for integer division!)\n", - "- Display the result with two decimal places\n", - "\n", - "**Hint:** Cast at least one number to double before division: `(double) num1 / 3`\n", - "\n", - "### Hack 2: Assignment vs Comparison Explanation \n", - "**Task:** Write an explanation distinguishing between:\n", - "- Assignment operator (`=`)\n", - "- Comparison operator (`==`)\n", - "\n", - "Include code examples showing proper usage of each. Explain a common bug that occurs when these are confused." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "The goal of this lesson is to teach you two key concepts:\n", - "1. **How to assign values to variables** and understand how expressions are evaluated\n", - "2. **How to take in user input** and use them in your program to create interactive applications\n", - "\n", - "These foundational skills will enable you to create dynamic programs that respond to user data rather than relying on hardcoded values." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 8. Interactive Quiz Game\n", - "Finally, here’s a fun quiz game built in **JavaScript + HTML** to test your knowledge of assignment statements, input, and how they connect to the lesson. Play through it and check your understanding!\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<a href=\"{{site.baseurl}}/csa/1_3_4/quiz\">1.3 and 1.4 Game</a>" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "name": "java" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.5-data_casting.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.5-data_casting.ipynb deleted file mode 100644 index 6eb0fa1e64..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.5-data_casting.ipynb +++ /dev/null @@ -1,750 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "a11a4f47", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Casting-and-Range]\n", - "lesson_language: Java\n", - "lesson_topic: Casting-and-Range\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Casting and Range of Variables\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_5\n", - "author: Ansh, Mihir, Yash\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "80b57aee", - "metadata": {}, - "source": [ - "# AP CSA Unit 1.5 — Casting and Range of Variables (2025)\n", - "\n", - "**Scope**: Java casting between `int` and `double`, integer division, modulus, and range/overflow behavior of `int`. \n", - "**Goal**: Predict results, spot overflow, and place casts correctly to control evaluation.\n" - ] - }, - { - "cell_type": "raw", - "id": "dcbafbf9", - "metadata": {}, - "source": [] - }, - { - "cell_type": "markdown", - "id": "8bd42425", - "metadata": {}, - "source": [ - "## Introduction\n", - "\n", - "What do you expect the output of this program to be??????????" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a71dbfec", - "metadata": {}, - "outputs": [], - "source": [ - "int a = 5, b = 2;\n", - "System.out.println(a / b);\n", - "System.out.println((double)a / b);\n", - "System.out.println((int)3.9);\n", - "System.out.println((int)(3.9 + 0.5));\n" - ] - }, - { - "cell_type": "markdown", - "id": "d3757cf6", - "metadata": {}, - "source": [ - "## Learning goals\n", - "- Use `(int)` and `(double)` correctly. \n", - "- Explain truncation vs rounding. \n", - "- Predict results of mixed `int`/`double` expressions. \n", - "- Identify overflow with `Integer.MAX_VALUE` / `Integer.MIN_VALUE`. \n", - "- Apply `%` and integer division rules.\n" - ] - }, - { - "cell_type": "markdown", - "id": "926103c1", - "metadata": {}, - "source": [ - "## Quick reference\n", - "\n", - "**Casting**\n", - "- Widening (automatic): `int → double` (no loss). \n", - "- Narrowing (explicit): `double → int` with truncation toward 0.\n", - "\n", - "**Integer division**\n", - "- If both operands are `int`, result is `int` with truncation. \n", - "- `%` returns the remainder.\n", - "\n", - "**Ranges**\n", - "- `int`: from `-2^31` to `2^31 - 1` ⇒ `-2147483648` to `2147483647`. \n", - "- `double`: ~15 digits of precision, IEEE 754.\n", - "\n", - "**Rounding to nearest `int` (per AP CSA CED)**\n", - "- Non‑negative `x`: `(int)(x + 0.5)` \n", - "- Negative `x`: `(int)(x - 0.5)`\n", - "\n", - "## Casting in Java\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "003a0d13", - "metadata": {}, - "outputs": [], - "source": [ - "public class CastDemo {\n", - " public static void main(String[] args) {\n", - " int a = 7, b = 2;\n", - " System.out.println(a / b); // 3 (int division)\n", - " System.out.println((double)a / b); // 3.5 (promoted to double before divide)\n", - "\n", - " double d = 5.9;\n", - " int t = (int) d; // 5 (truncate toward 0)\n", - " System.out.println(t);\n", - "\n", - " // Rounding to nearest int (per CED):\n", - " int rPos = (int)(d + 0.5); // 6 (non-negative rounding)\n", - " double n = -5.9;\n", - " int rNeg = (int)(n - 0.5); // -6 (negative rounding)\n", - " System.out.println(rPos + \" \" + rNeg);\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "2e5b856a", - "metadata": {}, - "source": [ - "## Integer division and `%`" - ] - }, - { - "cell_type": "markdown", - "id": "5df64ea5", - "metadata": {}, - "source": [ - "int x = 17, y = 5;\n", - "System.out.println(x / y); // 3\n", - "System.out.println(x % y); // 2" - ] - }, - { - "cell_type": "markdown", - "id": "11bb7a20", - "metadata": {}, - "source": [ - "\n", - "Properties: `x == (x / y) * y + (x % y)` when `y != 0`.\n", - "\n", - "## Range and overflow in Java `int`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5a040b47", - "metadata": {}, - "outputs": [], - "source": [ - "int max = Integer.MAX_VALUE; // 2147483647\n", - "int min = Integer.MIN_VALUE; // -2147483648\n", - "\n", - "System.out.println(max + 1); // overflow → -2147483648\n", - "System.out.println(min - 1); // overflow → 2147483647" - ] - }, - { - "cell_type": "markdown", - "id": "e7be835f", - "metadata": {}, - "source": [ - "\n", - "Overflow wraps around within the 32‑bit signed range.\n", - "\n", - "### Python helper: simulate Java 32‑bit `int`\n", - "\n", - "The following Python utilities mimic Java's 32‑bit signed `int` arithmetic so you can experiment inside this notebook.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "dc38675f", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "INT_MIN, INT_MAX: -2147483648 2147483647\n", - "Overflow examples:\n", - "MAX+1 = -2147483648\n", - "MIN-1 = 2147483647\n", - "(-7)/2 = -3 (-7)%2 = -1\n", - "(7)/-2 = -3 (7)%-2 = 1\n" - ] - } - ], - "source": [ - "\n", - "# Utilities to simulate Java 32-bit signed int in Python\n", - "INT_MIN = -2**31\n", - "INT_MAX = 2**31 - 1\n", - "MASK32 = 0xFFFFFFFF\n", - "\n", - "def to_int32(x: int) -> int:\n", - " x &= MASK32\n", - " # convert to signed\n", - " return x if x <= INT_MAX else x - (1 << 32)\n", - "\n", - "def add_int32(a: int, b: int) -> int:\n", - " return to_int32(a + b)\n", - "\n", - "def sub_int32(a: int, b: int) -> int:\n", - " return to_int32(a - b)\n", - "\n", - "def mul_int32(a: int, b: int) -> int:\n", - " return to_int32(a * b)\n", - "\n", - "def div_int32(a: int, b: int) -> int:\n", - " # Java int division truncates toward zero\n", - " if b == 0:\n", - " raise ZeroDivisionError(\"division by zero\")\n", - " q = int(a / b) # Python truncates toward zero for int()\n", - " return to_int32(q)\n", - "\n", - "def mod_int32(a: int, b: int) -> int:\n", - " # Java remainder has same sign as dividend (a)\n", - " if b == 0:\n", - " raise ZeroDivisionError(\"mod by zero\")\n", - " q = div_int32(a, b)\n", - " r = to_int32(a - q * b)\n", - " return r\n", - "\n", - "# Demo\n", - "print(\"INT_MIN, INT_MAX:\", INT_MIN, INT_MAX)\n", - "print(\"Overflow examples:\")\n", - "print(\"MAX+1 =\", add_int32(INT_MAX, 1))\n", - "print(\"MIN-1 =\", sub_int32(INT_MIN, 1))\n", - "print(\"(-7)/2 =\", div_int32(-7, 2), \" (-7)%2 =\", mod_int32(-7, 2))\n", - "print(\"(7)/-2 =\", div_int32(7, -2), \" (7)%-2 =\", mod_int32(7, -2))\n" - ] - }, - { - "cell_type": "markdown", - "id": "abe33b42", - "metadata": {}, - "source": [ - "## Truncation vs rounding (runnable demo)\n", - "\n", - "In Java, `(int) 5.9` → `5` because casting truncates toward 0. \n", - "The CED rounding technique: `(int)(x + 0.5)` for non‑negative, `(int)(x - 0.5)` for negative.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "135bdd65", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "x= 5.1 truncate= 5 ced_round= 5\n", - "x= 5.5 truncate= 5 ced_round= 6\n", - "x= 5.9 truncate= 5 ced_round= 6\n", - "x= -5.1 truncate= -5 ced_round= -5\n", - "x= -5.5 truncate= -5 ced_round= -6\n", - "x= -5.9 truncate= -5 ced_round= -6\n", - "x= 0.49 truncate= 0 ced_round= 0\n", - "x=-0.49 truncate= 0 ced_round= 0\n" - ] - } - ], - "source": [ - "\n", - "def java_truncate(x: float) -> int:\n", - " # Casting double->int truncates toward 0\n", - " return int(x) # Python int() also truncates toward 0\n", - "\n", - "def ced_round(x: float) -> int:\n", - " if x >= 0:\n", - " return int(x + 0.5)\n", - " else:\n", - " return int(x - 0.5)\n", - "\n", - "tests = [5.1, 5.5, 5.9, -5.1, -5.5, -5.9, 0.49, -0.49]\n", - "for v in tests:\n", - " print(f\"x={v:5} truncate={java_truncate(v):3} ced_round={ced_round(v):3}\")\n" - ] - }, - { - "cell_type": "markdown", - "id": "868bfca1", - "metadata": {}, - "source": [ - "## Promotion rules in mixed expressions\n", - "\n", - "- If either operand is `double`, the other is promoted to `double` before the operation. \n", - "- If both are `int`, integer arithmetic is used." - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "65a7a8ed", - "metadata": {}, - "outputs": [ - { - "ename": "SyntaxError", - "evalue": "invalid syntax (2582943399.py, line 1)", - "output_type": "error", - "traceback": [ - " \u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[3]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[31m \u001b[39m\u001b[31mint a = 3, b = 2;\u001b[39m\n ^\n\u001b[31mSyntaxError\u001b[39m\u001b[31m:\u001b[39m invalid syntax\n" - ] - } - ], - "source": [ - "int a = 3, b = 2;\n", - "double x = a / b; // 1.0 (int division then widened)\n", - "double y = (double)a / b; // 1.5 (promoted before divide)" - ] - }, - { - "cell_type": "markdown", - "id": "5f5362b7", - "metadata": {}, - "source": [ - "## Practice: predict the output (Java)\n", - "\n", - "Write your answers, then check against the key below.\n", - "\n", - "**Q1**" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "77e1b377", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2\n", - "2\n", - "2.0\n", - "2.5\n" - ] - } - ], - "source": [ - "int a = 10, b = 4;\n", - "System.out.println(a / b);\n", - "System.out.println(a % b);\n", - "System.out.println((double)(a / b));\n", - "System.out.println((double)a / b);" - ] - }, - { - "cell_type": "markdown", - "id": "2fc41bca", - "metadata": {}, - "source": [ - "**Q2**" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "c61c2783", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "-2\n", - "-3\n", - "3\n" - ] - } - ], - "source": [ - "double d = -2.6;\n", - "System.out.println((int)d);\n", - "System.out.println((int)(d - 0.5));\n", - "System.out.println((int)(-d + 0.5));" - ] - }, - { - "cell_type": "markdown", - "id": "6c7f83c8", - "metadata": {}, - "source": [ - "**Q3**" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e7df7f84", - "metadata": {}, - "outputs": [], - "source": [ - "int x = Integer.MAX_VALUE;\n", - "int y = x + 2;\n", - "System.out.println(x);\n", - "System.out.println(y);" - ] - }, - { - "cell_type": "markdown", - "id": "c2b8c7fc", - "metadata": {}, - "source": [ - "## Answer key\n", - "\n", - "**Q1**\n", - "```\n", - "2\n", - "2\n", - "2.0\n", - "2.5\n", - "```\n", - "\n", - "**Q2**\n", - "```\n", - "-2\n", - "-3\n", - "3\n", - "```\n", - "\n", - "**Q3**\n", - "```\n", - "2147483647\n", - "-2147483647 // wraps: MAX_VALUE + 2\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "d448e351", - "metadata": {}, - "source": [ - "### Optional: use Python helpers to reason about Q1\n", - "\n", - "The following Python mimics the Java behavior for integer parts.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "f6de1e45", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "a / b = 2\n", - "a % b = 2\n", - "(double)(a / b) = 2.0\n", - "(double)a / b = 2.5\n" - ] - } - ], - "source": [ - "\n", - "# Q1 reasoning\n", - "a, b = 10, 4\n", - "print(\"a / b =\", int(a / b)) # integer division result\n", - "print(\"a % b =\", a - int(a / b) * b)\n", - "print(\"(double)(a / b) =\", float(int(a / b)))\n", - "print(\"(double)a / b =\", a / b) # Python uses float division here by default" - ] - }, - { - "cell_type": "markdown", - "id": "891505df", - "metadata": {}, - "source": [ - "## FRQ-style tasks\n", - "\n", - "**FRQ 1. Average with correct casting** \n", - "Write a method `avgInt` that takes two `int` values and returns their average as a `double`, preserving the `.5` if present.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "73fd04b6", - "metadata": {}, - "outputs": [], - "source": [ - "public static double avgInt(int a, int b) {\n", - " // your code\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "b93bd549", - "metadata": {}, - "source": [ - "**FRQ 2. Percentage** \n", - "Given `int correct` and `int total`, compute the percentage as a `double` from 0.0 to 100.0 **without** losing fractional precision." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fe8b95db", - "metadata": {}, - "outputs": [], - "source": [ - "public static double percent(int correct, int total) {\n", - " // your code\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "ce4a91e8", - "metadata": {}, - "source": [ - "**FRQ 3. Safe remainder** \n", - "Implement `safeMod(int a, int b)` that returns `a % b`, but if `b == 0`, it should return `0` instead of throwing." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "73def34d", - "metadata": {}, - "outputs": [], - "source": [ - "public static int safeMod(int a, int b) {\n", - " // your code\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "e9b584ee", - "metadata": {}, - "source": [ - "## Suggested solutions (Java)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2c7e6cea", - "metadata": {}, - "outputs": [], - "source": [ - "// FRQ 1\n", - "public static double avgInt(int a, int b) {\n", - " return ((double)a + b) / 2.0;\n", - "}\n", - "\n", - "// FRQ 2\n", - "public static double percent(int correct, int total) {\n", - " if (total == 0) return 0.0;\n", - " return 100.0 * ((double) correct) / total;\n", - "}\n", - "\n", - "// FRQ 3\n", - "public static int safeMod(int a, int b) {\n", - " if (b == 0) return 0;\n", - " return a % b;\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "71832932", - "metadata": {}, - "source": [ - "# Java Casting MCQ's" - ] - }, - { - "cell_type": "markdown", - "id": "007b85a9", - "metadata": {}, - "source": [ - "Here are 5 multiple-choice questions on Java casting:\n", - "\n", - "**Question 1:**\n", - "What is the output of the following code?\n", - "A) 7.9 \n", - "B) 8 \n", - "C) 7 \n", - "D) 8.0 \n", - "E) Compile error" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a1d124c1", - "metadata": {}, - "outputs": [], - "source": [ - "double x = 7.9;\n", - "int y = (int) x;\n", - "System.out.println(y);" - ] - }, - { - "cell_type": "markdown", - "id": "3a53b66e", - "metadata": {}, - "source": [ - "**Question 2:**\n", - "Which of the following statements will compile without error?\n", - "A) `int c = a + b;` \n", - "B) `int c = (int)(a + b);` \n", - "C) `int c = a + (int)b;` \n", - "D) Both B and C \n", - "E) All of the above" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "849eae52", - "metadata": {}, - "outputs": [], - "source": [ - "int a = 10;\n", - "double b = 5.5;" - ] - }, - { - "cell_type": "markdown", - "id": "4d25817a", - "metadata": {}, - "source": [ - "**Question 3:**\n", - "What is the result of the following code?\n", - "A) 4.5 \n", - "B) 4 \n", - "C) 5 \n", - "D) 4.0 \n", - "E) Compile error" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e4e0d500", - "metadata": {}, - "outputs": [], - "source": [ - "int num = 9 / 2;\n", - "System.out.println(num);" - ] - }, - { - "cell_type": "markdown", - "id": "f6147e88", - "metadata": {}, - "source": [ - "**Question 4:**\n", - "Given the following code, what is printed?\n", - "A) 15 \n", - "B) 16 \n", - "C) 15.5 \n", - "D) 16.0 \n", - "E) 15.7" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "80ecae51", - "metadata": {}, - "outputs": [], - "source": [ - "double d = 15.7;\n", - "int i = (int)(d + 0.5);\n", - "System.out.println(i);" - ] - }, - { - "cell_type": "markdown", - "id": "adf7f09b", - "metadata": {}, - "source": [ - "**Question 5:**\n", - "Which statement about casting is TRUE?\n", - "A) Casting from int to double requires explicit casting \n", - "B) Casting from double to int requires explicit casting \n", - "C) Casting from int to double may result in loss of data \n", - "D) Casting is never necessary in Java \n", - "E) Casting from double to int always rounds to the nearest integer" - ] - }, - { - "cell_type": "markdown", - "id": "3eaf4ef4", - "metadata": {}, - "source": [] - }, - { - "cell_type": "markdown", - "id": "8eb979bf", - "metadata": {}, - "source": [ - "## Homework Submission\n", - "\n", - "- MCQ answers (on the google form)\n", - "- Entire notebook with all code cells EXECUTED and VISIBLE on your GitHub Pages (ex. https://yourgithubusername.github.io/)\n", - "\n", - "[Form link](https://forms.gle/aLo8Ley1SUAy8KqP9)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "python", - "pygments_lexer": "java", - "version": "3.13.1" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.6-operators-innovators.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.6-operators-innovators.ipynb deleted file mode 100644 index 5354742937..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.6-operators-innovators.ipynb +++ /dev/null @@ -1,339 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "c45bf0b6", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Compound-Assignment-Operators]\n", - "lesson_language: Java\n", - "lesson_topic: Compound-Assignment-Operators\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Compound Assignment Operators\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_6\n", - "author: Ruta, Vibha, Anvay\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "4ab2f3f9", - "metadata": {}, - "source": [ - "# Compound Assignment Operators (AP CS A, Unit 1.6)\n", - "\n", - "\n", - "## What Are They, and What Do They Help With?\n", - "##### A **compound assignment operator** combines an arithmetic (or other) operation with an assignment in one statement. \n", - "\n", - "**For example, instead of writing:**\n", - "```java\n", - "score = score + 10;\n", - "```\n", - "**You can write:**\n", - "```java\n", - "score += 10;\n", - "```\n", - "## Learning Goals For End of Lesson\n", - "By the end of this lesson, you'll be able to:\n", - "- Transform clunky `x = x + y` statements into sleek compound assignments\n", - "- Master all the essential operators (`+=`, `-=`, `*=`, `/=`, `%=`, `++`, `--`)\n", - "- Understand evaluation order and avoid common traps\n" - ] - }, - { - "cell_type": "markdown", - "id": "e356a2b6", - "metadata": {}, - "source": [ - "## Table of Different Operations in Java\n", - "\n", - "| Operator | Equivalent Full Form | Purpose / Typical Use |\n", - "|----------|---------------------|----------------------|\n", - "| `+=` | `x = x + y` | Add to a running total; accumulate; string concatenation when LHS is a String. |\n", - "| `-=` | `x = x - y` | Subtract / reduce something (e.g. subtract a cost, penalty). |\n", - "| `*=` | `x = x * y` | Multiply — useful for scaling, growth, repeated doubling or factors. |\n", - "| `/=` | `x = x / y` | Divide — scaling down; used in averages, proportions. (Watch out: integer division if both operands are ints.) |\n", - "| `%=` | `x = x % y` | Remainder after division — wrap-around logic, parity checks, keeping things within bounds. |\n", - "| `++` | `x = x + 1` | Add one; often used in loops, counters. |\n", - "| `--` | `x = x - 1` | Subtract one; used in loops as well as decrementing counters. |" - ] - }, - { - "cell_type": "markdown", - "id": "875d8f88", - "metadata": {}, - "source": [ - "## Popcorn Hack #1: \n", - "Transform this beginner code into more advanced code using compound assignment operators." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "72ae5a90", - "metadata": {}, - "outputs": [], - "source": [ - "int playerScore = 1000;\n", - "int playerHealth = 100;\n", - "int enemiesDefeated = 0;\n", - "\n", - "// Player defeats an enemy worth 250 points\n", - "playerScore = playerScore + 250;\n", - "\n", - "// Player takes 15 damage\n", - "playerHealth = playerHealth - 15;\n", - "\n", - "// Enemy count goes up\n", - "enemiesDefeated = enemiesDefeated + 1;\n", - "\n", - "// Boss battle: double the current score!\n", - "playerScore = playerScore * 2;\n", - "\n", - "// Healing potion restores health to 80% of current\n", - "playerHealth = playerHealth * 4;\n", - "playerHealth = playerHealth / 5; // 4/5 = 0.8, but we need integer math" - ] - }, - { - "cell_type": "markdown", - "id": "728202e2", - "metadata": {}, - "source": [ - "### Examples to further understand this concept:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1095fe00", - "metadata": {}, - "outputs": [], - "source": [ - "public class Example {\n", - " public static void main(String[] args) {\n", - " int score = 100;\n", - " double average = 85.5;\n", - " score += 50; // score = 150\n", - " score -= 25; // score = 125\n", - " score *= 2; // score = 250\n", - " score /= 5; // score = 50 (integer division)\n", - " score %= 15; // score = 5 (50 % 15)\n", - " average += 4.5; // average = 90.0\n", - " int count = 0;\n", - " count++; // count = 1\n", - " count--;\n", - " System.out.println(count); // count = 0\n", - " }\n", - "}\n", - "Example.main(null);\n", - "\n", - "// Output: 0\n", - "// Output: 0 \n", - "// Explanation: The code demonstrates various assignment and arithmetic operations, including integer division and the modulus operator. The final output is 0 after incrementing and decrementing the count variable." - ] - }, - { - "cell_type": "markdown", - "id": "b821cce5", - "metadata": {}, - "source": [ - "## Popcorn Hack #2: \n", - "Write a short program where a variable called ```score``` starts at 100. Use at least three different compound assignment operators to update score, and print the result after each step.\n", - "\n", - "Example goals to try:\n", - "1. Deduct points for a wrong answer (```-=```)\n", - "2. Double the score with a power-up (```*=```)\n", - "3. Find remainder after dividing by 7 (```%=```)" - ] - }, - { - "cell_type": "markdown", - "id": "f7f65161", - "metadata": {}, - "source": [ - "### Important Rules to keep in mind (AP Test-Specific):\n", - "1. You can only use these when the variable on the left already exists and has a value.\n", - "\n", - "2. Integer division: when you divide two ints, the fractional part is truncated. Be careful with ```/=```.\n", - "\n", - "3. Only post-form (```x++```, ```x--```) is in scope for the AP exam. Prefix forms (++x) are out of scope." - ] - }, - { - "cell_type": "markdown", - "id": "1ac7f636", - "metadata": {}, - "source": [ - "# Homework Assignment for Unit 1.6\n", - "\n", - "**Due:** 10/9/2025 \n", - "\n", - "---\n", - "\n", - "## Assignment Overview\n", - "\n", - "Now that you've learned about compound assignment operators, it's time to put them into practice! You'll create a short Java program that models a real-world scenario.\n", - "\n", - "## Requirements\n", - "\n", - "Your program must include:\n", - "- **At least 3 different** compound assignment operators (`+=`, `-=`, `*=`, `/=`, `%=`, `++`, `--`)\n", - "- **Meaningful variable names** that make sense for your chosen scenario\n", - "- **Print statements** showing the value after each operation\n", - "- **Comments** explaining what each operation represents in your scenario\n", - "- A **main method** that runs your simulation\n", - "\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "7f98a04b", - "metadata": {}, - "source": [ - "## Scenario Options\n", - "\n", - "Choose **ONE** of the following scenarios to model:\n", - "\n", - "### **Option A: Social Media Influencer Simulator**\n", - "Model the journey of a content creator tracking their growth:\n", - "\n", - "##### **Suggested variables to track:**\n", - "- `followers` - Start with some initial followers\n", - "- `posts` - Number of posts made\n", - "- `engagement` - Likes/comments received\n", - "- `sponsorshipEarnings` - Money earned from sponsors\n", - "\n", - "##### **Example operations you might use:**\n", - "- Gain followers from a viral post (`followers += 1000`)\n", - "- Lose followers from controversial content (`followers -= 50`)\n", - "- Double engagement from a trending hashtag (`engagement *= 2`)\n", - "- Calculate average engagement per post (`engagement /= posts`)\n", - "- Find your ranking position (`position %= 100`)\n" - ] - }, - { - "cell_type": "markdown", - "id": "c450ea2d", - "metadata": {}, - "source": [ - "### **Option B: Bank Account Manager**\n", - "Simulate managing a personal bank account over time:\n", - "\n", - "##### **Suggested variables to track:**\n", - "- `balance` - Current account balance\n", - "- `transactions` - Number of transactions made\n", - "- `monthlyFee` - Account maintenance costs\n", - "- `interestRate` - Interest earned/applied\n", - "\n", - "##### **Example operations you might use:**\n", - "- Add monthly salary (`balance += 3000`)\n", - "- Subtract rent payment (`balance -= 1200`)\n", - "- Apply interest rate (`balance *= 1.02`)\n", - "- Average monthly spending (`spending /= 12`)\n", - "- Check account tier eligibility (`tier %= 5`)" - ] - }, - { - "cell_type": "markdown", - "id": "6c00ecf0", - "metadata": {}, - "source": [ - "### **Option C: Fitness Progress Tracker** \n", - "Track your fitness journey and daily health metrics:\n", - "\n", - "##### **Suggested variables to track:**\n", - "- `totalCalories` - Calories consumed/burned\n", - "- `workoutDays` - Days you've exercised\n", - "- `stepCount` - Daily step count\n", - "- `weightGoal` - Target weight progress\n", - "\n", - "##### **Example operations you might use:**\n", - "- Add calories from meals (`totalCalories += 600`)\n", - "- Burn calories from exercise (`totalCalories -= 300`)\n", - "- Double steps from an active day (`stepCount *= 2`)\n", - "- Calculate average daily steps (`stepCount /= 7`)\n", - "- Track weekly goal progress (`progress %= 7`)" - ] - }, - { - "cell_type": "markdown", - "id": "1240b7f1", - "metadata": {}, - "source": [ - "\n", - "---\n", - "## Sample Output Format\n", - "\n", - "Your program should produce an output similar to this (**this is an example for Option A but the format for other options is similar**):\n", - "\n", - "```\n", - "=== SOCIAL MEDIA SIMULATOR ===\n", - "\n", - "Starting followers: 500\n", - "\n", - "Posted a new video!\n", - "\n", - "Followers: 750 (+250 from the viral video)\n", - "\n", - "Controversial opinion posted...\n", - "\n", - "Followers: 700 (-50 from upset followers)\n", - "\n", - "Trending hashtag boost!\n", - "\n", - "Followers: 1400 (doubled from trending!)\n", - "\n", - "Average engagement per post: 35\n", - "\n", - "Final ranking position: 400\n", - "\n", - "=== SIMULATION COMPLETE ===\n", - "```\n", - "\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "dc8347e5", - "metadata": {}, - "source": [ - "## Submission Instructions\n", - "**Create a section on your personal blog documenting one of the three provided options. After updating your blog, please submit a personal blog link of your completed assignment to the google form link inserted in the 'CSA Sign Up Sheet - Team Teach - Trimester 1' spreadsheet.**\n", - "\n", - "Here is where to submit your homework by **10/9/2025**! ([Lesson 1.6 Hacks + Homework Submission Form](https://forms.gle/tx7i7TntBVR3umPeA))\n", - "\n", - "**Please read the requirements in the form description before submitting your homework.**" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "17.0.16+0" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.7-grinders-apis-homework.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.7-grinders-apis-homework.ipynb deleted file mode 100644 index 3d51013a10..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.7-grinders-apis-homework.ipynb +++ /dev/null @@ -1,128 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "---\n", - "title: Application Program Interface (API) and Libraries Homework\n", - "description: Understanding Application Program Interfaces and Java Libraries - Homework\n", - "layout: post\n", - "categories: [Java, APIs-and-Libraries]\n", - "lesson_language: Java\n", - "lesson_topic: APIs-and-Libraries\n", - "lesson_part: interactive\n", - "lesson_type: homework\n", - "type: hacks\n", - "menu: nav/csa_units/csaunit1.html\n", - "toc: true\n", - "permalink: /csa/unit_01/1_7/homework\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 📝 Homework Hack: Phone Class\n", - "\n", - "Create a `Phone` class that demonstrates **all concepts** from this lesson:\n", - "- Libraries/Classes\n", - "- Packages (use ArrayList from java.util)\n", - "- Attributes\n", - "- Behaviors\n", - "\n", - "### Requirements:\n", - "\n", - "**Attributes (4):**\n", - "- `brand` (String)\n", - "- `model` (String)\n", - "- `batteryLevel` (int) - starts at 100\n", - "- `contacts` (ArrayList<String>)\n", - "\n", - "**Behaviors (5 methods):**\n", - "1. Constructor - sets brand and model, initializes empty contacts list\n", - "2. `displayInfo()` - prints brand, model, and battery level\n", - "3. `addContact(String name)` - adds name to contacts list\n", - "4. `showContacts()` - prints all contacts\n", - "5. `usePhone(int minutes)` - decreases battery by minutes used\n", - "\n", - "**Testing:**\n", - "- Create 2 Phone objects\n", - "- Add 3 contacts to each phone\n", - "- Use phone for some minutes\n", - "- Display all information\n", - "\n", - "### Grading:\n", - "- Correct attributes (4 points)\n", - "- Correct methods (5 points)\n", - "- Proper use of ArrayList from java.util (3 points)\n", - "- Complete testing (3 points)\n", - "- **Total: 15 points**" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [], - "source": [ - "// Homework Hack: Complete the Phone class\n", - "\n", - "import java.util.ArrayList;\n", - "\n", - "public class Phone {\n", - " // TODO: Add 4 attributes\n", - " \n", - " // TODO: Add constructor\n", - " \n", - " // TODO: Add displayInfo() method\n", - " \n", - " // TODO: Add addContact(String name) method\n", - " \n", - " // TODO: Add showContacts() method\n", - " \n", - " // TODO: Add usePhone(int minutes) method\n", - " \n", - "}\n", - "\n", - "// Test your Phone class\n", - "public class PhoneTest {\n", - " public static void main(String[] args) {\n", - " // TODO: Create 2 Phone objects\n", - " \n", - " // TODO: Add 3 contacts to each\n", - " \n", - " // TODO: Use phones for some minutes\n", - " \n", - " // TODO: Display all information\n", - " \n", - " }\n", - "}\n", - "\n", - "// PhoneTest.main(null);" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "11.0.12" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.7-grinders-apis.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.7-grinders-apis.ipynb deleted file mode 100644 index 1e30642517..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.7-grinders-apis.ipynb +++ /dev/null @@ -1,586 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "title: Application Program Interface (API) and Libraries\n", - "description: Understanding Application Program Interfaces and Java Libraries\n", - "layout: post\n", - "categories: [Java, APIs-and-Libraries]\n", - "lesson_language: Java\n", - "lesson_topic: APIs-and-Libraries\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "type: hacks\n", - "menu: nav/csa_units/csaunit1.html\n", - "toc: true\n", - "permalink: /csa/unit_01/1_7\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Topic 1.7: Application Program Interface (API) and Libraries\n", - "\n", - "<a href=\"{{ site.baseurl }}/csa/unit_01/1_7/homework\">Link to Homework</a>\n", - "\n", - "## College Board Requirements\n", - "\n", - "### Essential Knowledge 1.7.A.1\n", - "- **Libraries** = collections of classes\n", - "- **API** = tells you how to use classes \n", - "- **Packages** = organize classes\n", - "- **Documentation** = explains attributes and behaviors\n", - "\n", - "### Essential Knowledge 1.7.A.2\n", - "- **Attributes** = data (variables)\n", - "- **Behaviors** = actions (methods)\n", - "\n", - "---\n", - "\n", - "## 1. Libraries = Collections of Classes\n", - "\n", - "A **library** is a collection of pre-written classes that you can use in your programs.\n", - "\n", - "Think of it like a toolbox:\n", - "- Instead of building every tool from scratch, you use tools that already exist\n", - "- Java provides many libraries with useful classes\n", - "- You can create objects from these classes to solve problems\n", - "\n", - "**Example:** Java's standard library includes:\n", - "- `String` class - for working with text\n", - "- `ArrayList` class - for storing lists of items\n", - "- `Math` class - for mathematical operations\n", - "- `Random` class - for generating random numbers" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello, CSA!\n", - "Square root of 16: 4.0\n" - ] - } - ], - "source": [ - "// Using classes from Java's library\n", - "\n", - "public class LibraryDemo {\n", - " public static void main(String[] args) {\n", - " // Using String class from library\n", - " String message = \"Hello, CSA!\";\n", - " \n", - " // Using Math class from library \n", - " double result = Math.sqrt(16);\n", - " \n", - " System.out.println(message);\n", - " System.out.println(\"Square root of 16: \" + result);\n", - " }\n", - "}\n", - "\n", - "LibraryDemo.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 2. API = Tells You How to Use Classes\n", - "\n", - "An **API (Application Programming Interface)** is like an instruction manual.\n", - "\n", - "**Restaurant Analogy:**\n", - "- Menu (API) shows what dishes are available\n", - "- Menu describes each dish\n", - "- You order from the menu without knowing how to cook\n", - "\n", - "**In Java:**\n", - "- API documentation shows what classes are available\n", - "- API describes methods you can call\n", - "- You use classes without knowing how they work internally\n", - "\n", - "**Example: String API tells us:**\n", - "- `length()` - returns number of characters\n", - "- `toUpperCase()` - converts to uppercase\n", - "- `substring(start, end)` - extracts part of string" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Original: Computer Science\n", - "Length: 16\n", - "Uppercase: COMPUTER SCIENCE\n", - "First 8 chars: Computer\n" - ] - } - ], - "source": [ - "// Using methods from String API\n", - "\n", - "public class APIDemo {\n", - " public static void main(String[] args) {\n", - " String text = \"Computer Science\";\n", - " \n", - " // Methods from String API\n", - " System.out.println(\"Original: \" + text);\n", - " System.out.println(\"Length: \" + text.length());\n", - " System.out.println(\"Uppercase: \" + text.toUpperCase());\n", - " System.out.println(\"First 8 chars: \" + text.substring(0, 8));\n", - " }\n", - "}\n", - "\n", - "APIDemo.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 3. Packages = Organize Classes\n", - "\n", - "**Packages** organize classes into groups (like folders organize files).\n", - "\n", - "### Common Java Packages:\n", - "\n", - "| Package | Description | Example Classes |\n", - "|---------|-------------|------------------|\n", - "| `java.lang` | Fundamental classes | String, Math, Integer |\n", - "| `java.util` | Utility classes | ArrayList, Scanner, Random |\n", - "| `java.io` | Input/Output | File, FileReader |\n", - "\n", - "### Important Rule:\n", - "- `java.lang` classes **don't need** import statements\n", - "- All other packages **need** import statements" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "String: Java\n", - "Absolute value: 5\n", - "ArrayList: [Item 1]\n" - ] - } - ], - "source": [ - "// Demonstrating packages\n", - "\n", - "import java.util.ArrayList; // Need import for java.util\n", - "\n", - "public class PackageDemo {\n", - " public static void main(String[] args) {\n", - " // java.lang - no import needed\n", - " String name = \"Java\";\n", - " int num = Math.abs(-5);\n", - " \n", - " // java.util - import needed\n", - " ArrayList<String> list = new ArrayList<>();\n", - " list.add(\"Item 1\");\n", - " \n", - " System.out.println(\"String: \" + name);\n", - " System.out.println(\"Absolute value: \" + num);\n", - " System.out.println(\"ArrayList: \" + list);\n", - " }\n", - "}\n", - "\n", - "PackageDemo.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 4. Documentation = Explains Attributes and Behaviors\n", - "\n", - "**API Documentation** is essential for understanding classes.\n", - "\n", - "### What Documentation Shows:\n", - "1. **Constructors** - How to create objects\n", - "2. **Methods** - What the class can do\n", - "3. **Parameters** - What information methods need\n", - "4. **Return types** - What methods give back\n", - "\n", - "### Example: ArrayList Documentation\n", - "\n", - "**Common constructors:**\n", - "- `ArrayList()` - creates empty list\n", - "\n", - "**Common methods:**\n", - "- `add(element)` - adds to end\n", - "- `get(index)` - returns element at position\n", - "- `size()` - returns number of elements\n", - "- `remove(index)` - removes element" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Scores: [95, 87, 92]\n", - "First score: 95\n", - "Total scores: 3\n" - ] - } - ], - "source": [ - "// Using ArrayList based on documentation\n", - "\n", - "import java.util.ArrayList;\n", - "\n", - "public class DocumentationDemo {\n", - " public static void main(String[] args) {\n", - " // Constructor from documentation\n", - " ArrayList<Integer> scores = new ArrayList<>();\n", - " \n", - " // Methods from documentation\n", - " scores.add(95); // add(element)\n", - " scores.add(87);\n", - " scores.add(92);\n", - " \n", - " System.out.println(\"Scores: \" + scores);\n", - " System.out.println(\"First score: \" + scores.get(0)); // get(index)\n", - " System.out.println(\"Total scores: \" + scores.size()); // size()\n", - " }\n", - "}\n", - "\n", - "DocumentationDemo.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 🍿 Popcorn Hack #1: Using Documentation (5 minutes)\n", - "\n", - "**Task:** Use the Math class and ArrayList class based on their documentation.\n", - "\n", - "Complete the following:\n", - "1. Use `Math.pow()` to calculate 3^4\n", - "2. Use `Math.sqrt()` to find square root of 64\n", - "3. Create an ArrayList of Strings\n", - "4. Add 3 colors to the ArrayList\n", - "5. Print the ArrayList size" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// Popcorn Hack #1: Complete this code\n", - "\n", - "import java.util.ArrayList;\n", - "\n", - "public class PopcornHack1 {\n", - " public static void main(String[] args) {\n", - " // TODO: Use Math.pow() to calculate 3^4\n", - " \n", - " // TODO: Use Math.sqrt() to find square root of 64\n", - " \n", - " // TODO: Create ArrayList of Strings\n", - " \n", - " // TODO: Add 3 colors (\"red\", \"blue\", \"green\")\n", - " \n", - " // TODO: Print the size\n", - " \n", - " }\n", - "}\n", - "\n", - "// PopcornHack1.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 5. Attributes = Data (Variables)\n", - "\n", - "**Attributes** are what an object **HAS** (its data/state).\n", - "\n", - "### Key Points:\n", - "- Attributes are variables inside a class\n", - "- They store data about the object\n", - "- Usually declared as `private`\n", - "\n", - "### Example: Student Class\n", - "A Student has:\n", - "- `name` (String)\n", - "- `grade` (int)\n", - "- `gpa` (double)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Name: Alice\n", - "Grade: 11\n", - "GPA: 3.8\n" - ] - } - ], - "source": [ - "// Demonstrating Attributes\n", - "\n", - "public class Student {\n", - " // ATTRIBUTES - what the student HAS\n", - " private String name;\n", - " private int grade;\n", - " private double gpa;\n", - " \n", - " // Constructor to set attributes\n", - " public Student(String name, int grade, double gpa) {\n", - " this.name = name;\n", - " this.grade = grade;\n", - " this.gpa = gpa;\n", - " }\n", - " \n", - " // Method to display attributes\n", - " public void showInfo() {\n", - " System.out.println(\"Name: \" + name);\n", - " System.out.println(\"Grade: \" + grade);\n", - " System.out.println(\"GPA: \" + gpa);\n", - " }\n", - "}\n", - "\n", - "// Create a student object\n", - "Student alice = new Student(\"Alice\", 11, 3.8);\n", - "alice.showInfo();" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 6. Behaviors = Actions (Methods)\n", - "\n", - "**Behaviors** are what an object **DOES** (its actions).\n", - "\n", - "### Key Points:\n", - "- Behaviors are methods inside a class\n", - "- They perform actions or calculations\n", - "- They can modify attributes or return values\n", - "\n", - "### Example: Student Class Behaviors\n", - "A Student can:\n", - "- `displayInfo()` - show student data\n", - "- `updateGPA()` - change GPA\n", - "- `promoteGrade()` - move to next grade\n", - "- `isHonorRoll()` - check if GPA >= 3.5\n", - "\n", - "### Attributes vs. Behaviors Summary:\n", - "\n", - "| Concept | Definition | Example |\n", - "|---------|------------|----------|\n", - "| **Attributes** | What object HAS | name, grade, gpa |\n", - "| **Behaviors** | What object DOES | displayInfo(), updateGPA() |" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Bob - Grade 10 - GPA: 3.6\n", - "Bob's GPA updated to 3.8\n", - "Bob promoted to grade 11\n", - "Honor roll: true\n" - ] - } - ], - "source": [ - "// Demonstrating Behaviors\n", - "\n", - "public class Student {\n", - " // Attributes\n", - " private String name;\n", - " private int grade;\n", - " private double gpa;\n", - " \n", - " public Student(String name, int grade, double gpa) {\n", - " this.name = name;\n", - " this.grade = grade;\n", - " this.gpa = gpa;\n", - " }\n", - " \n", - " // BEHAVIORS - what the student DOES\n", - " \n", - " public void displayInfo() {\n", - " System.out.println(name + \" - Grade \" + grade + \" - GPA: \" + gpa);\n", - " }\n", - " \n", - " public void updateGPA(double newGPA) {\n", - " this.gpa = newGPA;\n", - " System.out.println(name + \"'s GPA updated to \" + gpa);\n", - " }\n", - " \n", - " public void promoteGrade() {\n", - " grade++;\n", - " System.out.println(name + \" promoted to grade \" + grade);\n", - " }\n", - " \n", - " public boolean isHonorRoll() {\n", - " return gpa >= 3.5;\n", - " }\n", - "}\n", - "\n", - "// Testing behaviors\n", - "Student bob = new Student(\"Bob\", 10, 3.6);\n", - "bob.displayInfo();\n", - "bob.updateGPA(3.8);\n", - "bob.promoteGrade();\n", - "System.out.println(\"Honor roll: \" + bob.isHonorRoll());" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 🍿 Popcorn Hack #2: Attributes and Behaviors (5 minutes)\n", - "\n", - "**Task:** Create a `Book` class with attributes and behaviors.\n", - "\n", - "**Requirements:**\n", - "\n", - "**Attributes (3):**\n", - "- `title` (String)\n", - "- `author` (String) \n", - "- `pages` (int)\n", - "\n", - "**Behaviors (3 methods):**\n", - "1. Constructor to set all attributes\n", - "2. `displayInfo()` - print all book info\n", - "3. `isLong()` - return true if pages > 300\n", - "\n", - "**Test:** Create a Book object and call all methods." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// Popcorn Hack #2: Complete the Book class\n", - "\n", - "public class Book {\n", - " // TODO: Add 3 attributes (title, author, pages)\n", - " \n", - " // TODO: Add constructor\n", - " \n", - " // TODO: Add displayInfo() method\n", - " \n", - " // TODO: Add isLong() method (returns true if pages > 300)\n", - " \n", - "}\n", - "\n", - "// TODO: Create a Book object and test all methods\n", - "// Example: Book myBook = new Book(\"Java Basics\", \"John Doe\", 350);\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## Summary: College Board Essentials\n", - "\n", - "### 1.7.A.1 - Libraries and APIs\n", - "✅ **Libraries** = collections of classes you can use \n", - "✅ **API** = tells you how to use those classes \n", - "✅ **Packages** = organize classes into groups \n", - "✅ **Documentation** = explains attributes and behaviors\n", - "\n", - "### 1.7.A.2 - Attributes vs. Behaviors\n", - "✅ **Attributes** = data (variables) - what object HAS \n", - "✅ **Behaviors** = actions (methods) - what object DOES\n", - "\n", - "### Key Reminders:\n", - "- `java.lang` classes don't need imports (String, Math, Integer)\n", - "- Other packages need `import` statements (ArrayList, Scanner, Random)\n", - "- Always check API documentation when using new classes\n", - "- Use existing library classes instead of writing code from scratch!\n", - "\n", - "---\n", - "\n", - "## Resources\n", - "- [Java API Documentation](https://docs.oracle.com/en/java/javase/11/docs/api/index.html)\n", - "- [AP CSA Course Description](https://apcentral.collegeboard.org/courses/ap-computer-science-a)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "11.0.12" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.8-documentation-with-comments.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.8-documentation-with-comments.ipynb deleted file mode 100644 index 0f7b155b4b..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.8-documentation-with-comments.ipynb +++ /dev/null @@ -1,797 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "d886c8cb", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Documentation-and-Comments]\n", - "lesson_language: Java\n", - "lesson_topic: Documentation-and-Comments\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Documentation with Comments\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_8\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "e2d94e01", - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "source": [ - "# CSA Unit 1.8: Documentation with Comments\\n\",\n", - "\n", - "## Lesson Plan\n", - "\n", - "**Learning Objectives:**\n", - "- Understand the purpose and importance of code documentation\n", - "- Master Javadoc comment syntax and structure\n", - "- Learn to write effective preconditions and postconditions\n", - "- Apply documentation best practices to classes and methods\n", - "\n", - "\n", - "**AP Exam Focus:** Required for FRQ responses, demonstrates professional programming practices\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "c3ad035b", - "metadata": {}, - "source": [ - "We need 2 volunteers to come up to play a game!" - ] - }, - { - "cell_type": "markdown", - "id": "be88be74", - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "source": [ - "## Part 1: Why Documentation Matters\n", - "\n", - "Documentation serves multiple audiences:\n", - "- **Other developers:** How do I use this method? What parameters does it expect?\n", - "- **Maintainers:** Why was this implemented this way? What are the edge cases?\n", - "- **Testers:** What should this method do in different scenarios?\n", - "- **Your future self:** Will you remember your logic in 3 months?\n", - "\n", - "**Think of documentation as the user manual for your code.**\n", - "\n", - "### Types of Java Comments:\n", - "1. **Single-line comments:** `//` - Quick notes and explanations\n", - "2. **Multi-line comments:** `/* */` - Longer explanations\n", - "3. **Javadoc comments:** `/** */` - API documentation (our focus today!)\n", - "\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "697c0a1a", - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "source": [ - "## Part 2: Javadoc Comment Structure\n", - "\n", - "Javadoc uses special tags to create comprehensive documentation:\n", - "- `@param` - Describes a parameter\n", - "- `@return` - Describes the return value\n", - "- `@throws` - Describes exceptions that might be thrown\n", - "\n", - "**Basic Template:**\n", - "```java\n", - "/**\n", - " * Brief description of what the method does.\n", - " * \n", - " * More detailed explanation if needed, including algorithm\n", - " * information, usage notes, or important behaviors.\n", - " *\n", - " * @param paramName description of the parameter\n", - " * @return description of what is returned\n", - " */\n", - "```\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ac434458", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Final Grade: 89.1\n" - ] - } - ], - "source": [ - "/**\n", - " * Calculates the final grade for a student based on weighted categories.\n", - " * The grade is computed using the formula: \n", - " * (homework * 0.3) + (tests * 0.5) + (participation * 0.2)\n", - " *\n", - " * @param homework the average homework score (0.0 to 100.0)\n", - " * @param tests the average test score (0.0 to 100.0) \n", - " * @param participation the participation score (0.0 to 100.0)\n", - " * @return the weighted final grade as a percentage (0.0 to 100.0)\n", - " */\n", - "public double calculateFinalGrade(double homework, double tests, double participation) {\n", - " return homework * 0.3 + tests * 0.5 + participation * 0.2;\n", - "}\n", - "\n", - "// Test the method\n", - "System.out.println(\"Final Grade: \" + calculateFinalGrade(85.0, 92.0, 88.0));" - ] - }, - { - "cell_type": "markdown", - "id": "f8048d2a", - "metadata": {}, - "source": [ - "## Part 3: Preconditions and Postconditions\n", - "\n", - "**Preconditions:** What must be true BEFORE the method is called\n", - "**Postconditions:** What will be true AFTER the method completes successfully\n", - "\n", - "These create a **contract** between the method and its callers.\n", - "\n", - "### Why They Matter:\n", - "- Clarify responsibilities\n", - "- Define expected behavior\n", - "- Help identify bugs\n", - "- Essential for AP FRQs!\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "7486d57e", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Transaction: Withdraw $100.0\n", - "New balance: $400.0\n" - ] - }, - { - "data": { - "text/plain": [ - "true" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "/**\n", - " * Withdraws money from the bank account.\n", - " * \n", - " * Preconditions: \n", - " * - amount must be positive\n", - " * - amount must not exceed current balance\n", - " * - account must not be frozen\n", - " * \n", - " * Postconditions:\n", - " * - balance is reduced by the withdrawal amount\n", - " * - transaction is recorded in account history\n", - " * - returns true if withdrawal successful\n", - " *\n", - " * @param amount the amount to withdraw (must be positive)\n", - " * @return true if withdrawal successful, false otherwise\n", - " */\n", - "\n", - "public boolean withdraw(double amount) {\n", - " // Local variable definitions\n", - " double balance = 500.0; // example current balance\n", - " boolean isFrozen = false; // example account state\n", - "\n", - " // Preconditions: amount must be positive, not exceed balance, and account not frozen\n", - " if (amount <= 0 || amount > balance || isFrozen) {\n", - " return false; // Precondition not met\n", - " }\n", - "\n", - " // Perform withdrawal\n", - " balance -= amount;\n", - "\n", - " // Record transaction (for now, just print it)\n", - " System.out.println(\"Transaction: Withdraw $\" + amount);\n", - " System.out.println(\"New balance: $\" + balance);\n", - "\n", - " // Postcondition: balance reduced, transaction recorded\n", - " return true;\n", - "}\n", - "withdraw(100.0);" - ] - }, - { - "cell_type": "markdown", - "id": "c7069af2", - "metadata": {}, - "source": [ - "## Part 4: Class-Level Documentation\n", - "\n", - "Classes need documentation explaining their overall purpose and usage.\n", - "\n", - "**Key Elements:**\n", - "- Overall purpose of the class\n", - "- Key responsibilities\n", - "- Usage examples\n", - "- Important design decisions\n", - "- Author and version information\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "a0d8c9d2", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "95.5\n" - ] - } - ], - "source": [ - "/**\n", - " * Represents a student in the school management system.\n", - " * \n", - " * This class maintains student information including personal details,\n", - " * academic records, and enrollment status. It provides methods for\n", - " * updating grades, managing course enrollment, and generating reports.\n", - " * \n", - " * Example usage:\n", - " * <pre>\n", - " * Student alice = new Student(\"Alice Johnson\", 12);\n", - " * alice.enrollInCourse(\"AP Computer Science\");\n", - " * alice.updateGrade(\"Math\", 95.5);\n", - " * System.out.println(alice.getGPA());\n", - " * </pre>\n", - " *\n", - " * @author Your Name\n", - " * @version 1.0\n", - " * @since 2024-01-15\n", - " */\n", - "public class Student {\n", - " private String name;\n", - " private int gradeLevel;\n", - " private ArrayList<String> courses;\n", - " private HashMap<String, Double> grades;\n", - " \n", - " // Constructor fix\n", - " public Student(String name, int gradeLevel) {\n", - " this.name = name;\n", - " this.gradeLevel = gradeLevel;\n", - " this.courses = new ArrayList<>();\n", - " this.grades = new HashMap<>();\n", - " }\n", - "\n", - " // Example methods\n", - " public void enrollInCourse(String course) {\n", - " courses.add(course);\n", - " }\n", - "\n", - " public void updateGrade(String course, double grade) {\n", - " grades.put(course, grade);\n", - " }\n", - "\n", - " public double getGPA() {\n", - " if (grades.isEmpty()) return 0.0;\n", - " double sum = 0;\n", - " for (double g : grades.values()) {\n", - " sum += g;\n", - " }\n", - " return sum / grades.size();\n", - " }\n", - "}\n", - "// Test the Student class\n", - "Student alice = new Student(\"Alice Johnson\", 12);\n", - "alice.enrollInCourse(\"AP Computer Science\");\n", - "alice.updateGrade(\"Math\", 95.5);\n", - "System.out.println(alice.getGPA());" - ] - }, - { - "cell_type": "markdown", - "id": "bdab0599", - "metadata": {}, - "source": [ - "## Part 5: Documentation Best Practices\n", - "\n", - "### DO:\n", - "1. **Be specific and actionable** - \"sets the student's GPA to the specified value, rounded to one decimal place\"\n", - "2. **Include examples for complex methods**\n", - "3. **Document assumptions and limitations**\n", - "4. **Update docs when code changes**\n", - "5. **Focus on WHY, not just WHAT**\n", - "\n", - "### DON'T:\n", - "1. **Over-document obvious code** - Simple getters/setters don't need documentation\n", - "2. **Use vague descriptions** - \"processes the data\" tells us nothing\n", - "3. **Forget edge cases** - What happens with null? Empty arrays?\n", - "4. **Let documentation become outdated**\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "9de83950", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "ename": "CompilationException", - "evalue": "", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41mthis\u001b[0m\u001b[1m\u001b[30m.name = normalizeName(name.trim());\u001b[0m", - "\u001b[1m\u001b[31mnon-static variable this cannot be referenced from a static context\u001b[0m", - "", - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41mthis.name\u001b[0m\u001b[1m\u001b[30m = normalizeName(name.trim());\u001b[0m", - "\u001b[1m\u001b[31mcannot find symbol\u001b[0m", - "\u001b[1m\u001b[31m symbol: variable name\u001b[0m", - "", - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m this.name = \u001b[0m\u001b[1m\u001b[30m\u001b[41mnormalizeName\u001b[0m\u001b[1m\u001b[30m(name.trim());\u001b[0m", - "\u001b[1m\u001b[31mcannot find symbol\u001b[0m", - "\u001b[1m\u001b[31m symbol: method normalizeName(java.lang.String)\u001b[0m", - "" - ] - } - ], - "source": [ - "// BAD: Over-documentation of obvious code\n", - "/**\n", - " * Gets the name.\n", - " * @return the name\n", - " */\n", - "public String getName() {\n", - " return name;\n", - "}\n", - "\n", - "// GOOD: No documentation needed for simple accessor\n", - "public String getName() { \n", - " return name; \n", - "}\n", - "\n", - "// GOOD: Document complex behavior\n", - "/**\n", - " * Updates the student's name with validation and normalization.\n", - " * \n", - " * Trims whitespace, converts to proper case, and validates that\n", - " * the name contains only letters, spaces, hyphens, and apostrophes.\n", - " *\n", - " * @param name the new name (will be normalized)\n", - " * @throws IllegalArgumentException if name is null, empty, or contains invalid characters\n", - " */\n", - "public void setNameWithValidation(String name) {\n", - " if (name == null || name.trim().isEmpty()) {\n", - " throw new IllegalArgumentException(\"Name cannot be null or empty\");\n", - " }\n", - " this.name = normalizeName(name.trim());\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "b364f26d", - "metadata": {}, - "source": [ - "## Part 6: AP Exam Connections\n", - "\n", - "### Multiple Choice Tips:\n", - "- Know the difference between `//`, `/* */`, and `/** */`\n", - "- Understand when documentation is most helpful\n", - "- Recognize proper @param and @return usage\n", - "\n", - "### FRQ Requirements:\n", - "- **Always document complex methods** - Shows programming maturity\n", - "- **Explain your logic** - Helps scorers understand your intent\n", - "- **Document non-obvious design decisions**\n", - "- **Specify parameter constraints**\n", - "\n", - "### Quick Documentation Checklist:\n", - "- ✓ Complex methods have clear purpose descriptions\n", - "- ✓ Parameter constraints are specified\n", - "- ✓ Return values are explained\n", - "- ✓ Edge cases and error conditions are documented\n", - "- ✓ Examples provided for non-obvious usage\n", - "\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "2b44f1d1", - "metadata": {}, - "source": [ - "## Lesson Hack #1: Fix the Documentation\n", - "\n", - "**Task:** The following code has poor documentation. Rewrite it with proper Javadoc comments including preconditions and postconditions.\n", - "\n", - "```java\n", - "// Does stuff with numbers\n", - "public int doSomething(int[] nums) {\n", - " int result = 0;\n", - " for (int i = 0; i < nums.length; i++) {\n", - " if (nums[i] > 0 && nums[i] % 2 == 0) {\n", - " result += nums[i];\n", - " }\n", - " }\n", - " return result;\n", - "}\n", - "```\n", - "\n", - "**Your task:** Write proper Javadoc documentation for this method in the code cell below.\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "347c940e", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "/**\n", - " * Calculates the sum of all positive even integers in the given array.\n", - " * <p>\n", - " * This method loops through each element of {@code nums} and adds it to a running total\n", - " * only if the element is greater than zero and evenly divisible by two.\n", - " * The method then returns the resulting sum.\n", - " * </p>\n", - " *\n", - " * <p><b>Preconditions:</b></p>\n", - " * <ul>\n", - " * <li>{@code nums} must not be {@code null}.</li>\n", - " * <li>{@code nums} may contain any integers (positive, negative, or zero).</li>\n", - " * </ul>\n", - " *\n", - " * <p><b>Postconditions:</b></p>\n", - " * <ul>\n", - " * <li>Returns the sum of all positive even numbers in {@code nums}.</li>\n", - " * <li>If there are no positive even numbers, returns {@code 0}.</li>\n", - " * </ul>\n", - " *\n", - " * @param nums an array of integers to evaluate\n", - " * @return the sum of all positive even integers in {@code nums}; {@code 0} if none exist\n", - " *\n", - " * <p><b>Example usage:</b></p>\n", - " * <pre>\n", - " * int[] numbers = {1, 2, 3, 4, -6};\n", - " * int result = doSomething(numbers); // result = 6\n", - " * </pre>\n", - " */\n", - "public int doSomething(int[] nums) {\n", - " int result = 0;\n", - " for (int i = 0; i < nums.length; i++) {\n", - " if (nums[i] > 0 && nums[i] % 2 == 0) {\n", - " result += nums[i];\n", - " }\n", - " }\n", - " return result;\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "84ece20e", - "metadata": {}, - "source": [ - "## Popcorn Hack #2: Write Class Documentation\n", - "\n", - "**Your Mission:** Add Javadoc comments to document this GradeBook class!\n", - "\n", - "**What to include:**\n", - "- What does this class do? (purpose)\n", - "- What are the main features? (key methods)\n", - "- How would someone use it? (example)\n", - "- Tags: @author, @version, @since\n", - "```java\n", - "// TODO: Add your class-level Javadoc here!\n", - "// Hint: Start with /** and end with */\n", - "\n", - "public class GradeBook {\n", - " private HashMap<String, Double> assignments;\n", - " private HashMap<String, Double> categoryWeights;\n", - " private double extraCredit;\n", - " \n", - " // TODO: Document each method too!\n", - " public void addAssignment(String category, String name, double score) { }\n", - " \n", - " public void setCategoryWeight(String category, double weight) { }\n", - " \n", - " public double calculateFinalGrade() { }\n", - " \n", - " public String generateReport() { }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "2e24f3b5", - "metadata": {}, - "source": [ - "Check your answer below!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2358b2f5", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "/**\n", - " * Manages student grades and calculates final grades based on weighted categories.\n", - " * \n", - " * This class allows teachers to track assignments across different categories\n", - " * (like homework, tests, projects) and calculate final grades using custom weights.\n", - " * \n", - " * Key Features:\n", - " * - Store assignments by category\n", - " * - Apply custom weights to each category\n", - " * - Track extra credit points\n", - " * - Generate grade reports\n", - " * \n", - " * Usage Example:\n", - " * GradeBook myGrades = new GradeBook();\n", - " * myGrades.setCategoryWeight(\"Homework\", 0.30);\n", - " * myGrades.setCategoryWeight(\"Tests\", 0.70);\n", - " * myGrades.addAssignment(\"Homework\", \"HW1\", 95.0);\n", - " * double finalGrade = myGrades.calculateFinalGrade();\n", - " * \n", - " * @author Your Name\n", - " * @version 1.0\n", - " * @since 2025-10-06\n", - " */\n", - "public class GradeBook {\n", - " private HashMap<String, Double> assignments;\n", - " private HashMap<String, Double> categoryWeights;\n", - " private double extraCredit;\n", - " \n", - " /**\n", - " * Adds an assignment score to a specific category.\n", - " * \n", - " * @param category the category name (e.g., \"Homework\", \"Tests\")\n", - " * @param name the assignment name\n", - " * @param score the score earned (0-100)\n", - " */\n", - " public void addAssignment(String category, String name, double score) { }\n", - " \n", - " /**\n", - " * Sets the weight for a grade category.\n", - " * \n", - " * @param category the category name\n", - " * @param weight the weight as a decimal (e.g., 0.30 for 30%)\n", - " */\n", - " public void setCategoryWeight(String category, double weight) { }\n", - " \n", - " /**\n", - " * Calculates the final weighted grade including extra credit.\n", - " * \n", - " * @return the final grade as a percentage\n", - " */\n", - " public double calculateFinalGrade() { }\n", - " \n", - " /**\n", - " * Generates a formatted report of all grades and categories.\n", - " * \n", - " * @return a String containing the grade report\n", - " */\n", - " public String generateReport() { }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "9461cca7", - "metadata": {}, - "source": [ - "## Homework Assignment\n", - "\n", - "### Part 1: Documentation Analysis \n", - "Submission: https://docs.google.com/forms/d/e/1FAIpQLSepOCmW6KeE7jw4f80JO4Kad5YWeDUHKTpnNxnCPTtj9WEAsw/viewform?usp=header \n", - "Rewrite the poorly written code. Write them with proper Javadoc comments.\n", - "1. The original code:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ef9efa33", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "/*\n", - "public class stuff{\n", - "public static void main(String args[]){\n", - "int x=5;\n", - "int y=10;\n", - "int z=add(x,y);\n", - "System.out.println(\"ans is \"+z);\n", - "}\n", - "\n", - "static int add(int a,int b){\n", - "return a+b;\n", - "}\n", - "}\n", - " */" - ] - }, - { - "cell_type": "markdown", - "id": "cace0026", - "metadata": {}, - "source": [ - "\n", - "Submit:\n", - "\n", - "2. Your improved version\n", - "3. A brief explanation of what you improved\n", - "\n", - "### Part 2: \n", - "Problem 1: Document a Complex Method\n", - "Write complete Javadoc documentation for this method:\n", - "\n", - "public boolean enrollStudent(String studentId, String courseCode, int semester) {\n", - " Student student = findStudentById(studentId);\n", - " if (student == null) return false;\n", - "\n", - " Course course = findCourseByCode(courseCode);\n", - " if (course == null) return false;\n", - "\n", - " if (course.isFull()) return false;\n", - " if (student.hasScheduleConflict(course)) return false;\n", - " if (!student.hasPrerequisites(course)) return false;\n", - " if (student.getCreditHours() + course.getCreditHours() > 18) return false;\n", - "\n", - " student.addCourse(course);\n", - " course.addStudent(student);\n", - " recordEnrollmentTransaction(studentId, courseCode, semester);\n", - " return true;\n", - "}\n", - "\n", - "\n", - "### Part 3: Reflection Questions \n", - "1. Why is documentation more important in team projects than solo projects?\n", - "2. Give an example of when a method SHOULD be documented and when it SHOULD NOT.\n", - "\n", - "**Submit:** A Jupyter notebook or Java file with all three parts completed.\n", - "\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "1b063ed3", - "metadata": {}, - "source": [ - "## Key Takeaways\n", - "\n", - "1. **Documentation is communication** - Write for others (and your future self)\n", - "2. **Javadoc format matters** - Use `/** */` with proper tags\n", - "3. **Preconditions and postconditions create contracts** - Essential for reliable code\n", - "4. **Balance is key** - Don't over-document obvious code, but thoroughly document complex logic\n", - "5. **Keep it updated** - Outdated documentation is worse than no documentation\n", - "6. **AP Exam success** - Good documentation demonstrates programming maturity on FRQs\n", - "\n", - "### Remember:\n", - "> \"Code tells you HOW, documentation tells you WHY\"\n", - "\n", - "**The collaborative mindset:** Write documentation that you would want to find when using someone else's code. Be specific, be helpful, and anticipate questions.\n", - "\n", - "---\n", - "\n", - "## Additional Resources\n", - "- [Oracle Java Documentation Guidelines](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html)\n", - "- [AP Computer Science A Course Description](https://apcentral.collegeboard.org/)\n", - "- Practice writing documentation for existing code projects!" - ] - }, - { - "cell_type": "markdown", - "id": "11f14ac0", - "metadata": {}, - "source": [ - "## Challenge Problems (Extra Credit)\n", - "\n", - "### Challenge 1: Document a Recursive Method\n", - "Write complete documentation for a recursive method including base case, recursive case, and complexity analysis.\n", - "\n", - "### Challenge 2: Team Documentation Standard\n", - "Create a documentation style guide for a team project. Include:\n", - "- When to document (and when not to)\n", - "- Required tags for different method types\n", - "- Example templates\n", - "- Common mistakes to avoid\n", - "\n", - "### Challenge 3: Documentation Detective\n", - "Find a poorly documented open-source project. Write improved documentation for one class and submit a comparison showing before/after.\n", - "\n", - "---" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "17.0.16+8-Ubuntu-0ubuntu122.04.1" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.8.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.8.ipynb deleted file mode 100644 index 0f7b155b4b..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.8.ipynb +++ /dev/null @@ -1,797 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "d886c8cb", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Documentation-and-Comments]\n", - "lesson_language: Java\n", - "lesson_topic: Documentation-and-Comments\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Documentation with Comments\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_8\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "e2d94e01", - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "source": [ - "# CSA Unit 1.8: Documentation with Comments\\n\",\n", - "\n", - "## Lesson Plan\n", - "\n", - "**Learning Objectives:**\n", - "- Understand the purpose and importance of code documentation\n", - "- Master Javadoc comment syntax and structure\n", - "- Learn to write effective preconditions and postconditions\n", - "- Apply documentation best practices to classes and methods\n", - "\n", - "\n", - "**AP Exam Focus:** Required for FRQ responses, demonstrates professional programming practices\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "c3ad035b", - "metadata": {}, - "source": [ - "We need 2 volunteers to come up to play a game!" - ] - }, - { - "cell_type": "markdown", - "id": "be88be74", - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "source": [ - "## Part 1: Why Documentation Matters\n", - "\n", - "Documentation serves multiple audiences:\n", - "- **Other developers:** How do I use this method? What parameters does it expect?\n", - "- **Maintainers:** Why was this implemented this way? What are the edge cases?\n", - "- **Testers:** What should this method do in different scenarios?\n", - "- **Your future self:** Will you remember your logic in 3 months?\n", - "\n", - "**Think of documentation as the user manual for your code.**\n", - "\n", - "### Types of Java Comments:\n", - "1. **Single-line comments:** `//` - Quick notes and explanations\n", - "2. **Multi-line comments:** `/* */` - Longer explanations\n", - "3. **Javadoc comments:** `/** */` - API documentation (our focus today!)\n", - "\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "697c0a1a", - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "source": [ - "## Part 2: Javadoc Comment Structure\n", - "\n", - "Javadoc uses special tags to create comprehensive documentation:\n", - "- `@param` - Describes a parameter\n", - "- `@return` - Describes the return value\n", - "- `@throws` - Describes exceptions that might be thrown\n", - "\n", - "**Basic Template:**\n", - "```java\n", - "/**\n", - " * Brief description of what the method does.\n", - " * \n", - " * More detailed explanation if needed, including algorithm\n", - " * information, usage notes, or important behaviors.\n", - " *\n", - " * @param paramName description of the parameter\n", - " * @return description of what is returned\n", - " */\n", - "```\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ac434458", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Final Grade: 89.1\n" - ] - } - ], - "source": [ - "/**\n", - " * Calculates the final grade for a student based on weighted categories.\n", - " * The grade is computed using the formula: \n", - " * (homework * 0.3) + (tests * 0.5) + (participation * 0.2)\n", - " *\n", - " * @param homework the average homework score (0.0 to 100.0)\n", - " * @param tests the average test score (0.0 to 100.0) \n", - " * @param participation the participation score (0.0 to 100.0)\n", - " * @return the weighted final grade as a percentage (0.0 to 100.0)\n", - " */\n", - "public double calculateFinalGrade(double homework, double tests, double participation) {\n", - " return homework * 0.3 + tests * 0.5 + participation * 0.2;\n", - "}\n", - "\n", - "// Test the method\n", - "System.out.println(\"Final Grade: \" + calculateFinalGrade(85.0, 92.0, 88.0));" - ] - }, - { - "cell_type": "markdown", - "id": "f8048d2a", - "metadata": {}, - "source": [ - "## Part 3: Preconditions and Postconditions\n", - "\n", - "**Preconditions:** What must be true BEFORE the method is called\n", - "**Postconditions:** What will be true AFTER the method completes successfully\n", - "\n", - "These create a **contract** between the method and its callers.\n", - "\n", - "### Why They Matter:\n", - "- Clarify responsibilities\n", - "- Define expected behavior\n", - "- Help identify bugs\n", - "- Essential for AP FRQs!\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "7486d57e", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Transaction: Withdraw $100.0\n", - "New balance: $400.0\n" - ] - }, - { - "data": { - "text/plain": [ - "true" - ] - }, - "execution_count": 8, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "/**\n", - " * Withdraws money from the bank account.\n", - " * \n", - " * Preconditions: \n", - " * - amount must be positive\n", - " * - amount must not exceed current balance\n", - " * - account must not be frozen\n", - " * \n", - " * Postconditions:\n", - " * - balance is reduced by the withdrawal amount\n", - " * - transaction is recorded in account history\n", - " * - returns true if withdrawal successful\n", - " *\n", - " * @param amount the amount to withdraw (must be positive)\n", - " * @return true if withdrawal successful, false otherwise\n", - " */\n", - "\n", - "public boolean withdraw(double amount) {\n", - " // Local variable definitions\n", - " double balance = 500.0; // example current balance\n", - " boolean isFrozen = false; // example account state\n", - "\n", - " // Preconditions: amount must be positive, not exceed balance, and account not frozen\n", - " if (amount <= 0 || amount > balance || isFrozen) {\n", - " return false; // Precondition not met\n", - " }\n", - "\n", - " // Perform withdrawal\n", - " balance -= amount;\n", - "\n", - " // Record transaction (for now, just print it)\n", - " System.out.println(\"Transaction: Withdraw $\" + amount);\n", - " System.out.println(\"New balance: $\" + balance);\n", - "\n", - " // Postcondition: balance reduced, transaction recorded\n", - " return true;\n", - "}\n", - "withdraw(100.0);" - ] - }, - { - "cell_type": "markdown", - "id": "c7069af2", - "metadata": {}, - "source": [ - "## Part 4: Class-Level Documentation\n", - "\n", - "Classes need documentation explaining their overall purpose and usage.\n", - "\n", - "**Key Elements:**\n", - "- Overall purpose of the class\n", - "- Key responsibilities\n", - "- Usage examples\n", - "- Important design decisions\n", - "- Author and version information\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "a0d8c9d2", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "95.5\n" - ] - } - ], - "source": [ - "/**\n", - " * Represents a student in the school management system.\n", - " * \n", - " * This class maintains student information including personal details,\n", - " * academic records, and enrollment status. It provides methods for\n", - " * updating grades, managing course enrollment, and generating reports.\n", - " * \n", - " * Example usage:\n", - " * <pre>\n", - " * Student alice = new Student(\"Alice Johnson\", 12);\n", - " * alice.enrollInCourse(\"AP Computer Science\");\n", - " * alice.updateGrade(\"Math\", 95.5);\n", - " * System.out.println(alice.getGPA());\n", - " * </pre>\n", - " *\n", - " * @author Your Name\n", - " * @version 1.0\n", - " * @since 2024-01-15\n", - " */\n", - "public class Student {\n", - " private String name;\n", - " private int gradeLevel;\n", - " private ArrayList<String> courses;\n", - " private HashMap<String, Double> grades;\n", - " \n", - " // Constructor fix\n", - " public Student(String name, int gradeLevel) {\n", - " this.name = name;\n", - " this.gradeLevel = gradeLevel;\n", - " this.courses = new ArrayList<>();\n", - " this.grades = new HashMap<>();\n", - " }\n", - "\n", - " // Example methods\n", - " public void enrollInCourse(String course) {\n", - " courses.add(course);\n", - " }\n", - "\n", - " public void updateGrade(String course, double grade) {\n", - " grades.put(course, grade);\n", - " }\n", - "\n", - " public double getGPA() {\n", - " if (grades.isEmpty()) return 0.0;\n", - " double sum = 0;\n", - " for (double g : grades.values()) {\n", - " sum += g;\n", - " }\n", - " return sum / grades.size();\n", - " }\n", - "}\n", - "// Test the Student class\n", - "Student alice = new Student(\"Alice Johnson\", 12);\n", - "alice.enrollInCourse(\"AP Computer Science\");\n", - "alice.updateGrade(\"Math\", 95.5);\n", - "System.out.println(alice.getGPA());" - ] - }, - { - "cell_type": "markdown", - "id": "bdab0599", - "metadata": {}, - "source": [ - "## Part 5: Documentation Best Practices\n", - "\n", - "### DO:\n", - "1. **Be specific and actionable** - \"sets the student's GPA to the specified value, rounded to one decimal place\"\n", - "2. **Include examples for complex methods**\n", - "3. **Document assumptions and limitations**\n", - "4. **Update docs when code changes**\n", - "5. **Focus on WHY, not just WHAT**\n", - "\n", - "### DON'T:\n", - "1. **Over-document obvious code** - Simple getters/setters don't need documentation\n", - "2. **Use vague descriptions** - \"processes the data\" tells us nothing\n", - "3. **Forget edge cases** - What happens with null? Empty arrays?\n", - "4. **Let documentation become outdated**\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "9de83950", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "ename": "CompilationException", - "evalue": "", - "output_type": "error", - "traceback": [ - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41mthis\u001b[0m\u001b[1m\u001b[30m.name = normalizeName(name.trim());\u001b[0m", - "\u001b[1m\u001b[31mnon-static variable this cannot be referenced from a static context\u001b[0m", - "", - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m \u001b[0m\u001b[1m\u001b[30m\u001b[41mthis.name\u001b[0m\u001b[1m\u001b[30m = normalizeName(name.trim());\u001b[0m", - "\u001b[1m\u001b[31mcannot find symbol\u001b[0m", - "\u001b[1m\u001b[31m symbol: variable name\u001b[0m", - "", - "\u001b[1m\u001b[30m| \u001b[1m\u001b[30m this.name = \u001b[0m\u001b[1m\u001b[30m\u001b[41mnormalizeName\u001b[0m\u001b[1m\u001b[30m(name.trim());\u001b[0m", - "\u001b[1m\u001b[31mcannot find symbol\u001b[0m", - "\u001b[1m\u001b[31m symbol: method normalizeName(java.lang.String)\u001b[0m", - "" - ] - } - ], - "source": [ - "// BAD: Over-documentation of obvious code\n", - "/**\n", - " * Gets the name.\n", - " * @return the name\n", - " */\n", - "public String getName() {\n", - " return name;\n", - "}\n", - "\n", - "// GOOD: No documentation needed for simple accessor\n", - "public String getName() { \n", - " return name; \n", - "}\n", - "\n", - "// GOOD: Document complex behavior\n", - "/**\n", - " * Updates the student's name with validation and normalization.\n", - " * \n", - " * Trims whitespace, converts to proper case, and validates that\n", - " * the name contains only letters, spaces, hyphens, and apostrophes.\n", - " *\n", - " * @param name the new name (will be normalized)\n", - " * @throws IllegalArgumentException if name is null, empty, or contains invalid characters\n", - " */\n", - "public void setNameWithValidation(String name) {\n", - " if (name == null || name.trim().isEmpty()) {\n", - " throw new IllegalArgumentException(\"Name cannot be null or empty\");\n", - " }\n", - " this.name = normalizeName(name.trim());\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "b364f26d", - "metadata": {}, - "source": [ - "## Part 6: AP Exam Connections\n", - "\n", - "### Multiple Choice Tips:\n", - "- Know the difference between `//`, `/* */`, and `/** */`\n", - "- Understand when documentation is most helpful\n", - "- Recognize proper @param and @return usage\n", - "\n", - "### FRQ Requirements:\n", - "- **Always document complex methods** - Shows programming maturity\n", - "- **Explain your logic** - Helps scorers understand your intent\n", - "- **Document non-obvious design decisions**\n", - "- **Specify parameter constraints**\n", - "\n", - "### Quick Documentation Checklist:\n", - "- ✓ Complex methods have clear purpose descriptions\n", - "- ✓ Parameter constraints are specified\n", - "- ✓ Return values are explained\n", - "- ✓ Edge cases and error conditions are documented\n", - "- ✓ Examples provided for non-obvious usage\n", - "\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "2b44f1d1", - "metadata": {}, - "source": [ - "## Lesson Hack #1: Fix the Documentation\n", - "\n", - "**Task:** The following code has poor documentation. Rewrite it with proper Javadoc comments including preconditions and postconditions.\n", - "\n", - "```java\n", - "// Does stuff with numbers\n", - "public int doSomething(int[] nums) {\n", - " int result = 0;\n", - " for (int i = 0; i < nums.length; i++) {\n", - " if (nums[i] > 0 && nums[i] % 2 == 0) {\n", - " result += nums[i];\n", - " }\n", - " }\n", - " return result;\n", - "}\n", - "```\n", - "\n", - "**Your task:** Write proper Javadoc documentation for this method in the code cell below.\n", - "\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "347c940e", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "/**\n", - " * Calculates the sum of all positive even integers in the given array.\n", - " * <p>\n", - " * This method loops through each element of {@code nums} and adds it to a running total\n", - " * only if the element is greater than zero and evenly divisible by two.\n", - " * The method then returns the resulting sum.\n", - " * </p>\n", - " *\n", - " * <p><b>Preconditions:</b></p>\n", - " * <ul>\n", - " * <li>{@code nums} must not be {@code null}.</li>\n", - " * <li>{@code nums} may contain any integers (positive, negative, or zero).</li>\n", - " * </ul>\n", - " *\n", - " * <p><b>Postconditions:</b></p>\n", - " * <ul>\n", - " * <li>Returns the sum of all positive even numbers in {@code nums}.</li>\n", - " * <li>If there are no positive even numbers, returns {@code 0}.</li>\n", - " * </ul>\n", - " *\n", - " * @param nums an array of integers to evaluate\n", - " * @return the sum of all positive even integers in {@code nums}; {@code 0} if none exist\n", - " *\n", - " * <p><b>Example usage:</b></p>\n", - " * <pre>\n", - " * int[] numbers = {1, 2, 3, 4, -6};\n", - " * int result = doSomething(numbers); // result = 6\n", - " * </pre>\n", - " */\n", - "public int doSomething(int[] nums) {\n", - " int result = 0;\n", - " for (int i = 0; i < nums.length; i++) {\n", - " if (nums[i] > 0 && nums[i] % 2 == 0) {\n", - " result += nums[i];\n", - " }\n", - " }\n", - " return result;\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "84ece20e", - "metadata": {}, - "source": [ - "## Popcorn Hack #2: Write Class Documentation\n", - "\n", - "**Your Mission:** Add Javadoc comments to document this GradeBook class!\n", - "\n", - "**What to include:**\n", - "- What does this class do? (purpose)\n", - "- What are the main features? (key methods)\n", - "- How would someone use it? (example)\n", - "- Tags: @author, @version, @since\n", - "```java\n", - "// TODO: Add your class-level Javadoc here!\n", - "// Hint: Start with /** and end with */\n", - "\n", - "public class GradeBook {\n", - " private HashMap<String, Double> assignments;\n", - " private HashMap<String, Double> categoryWeights;\n", - " private double extraCredit;\n", - " \n", - " // TODO: Document each method too!\n", - " public void addAssignment(String category, String name, double score) { }\n", - " \n", - " public void setCategoryWeight(String category, double weight) { }\n", - " \n", - " public double calculateFinalGrade() { }\n", - " \n", - " public String generateReport() { }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "2e24f3b5", - "metadata": {}, - "source": [ - "Check your answer below!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2358b2f5", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "/**\n", - " * Manages student grades and calculates final grades based on weighted categories.\n", - " * \n", - " * This class allows teachers to track assignments across different categories\n", - " * (like homework, tests, projects) and calculate final grades using custom weights.\n", - " * \n", - " * Key Features:\n", - " * - Store assignments by category\n", - " * - Apply custom weights to each category\n", - " * - Track extra credit points\n", - " * - Generate grade reports\n", - " * \n", - " * Usage Example:\n", - " * GradeBook myGrades = new GradeBook();\n", - " * myGrades.setCategoryWeight(\"Homework\", 0.30);\n", - " * myGrades.setCategoryWeight(\"Tests\", 0.70);\n", - " * myGrades.addAssignment(\"Homework\", \"HW1\", 95.0);\n", - " * double finalGrade = myGrades.calculateFinalGrade();\n", - " * \n", - " * @author Your Name\n", - " * @version 1.0\n", - " * @since 2025-10-06\n", - " */\n", - "public class GradeBook {\n", - " private HashMap<String, Double> assignments;\n", - " private HashMap<String, Double> categoryWeights;\n", - " private double extraCredit;\n", - " \n", - " /**\n", - " * Adds an assignment score to a specific category.\n", - " * \n", - " * @param category the category name (e.g., \"Homework\", \"Tests\")\n", - " * @param name the assignment name\n", - " * @param score the score earned (0-100)\n", - " */\n", - " public void addAssignment(String category, String name, double score) { }\n", - " \n", - " /**\n", - " * Sets the weight for a grade category.\n", - " * \n", - " * @param category the category name\n", - " * @param weight the weight as a decimal (e.g., 0.30 for 30%)\n", - " */\n", - " public void setCategoryWeight(String category, double weight) { }\n", - " \n", - " /**\n", - " * Calculates the final weighted grade including extra credit.\n", - " * \n", - " * @return the final grade as a percentage\n", - " */\n", - " public double calculateFinalGrade() { }\n", - " \n", - " /**\n", - " * Generates a formatted report of all grades and categories.\n", - " * \n", - " * @return a String containing the grade report\n", - " */\n", - " public String generateReport() { }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "9461cca7", - "metadata": {}, - "source": [ - "## Homework Assignment\n", - "\n", - "### Part 1: Documentation Analysis \n", - "Submission: https://docs.google.com/forms/d/e/1FAIpQLSepOCmW6KeE7jw4f80JO4Kad5YWeDUHKTpnNxnCPTtj9WEAsw/viewform?usp=header \n", - "Rewrite the poorly written code. Write them with proper Javadoc comments.\n", - "1. The original code:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ef9efa33", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "/*\n", - "public class stuff{\n", - "public static void main(String args[]){\n", - "int x=5;\n", - "int y=10;\n", - "int z=add(x,y);\n", - "System.out.println(\"ans is \"+z);\n", - "}\n", - "\n", - "static int add(int a,int b){\n", - "return a+b;\n", - "}\n", - "}\n", - " */" - ] - }, - { - "cell_type": "markdown", - "id": "cace0026", - "metadata": {}, - "source": [ - "\n", - "Submit:\n", - "\n", - "2. Your improved version\n", - "3. A brief explanation of what you improved\n", - "\n", - "### Part 2: \n", - "Problem 1: Document a Complex Method\n", - "Write complete Javadoc documentation for this method:\n", - "\n", - "public boolean enrollStudent(String studentId, String courseCode, int semester) {\n", - " Student student = findStudentById(studentId);\n", - " if (student == null) return false;\n", - "\n", - " Course course = findCourseByCode(courseCode);\n", - " if (course == null) return false;\n", - "\n", - " if (course.isFull()) return false;\n", - " if (student.hasScheduleConflict(course)) return false;\n", - " if (!student.hasPrerequisites(course)) return false;\n", - " if (student.getCreditHours() + course.getCreditHours() > 18) return false;\n", - "\n", - " student.addCourse(course);\n", - " course.addStudent(student);\n", - " recordEnrollmentTransaction(studentId, courseCode, semester);\n", - " return true;\n", - "}\n", - "\n", - "\n", - "### Part 3: Reflection Questions \n", - "1. Why is documentation more important in team projects than solo projects?\n", - "2. Give an example of when a method SHOULD be documented and when it SHOULD NOT.\n", - "\n", - "**Submit:** A Jupyter notebook or Java file with all three parts completed.\n", - "\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "1b063ed3", - "metadata": {}, - "source": [ - "## Key Takeaways\n", - "\n", - "1. **Documentation is communication** - Write for others (and your future self)\n", - "2. **Javadoc format matters** - Use `/** */` with proper tags\n", - "3. **Preconditions and postconditions create contracts** - Essential for reliable code\n", - "4. **Balance is key** - Don't over-document obvious code, but thoroughly document complex logic\n", - "5. **Keep it updated** - Outdated documentation is worse than no documentation\n", - "6. **AP Exam success** - Good documentation demonstrates programming maturity on FRQs\n", - "\n", - "### Remember:\n", - "> \"Code tells you HOW, documentation tells you WHY\"\n", - "\n", - "**The collaborative mindset:** Write documentation that you would want to find when using someone else's code. Be specific, be helpful, and anticipate questions.\n", - "\n", - "---\n", - "\n", - "## Additional Resources\n", - "- [Oracle Java Documentation Guidelines](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html)\n", - "- [AP Computer Science A Course Description](https://apcentral.collegeboard.org/)\n", - "- Practice writing documentation for existing code projects!" - ] - }, - { - "cell_type": "markdown", - "id": "11f14ac0", - "metadata": {}, - "source": [ - "## Challenge Problems (Extra Credit)\n", - "\n", - "### Challenge 1: Document a Recursive Method\n", - "Write complete documentation for a recursive method including base case, recursive case, and complexity analysis.\n", - "\n", - "### Challenge 2: Team Documentation Standard\n", - "Create a documentation style guide for a team project. Include:\n", - "- When to document (and when not to)\n", - "- Required tags for different method types\n", - "- Example templates\n", - "- Common mistakes to avoid\n", - "\n", - "### Challenge 3: Documentation Detective\n", - "Find a poorly documented open-source project. Write improved documentation for one class and submit a comparison showing before/after.\n", - "\n", - "---" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "17.0.16+8-Ubuntu-0ubuntu122.04.1" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.9-Method_Signatures-Homework-applicators.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.9-Method_Signatures-Homework-applicators.ipynb deleted file mode 100644 index 6339d872cd..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.9-Method_Signatures-Homework-applicators.ipynb +++ /dev/null @@ -1,264 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Method-Signatures]\n", - "lesson_language: Java\n", - "lesson_topic: Method-Signatures\n", - "lesson_part: interactive\n", - "lesson_type: homework\n", - "toc: true\n", - "title: Method Signatures — Homework (1.9)\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_9_hw\n", - "author: Aashray, Sai, Manas\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## AP CSA 1.9 — Method Signatures: Homework\n", - "\n", - "Complete all parts. Submit this executed notebook on GitHub Pages and answer MCQs on the Google Form.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack: Write and test max overloads\n", - "Instructions: Write two overloaded methods named max that each return the larger of two numbers.\n", - "\n", - "One should accept two int values.\n", - "\n", - "The other should accept two double values.\n", - "\n", - "Then, test both versions in the main method." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "outputs": [], - "source": [ - "public class PopcornMax {\n", - " // TODO: write int version of max\n", - " // TODO: write double version of max\n", - "\n", - " public static void main(String[] args) {\n", - " System.out.println(max(3, 9)); // expected: 9\n", - " System.out.println(max(-2, -7)); // expected: -2\n", - " System.out.println(max(3.5, 2.9)); // expected: 3.5\n", - " System.out.println(max(2, 2.0)); // should call double version → 2.0\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack 1 Answer:\n", - "\n", - "```java\n", - "public class PopcornMax {\n", - " // int overload\n", - " public static int max(int a, int b) {\n", - " return a >= b ? a : b;\n", - " }\n", - "\n", - " // double overload\n", - " public static double max(double a, double b) {\n", - " return a >= b ? a : b;\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " System.out.println(max(3, 9)); // 9\n", - " System.out.println(max(-2, -7)); // -2\n", - " System.out.println(max(3.5, 2.9)); // 3.5\n", - " System.out.println(max(2, 2.0)); // 2.0 (int 2 promoted to double → calls max(double,double))\n", - " }\n", - "}\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack: Overload print for int and String\n", - "Instructions:Implement two overloaded print methods — one that accepts an int and prints int:<n> and another that accepts String and prints str:<s>. Test with mixed types.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "outputs": [], - "source": [ - "public class PopcornPrint {\n", - " // TODO: write print(int n)\n", - " // TODO: write print(String s)\n", - "\n", - " public static void main(String[] args) {\n", - " print(42); // expected: int:42\n", - " print(\"hello\"); // expected: str:hello\n", - " print('A' + \"!\"); // char + String → String → expected: str:A!\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Popcorn Hack 2 Answer:\n", - "```java\n", - "public class PopcornPrint {\n", - " static void print(int n) {\n", - " System.out.println(\"int:\" + n);\n", - " }\n", - "\n", - " static void print(String s) {\n", - " System.out.println(\"str:\" + s);\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " print(42); // int:42\n", - " print(\"hello\"); // str:hello\n", - " print('A' + \"!\"); // str:A!\n", - " }\n", - "}\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### MCQs\n", - "1) Which pair is a valid overload?\n", - "- A) `int f(int a)` and `int f(int x)`\n", - "- B) `int f(int a)` and `double f(int a)`\n", - "- C) `int f(int a)` and `double f(double a)`\n", - "- D) `int f(int a, int b)` and `int f(int a, int b)`\n", - "\n", - "2) Which is the AP CSA notion of a method signature?\n", - "- A) `public static int max(int a, int b)`\n", - "- B) `max(int, int)`\n", - "- C) `max(int a, int b) throws Exception`\n", - "- D) `max(int, double)`\n", - "\n", - "3) With the overloads `void p(int x)` and `void p(double x)`, what prints?\n", - "```java\n", - "p(5);\n", - "p(5.0);\n", - "```\n", - "- A) `int`, `double`\n", - "- B) `double`, `double`\n", - "- C) `int`, `int`\n", - "- D) Compile error\n", - "\n", - "4) Which call is ambiguous with only these two methods?\n", - "```java\n", - "void h(long x) {}\n", - "void h(float x) {}\n", - "```\n", - "- A) `h(5)`\n", - "- B) `h(5.0)`\n", - "- C) `h(5f)`\n", - "- D) None are ambiguous\n", - "\n", - "5) Which statement is TRUE?\n", - "- A) Parameter names affect the method signature.\n", - "- B) Return type affects the method signature.\n", - "- C) Access modifiers affect the method signature.\n", - "- D) Overloading requires different parameter lists.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Short answer\n", - "- Explain why `int sum(int a, int b)` and `double sum(int a, int b)` cannot both exist.\n", - "- In one sentence, distinguish parameters vs arguments.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Coding Tasks (write Java in code blocks; pseudo-Java acceptable)\n", - "1) Write three overloads of `abs`: `int abs(int x)`, `double abs(double x)`, and `long abs(long x)`.\n", - "2) Implement two overloads of `concat`:\n", - " - `String concat(String a, String b)` returns concatenation.\n", - " - `String concat(String a, int n)` returns `a` repeated `n` times.\n", - "3) Determine output:\n", - "```java\n", - "static void show(int x) { System.out.println(\"int\"); }\n", - "static void show(double x) { System.out.println(\"double\"); }\n", - "static void show(long x) { System.out.println(\"long\"); }\n", - "\n", - "show(7);\n", - "show(7L);\n", - "show(7.0);\n", - "```\n", - "Write the expected output and a one-line explanation for each.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### FRQ-style\n", - "- FRQ 1. `indexOf(char target, String s)`: return the index of first `target` in `s` or `-1` if not found. Overload with `indexOf(String target, String s)` for first substring occurrence (without using library indexOf). State assumptions and constraints.\n", - "- FRQ 2. Overload `clamp`:\n", - " - `int clamp(int value, int low, int high)` returns `value` confined to `[low, high]`.\n", - " - `double clamp(double value, double low, double high)` similarly for doubles.\n", - " Handle the case `low > high` by swapping.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Submission checklist\n", - "- MCQs completed on the Google Form.\n", - "- This notebook executes top-to-bottom with outputs visible.\n", - "- Answers are clear and concise.\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.9-method_signatures-applicators.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.9-method_signatures-applicators.ipynb deleted file mode 100644 index 86c3b04299..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-1.9-method_signatures-applicators.ipynb +++ /dev/null @@ -1,291 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "a997f6cb", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Method-Signatures]\n", - "lesson_language: Java\n", - "lesson_topic: Method-Signatures\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Method Signatures\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_9\n", - "author: Aashray, Sai, Manas\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "32b3a894", - "metadata": {}, - "source": [ - "## AP CSA 1.9 — Method Signatures (2025)\n", - "\n", - "### Introduction\n", - "In Java, a method’s signature determines which method is called. Understanding what is and is not part of a signature is essential for reading APIs and writing overloaded methods.\n" - ] - }, - { - "cell_type": "markdown", - "id": "43eb315d", - "metadata": {}, - "source": [ - "### Learning goals\n", - "- Identify what constitutes a Java method signature (per AP): method name + parameter types and order.\n", - "- Distinguish parameters vs arguments; return type is NOT part of the signature.\n", - "- Explain method overloading and how Java selects an overload.\n", - "- Write valid method headers and call them correctly.\n", - "- Trace evaluation for calls with literals, variables, and expressions.\n" - ] - }, - { - "cell_type": "markdown", - "id": "2c01ae18", - "metadata": {}, - "source": [ - "### Quick reference\n", - "- Signature (AP scope): `methodName(type1, type2, ...)` — only name + parameter types/order.\n", - "- Not in signature: return type, parameter names, access modifiers.\n", - "- Overloading: same name, different parameter lists (type and/or arity and/or order).\n", - "- Calls: arguments must be compatible with the parameter types (with standard promotions/widening allowed).\n", - "- Return: a method declared `void` returns nothing; non-void must `return` a value of its declared type.\n", - "- Widening at call site: `int` → `double` allowed; narrowing requires explicit cast.\n" - ] - }, - { - "cell_type": "markdown", - "id": "fa08aee7", - "metadata": {}, - "source": [ - "### Example: runnable Java class (overloading)\n", - "```java\n", - "public class SigDemo {\n", - " public static int add(int a, int b) { // signature: add(int, int)\n", - " return a + b;\n", - " }\n", - " public static double add(double a, double b) { // signature: add(double, double)\n", - " return a + b;\n", - " }\n", - " public static int add(int a) { // signature: add(int)\n", - " return a + 1;\n", - " }\n", - " public static int increment(int a) { // different name\n", - " return a + 1;\n", - " }\n", - " public static void main(String[] args) {\n", - " System.out.println(add(3, 4)); // 7\n", - " System.out.println(add(3.0, 4)); // 7.0\n", - " System.out.println(add(5)); // 6\n", - " System.out.println(increment(9)); // 10\n", - " }\n", - "}\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "id": "e58a5501", - "metadata": {}, - "source": [ - "### What is and isn’t in a signature\n", - "- In AP CSA scope, signature = name + parameter types and order: `name(T1, T2, ...)`.\n", - "- NOT in signature: return type, parameter names, access modifiers, `throws` clauses.\n", - "- Therefore, you cannot overload by changing only the return type.\n" - ] - }, - { - "cell_type": "markdown", - "id": "eb2d8940", - "metadata": {}, - "source": [ - "### Not overloading by return type (concept)\n", - "- Changing only the return type does not create a new signature.\n", - "- If two methods differ only by return type and are otherwise identical, it’s a compile-time error.\n", - "- Tip: Change parameter types/arity/order to overload correctly.\n" - ] - }, - { - "cell_type": "markdown", - "id": "601d489d", - "metadata": {}, - "source": [ - "### Runnable example: Overload resolution with literals and variables\n", - "```java\n", - "public class OverloadPick {\n", - " static void show(int x) { System.out.println(\"int:\" + x); }\n", - " static void show(double x) { System.out.println(\"double:\" + x); }\n", - " static void show(long x) { System.out.println(\"long:\" + x); }\n", - "\n", - " public static void main(String[] args) {\n", - " show(5); // int literal → show(int)\n", - " show(5L); // long literal → show(long)\n", - " show(5.0); // double literal → show(double)\n", - " int i = 7; long L = 7L; double d = 7.0;\n", - " show(i); show(L); show(d);\n", - " }\n", - "}\n", - "```\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "c6c5dbf0", - "metadata": {}, - "source": [ - "### Ambiguity and overload selection (concept)\n", - "- Java prefers the most specific applicable method without narrowing.\n", - "- `int` literal can widen to `long` or convert to `float`; integral widening to `long` is typically chosen.\n", - "- Avoid ambiguous designs: provide distinct parameter lists or cast at the call site to disambiguate.\n" - ] - }, - { - "cell_type": "markdown", - "id": "8475fa9f", - "metadata": {}, - "source": [ - "### Parameter passing (concept)\n", - "- Primitives are passed by value. Changing the parameter does not change the argument in the caller.\n", - "- E.g., calling `bump(a)` does not modify `a` outside the method." - ] - }, - { - "cell_type": "markdown", - "id": "db66fefa", - "metadata": {}, - "source": [ - "### FRQ-style runnable templates\n", - "Instructions:Practice FRQ-style overloaded methods. Implement sumRange, overloaded area (circle and rectangle), and overloaded formatScore (fraction and percent).\n", - "```java\n", - "public class FrqTemplates {\n", - " // FRQ 1\n", - " // TODO: implement sumRange(start, end) — sum inclusive, return 0 if start > end\n", - " public static int sumRange(int start, int end) {\n", - " return 0; // placeholder\n", - " }\n", - "\n", - " // FRQ 2\n", - " // TODO: implement area(radius) -> circle area (double)\n", - " // TODO: implement area(width, height) -> rectangle area (int)\n", - " public static double area(double radius) {\n", - " return 0.0; // placeholder\n", - " }\n", - " public static int area(int width, int height) {\n", - " return 0; // placeholder\n", - " }\n", - "\n", - " // FRQ 3\n", - " // TODO: implement formatScore(earned, total) -> \"earned/total\"\n", - " // TODO: implement formatScore(percent) -> \"xx.x%\"\n", - " public static String formatScore(int earned, int total) {\n", - " return \"\"; // placeholder\n", - " }\n", - " public static String formatScore(double percent) {\n", - " return \"\"; // placeholder\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " System.out.println(sumRange(1, 5)); // expected: 15\n", - " System.out.println(area(3.0)); // expected: ~28.27\n", - " System.out.println(area(3, 4)); // expected: 12\n", - " System.out.println(formatScore(45, 50)); // expected: 45/50\n", - " System.out.println(formatScore(92.35)); // expected: 92.4%\n", - " }\n", - "}\n", - "\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "id": "01c77534", - "metadata": {}, - "source": [ - "### FRQ Answer Key:\n", - "```java\n", - "public class FrqTemplates {\n", - " // FRQ 1: Sum all integers from start to end (inclusive)\n", - " public static int sumRange(int start, int end) {\n", - " if (start > end) return 0;\n", - " int sum = 0;\n", - " for (int n = start; n <= end; n++) {\n", - " sum += n;\n", - " }\n", - " return sum;\n", - " }\n", - "\n", - " // FRQ 2: Overload area for circle vs. rectangle\n", - " public static double area(double radius) {\n", - " return Math.PI * radius * radius;\n", - " }\n", - " public static int area(int width, int height) {\n", - " return width * height;\n", - " }\n", - "\n", - " // FRQ 3: Overload formatScore for fraction vs. percent\n", - " public static String formatScore(int earned, int total) {\n", - " return earned + \"/\" + total;\n", - " }\n", - " public static String formatScore(double percent) {\n", - " return String.format(\"%.1f%%\", percent);\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " System.out.println(sumRange(1, 5)); // 15\n", - " System.out.println(area(3.0)); // ~28.274333882308138\n", - " System.out.println(area(3, 4)); // 12\n", - " System.out.println(formatScore(45, 50)); // 45/50\n", - " System.out.println(formatScore(92.35)); // 92.4%\n", - " }\n", - "}\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "8128e0e2", - "metadata": {}, - "source": [ - "### Anatomy of a method header (AP scope)\n", - "- General form: `modifiers returnType name(parameterList)`\n", - "- Signature considered in AP: `name(parameterTypesInOrder)`\n", - "- Examples:\n", - " - `public static int sum(int a, int b)` → signature `sum(int,int)`\n", - " - `private double area(double r)` → signature `area(double)`\n", - "\n", - "### Overloading checklist\n", - "- Different parameter count and/or parameter types and/or order\n", - "- Same method name\n", - "- Return type alone does not differentiate\n", - "\n", - "### Common pitfalls\n", - "- Ambiguity between numeric types (`int`, `long`, `float`, `double`)\n", - "- Unintended autowidening creates a different overload call than expected\n", - "- Shadowing due to parameter names does not matter to signature\n", - "\n", - "### Best practices\n", - "- Keep overloads consistent in behavior and naming\n", - "- Prefer clear, non-ambiguous parameter lists\n", - "- Add documentation examples showing which overload is picked\n", - "\n" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.1.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.1.ipynb deleted file mode 100644 index 36345f1a83..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.1.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "882c1d96", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Algorithms-with-Selection-and-Repetition]\n", - "lesson_language: Java\n", - "lesson_topic: Algorithms-with-Selection-and-Repetition\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Algorithms with Selection and Repetition\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_1\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.10.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.10.ipynb deleted file mode 100644 index b683669146..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.10.ipynb +++ /dev/null @@ -1,141 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "187845a9", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, String-Algorithms]\n", - "lesson_language: Java\n", - "lesson_topic: String-Algorithms\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Implementing String Algorithms\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_10\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "58dc957d", - "metadata": {}, - "source": [ - "# Developing Algorithms Using Strings" - ] - }, - { - "cell_type": "markdown", - "id": "353bf079", - "metadata": {}, - "source": [ - "LEARNING OBJECTIVES:\n", - "For algorithms in the context of a particular specification that involves ```String``` objects:\n", - "- identify standard algorithms\n", - "- modify standard algorithms\n", - "- develop an algorithm\n", - "\n", - "\n", - "**Java has many methods that are helpful when working with strings:**\n", - "\n", - "* ```String .substring``` --> retrieves portion of a string\n", - "* ```String .equals``` --> compares two strings\n", - "* ```String .length``` --> returns length of a string\n", - "* ```for Loop``` --> iterating through characters of a string\n", - "\n", - "<br>\n", - "<br>\n", - "\n", - "<h3> Finding a substring within a string </h3>\n", - "\n", - "We can use the \"window\" method:\n", - "\n", - "A \"window\" is created the same length as the substring. We then iterate through the main string in sections and compare to the substring\n", - "\n", - "For example:\n", - "\n", - "<h3> I T E R A T E </h3>with substring \"ERA\"\n", - "\n", - "<br>\n", - "<br>\n", - "<br>" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1e74bcdc", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "public class StringFinder {\n", - " public static void main(String[] args) {\n", - " String word = \"iterate\";\n", - " String sub = \"xxx\";\n", - " boolean found = false; // will be set to true once substring is found\n", - "\n", - " for (int i = 0; i < word.length(); i++) { //iterating forwards: starting at first index (0) and going to the length of the word.. let's try word.length\n", - " String portion = word.substring(i, i + sub.length());\n", - " if (sub.length() > portion.length()) break;\n", - " if (portion.equals(sub)) { // make sure you use .equals!!\n", - " found = true;\n", - " break;\n", - " }\n", - " }\n", - "\n", - " if (found)\n", - " System.out.println(\"substring is found within string!\");\n", - " else\n", - " System.out.println(\"substring is NOT within string\");\n", - " }\n", - "\n", - "}\n", - "\n", - "\n", - "StringFinder.main(null);" - ] - }, - { - "cell_type": "markdown", - "id": "08f1a7e6", - "metadata": {}, - "source": [ - "<h4> POPCORN HACK: Run the code.. what happened? How can we fix it?</h4>\n", - "\n", - "Tell us below!\n", - "\n", - "<br>\n", - "<br>\n", - "\n", - "<h4> Another issue:</h4>\n", - "\n", - "<h3> I T E R A T E </h3>\n", - "What if our substring was the word \"RATE\"? Note that RATE is at the end of the whole string\n", - "\n", - "<br>\n", - "<br>\n", - "\n", - "<h3> HACKS </h3>\n", - "\n", - "**Create a algorithm similar to the one above. Except this time, use iteration to count the number of vowels within the main string.**\n", - "\n", - "HINT: Use the boolean expressions we have learned in previous lessons. Which would you use when comparing your \"window\" with multiple options of substrings?" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.11.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.11.ipynb deleted file mode 100644 index d453a868ff..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.11.ipynb +++ /dev/null @@ -1,86 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "1d949357", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Nested-Iteration]\n", - "lesson_language: Java\n", - "lesson_topic: Nested-Iteration\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Nested Iteration\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_11\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "5f8d2462", - "metadata": {}, - "source": [ - "# Nested Iteration" - ] - }, - { - "cell_type": "markdown", - "id": "5205677c", - "metadata": {}, - "source": [ - "**nested iteration**\n", - "<details>occurs when we have a loop inside of another loop, similar to nested conditional statements in unit 3" - ] - }, - { - "cell_type": "markdown", - "id": "1c816a41", - "metadata": {}, - "source": [ - "When you have one loop inside another, the inner loop has to finish all its rounds before the outer loop moves to the next round. If the inner loop has a \"stop\" command, it only stops for that round of the outer loop. The next time the outer loop starts a new round, the inner loop starts over.\n", - "\n", - "If you have two nested loops without stops, and the outer one runs n times while the inner one runs m times each time the outer one goes around, the inner loop will run m times n times, which is m * n times in total. This rule also applies if you have more than two nested loops. To find the total number of times the innermost loop runs, just multiply how many times each loop runs per round." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9ea3cb0d", - "metadata": { - "vscode": { - "languageId": "groovy" - } - }, - "outputs": [], - "source": [ - "public class NestedLoopsDemo {\n", - " public static void main(String[] args) {\n", - " int n = 3; //numb of times the outside loop runs\n", - " int m = 2; //numb of times the inside loop runs\n", - "\n", - " //the nested loops\n", - " for (int i = 1; i <= n; i++) {\n", - " System.out.println(\"Outer loop iteration: \" + i);\n", - " for (int j = 1; j <= m; j++) {\n", - " System.out.println(\"Inner loop iteration: \" + j);\n", - " }\n", - " }\n", - " }\n", - "}\n", - "NestedLoopsDemo.main(null)" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.12.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.12.ipynb deleted file mode 100644 index aab8189d39..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.12.ipynb +++ /dev/null @@ -1,188 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "b5bfea60", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Run-Time-Analysis]\n", - "lesson_language: Java\n", - "lesson_topic: Run-Time-Analysis\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Informal Run-Time Analysis\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_12\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "fac25f4d", - "metadata": {}, - "source": [ - "# Informal Code Analysis\n", - "\n", - "<b>Learning objective</b>: Compute statement execution counts & informal run-time comparison of iterative statements\n", - "\n", - "<b>Essential Knowledge</b>: A statement execution count indicates the number of times a statement is executed by the program" - ] - }, - { - "cell_type": "markdown", - "id": "514e1ed4", - "metadata": {}, - "source": [ - "<h3> What IS informal code analysis? </h3>\n", - "\n", - "Answer:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "71f52e02", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// CODE EXAMPLE #1 (for loop)\n", - "public class InformalCodeAnalysis {\n", - " public static void main(String[] args) {\n", - " int count = 0;\n", - " for (int k = 0; k < 30; k++)\n", - " {\n", - " if (k % 3 == 0) // statement 1\n", - " {\n", - " count++; // statement 2\n", - " }\n", - " }\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "3b0a54ac", - "metadata": {}, - "source": [ - "<b>How many times will statement 1 execute? </b>\n", - "\n", - "Answer:\n", - "\n", - "<b>How many times will statement 2 execute?</b>\n", - "\n", - "Answer:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0bacda90", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "<b>How many times will statement 3 execute?</b>\n", - "\n", - "Answer:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b634d447", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Rewrite the code segment below to have a faster run-time based on statement execution counts\n", - "for (int k = 0; k < 135; k++)\n", - "{\n", - " if (k % 5 == 0)\n", - " {\n", - " System.out.println(k);\n", - " }\n", - "}" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "46081b87", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// CODE EXAMPLE #3 (while loop)\n", - "\n", - "int num = (int)(Math.random() * 10);\n", - "while (num % 2 != 0)\n", - "{\n", - " num = (int)(Math.random() * 10) // statement 4\n", - "}" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c7493f8c", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "<b>What is the min/max number of times statement 4 will execute?</b>\n", - "\n", - "Answer:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "36c988b2", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// CODE EXAMPLE #4 (nested loop)\n", - "\n", - "for (int outer = 0; outer < 3; outer++)\n", - "{\n", - " for (int inner = 0; inner < 4; inner++)\n", - " {\n", - " // statement #5\n", - " }\n", - "}" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.2.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.2.ipynb deleted file mode 100644 index b6a44c7b61..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.2.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "064892a5", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Boolean-Expressions]\n", - "lesson_language: Java\n", - "lesson_topic: Boolean-Expressions\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Boolean Expressions\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_2\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.3.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.3.ipynb deleted file mode 100644 index e39767ce39..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.3.ipynb +++ /dev/null @@ -1,144 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, If-Statements]\n", - "lesson_language: Java\n", - "lesson_topic: If-Statements\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: if Statements\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_3\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 3.3 If Else Statements\n", - "\n", - "<a id=\"if-else-statements\"></a>\n", - "## Purpose of Else Statements\n", - "Else statements: Handles what happens when the if condition is false.\n", - "Structure of If-Else:\n", - "- If statement with a condition.\n", - "- Else statement without a condition.\n", - "- Both parts have code blocks surrounded by {}.\n", - "\n", - "- if there is only one instruction in the if statement technically brackets aren't mandatory, but its good to practice using them because generally there is more in the statements. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// example of a simple if else loop: \n", - "// things to keep in mind: \n", - "// Always put a semicolon after a parenthesis \n", - "// make sure you use double quotes are your message \n", - "\n", - "int number = 2; // change this number to see what happens when its odd\n", - "\n", - "if (number % 2 == 0) {\n", - " System.out.println(\"Number is even\");\n", - "} else {\n", - " System.out.println(\"Number is odd\");\n", - "}" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// slightly more complex loop because there are 2 messages \n", - "\n", - "int myAge = 17; // adjust the age too see the difference in what it prints out\n", - "\n", - "System.out.println(\"Current age: \" + myAge);\n", - "\n", - "if (myAge >= 16) {\n", - " System.out.println(\"You can learn to drive a car.\");\n", - " System.out.println(\"Drive safe!\");\n", - "} else {\n", - " System.out.println(\"You are not old enough for a license yet.\");\n", - " System.out.println(\"Try again next year\");\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### popcorn hack 1 \n", - "\n", - "<img width=\"816\" alt=\"image\" src=\"https://github.com/user-attachments/assets/c6701143-b87f-427b-a206-6cee0660571c\">\n", - "\n", - "1. Based on this code, if you were younger than 16 what would it print out?\n", - "2. Write your own if else statement\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// popcorn hack 2 \n", - "// Figure out what is wrong with this code and fix the error. (2 errors)\n", - "\n", - "int number = 2; \n", - "\n", - "if (number % 2 == 0) {\n", - " System.out.println('Number is even');\n", - "} else {\n", - " System.out.println(\"Number is odd\")\n", - "}" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "17.0.12+0" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.4.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.4.ipynb deleted file mode 100644 index 0b31921f98..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.4.ipynb +++ /dev/null @@ -1,138 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Nested-If-Statements]\n", - "lesson_language: Java\n", - "lesson_topic: Nested-If-Statements\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Nested `if` Statements\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_4\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# 3.4 Else If Statements \n", - "Else If Statements: Used when you have multiple conditions that need to be checked sequentially.\n", - "\n", - "Flow of Execution: Each condition is evaluated in the order written. The first true condition's code runs, and the rest are skipped.\n", - "\n", - "Structure:\n", - "\n", - "- Start with a single if statement.\n", - "- Follow with as many else if statements as needed.\n", - "- Optionally end with one else to handle any remaining cases.\n", - "Key Concept: The order of conditions matters. More specific conditions should come before broader ones to ensure accurate results.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Current age: 17\n", - "You are old enough for a license to drive.\n" - ] - } - ], - "source": [ - "int myAge = 17; // adjust the age too see the difference in what it prints out\n", - "System.out.println(\"Current age: \" + myAge);\n", - "if (myAge >= 18) \n", - "{\n", - " System.out.println(\"You can registar to vote.\");\n", - " System.out.println(\"You are old enough for a license to drive.\");\n", - "}\n", - "else if (myAge >= 16) {\n", - " System.out.println(\"You are old enough for a license to drive.\");\n", - "} \n", - "else if (myAge >= 15) {\n", - " System.out.println(\"You can learn to drive a car.\");\n", - "}\n", - "else if (myAge >= 14) {\n", - " System.out.println(\"You are 14\");\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Raise your hand: \n", - "1. If I was 19 what would it print out?\n", - "2. If I was 13 what would it print out?" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hack \n", - "Add more statements to make the code print out an \"F\" and \"C\"" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [], - "source": [ - "public class gradeEvaluator \n", - "{\n", - " public static void main(String[] args) \n", - " {\n", - " double myAverage = 90;\n", - " System.out.println(\"Current average: \" + myAverage);\n", - " if (myAverage >= 90)\n", - " {\n", - " System.out.println(\"You have \\\"A\\\" average.\");\n", - " }\n", - " \n", - " else if (myAverage >= 80)\n", - " { \n", - " System.out.println(\"You have an \\\"B\\\" average.\");\n", - " }\n", - " //add more letter grade options as needed\n", - " }\n", - "}\n", - " " - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "17.0.12+0" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.5.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.5.ipynb deleted file mode 100644 index 2a1c75cc23..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.5.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "fb11f85c", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Compound-Boolean-Expressions]\n", - "lesson_language: Java\n", - "lesson_topic: Compound-Boolean-Expressions\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Compound Boolean Expressions\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_5\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.6.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.6.ipynb deleted file mode 100644 index d884e92f78..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.6.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "b16b641e", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Comparing-Boolean-Expressions]\n", - "lesson_language: Java\n", - "lesson_topic: Comparing-Boolean-Expressions\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Comparing Boolean Expressions\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_6\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.7.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.7.ipynb deleted file mode 100644 index 67fb13cdd9..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.7.ipynb +++ /dev/null @@ -1,289 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "id": "H2owDd1giFbL" - }, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, While-Loops]\n", - "lesson_language: Java\n", - "lesson_topic: While-Loops\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: while Loops\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_7\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "n5DwvzKDiFbO" - }, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "tz_lOIHhiFbP" - }, - "source": [ - "# while Loops" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "WWocj22RiFbP" - }, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "8LcvRRKgiGt8" - }, - "source": [ - "- A while loop is a fundamental control structure in programming used for repeated execution of a block of code as long as a condition is true.\n", - "- The loop starts by evaluating the condition. If the condition is true, the code inside the loop is executed.\n", - "- After each iteration, the condition is re-evaluated, and if it's still true, the loop continues.\n", - "If the condition is false initially, the loop code is never executed.\n", - "- While loops are used when you don't know in advance how many times the loop needs to execute.\n", - "- There's a risk of infinite loops if the condition never becomes false, so be cautious.\n", - "You can use variables and complex expressions as loop conditions.\n", - "- It's essential to update the loop control variable within the loop to prevent infinite loops.\n", - "- While loops are typically used for tasks such as iterating over collections or waiting for a specific condition to be met.\n", - "- You can always break out of a while loop prematurely using the break statement." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "E8iapCcPija6" - }, - "source": [ - "## Example of While Loops" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "Jq6_6Xz9iQ7T" - }, - "outputs": [], - "source": [ - "public class PyramidPattern {\n", - " public static void main(String[] args) {\n", - " int height = 5;\n", - " int row = 1;\n", - "\n", - " while (row <= height) {\n", - " int spaces = height - row;\n", - " int stars = 2 * row - 1;\n", - "\n", - " // Print spaces\n", - " int spaceCount = spaces;\n", - " while (spaceCount > 0) {\n", - " System.out.print(\" \");\n", - " spaceCount--;\n", - " }\n", - "\n", - " // Print stars\n", - " int starCount = stars;\n", - " while (starCount > 0) {\n", - " System.out.print(\"*\");\n", - " starCount--;\n", - " }\n", - "\n", - " System.out.println(); // Move to the next line for the next row\n", - " row++;\n", - " }\n", - " }\n", - "}\n", - "PyramidPattern.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "gQ5Aei3eiFbT" - }, - "source": [ - "# 4.4 Nested Iteration" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "sdYSe47hiFbT" - }, - "source": [ - "**nested iteration**\n", - "<details>occurs when we have a loop inside of another loop, similar to nested conditional statements in unit 3" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "8qx7m09piFbT" - }, - "source": [ - "When you have one loop inside another, the inner loop has to finish all its rounds before the outer loop moves to the next round. If the inner loop has a \"stop\" command, it only stops for that round of the outer loop. The next time the outer loop starts a new round, the inner loop starts over.\n", - "\n", - "If you have two nested loops without stops, and the outer one runs n times while the inner one runs m times each time the outer one goes around, the inner loop will run m times n times, which is m * n times in total. This rule also applies if you have more than two nested loops. To find the total number of times the innermost loop runs, just multiply how many times each loop runs per round." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "SE-EnFk5iFbU" - }, - "outputs": [], - "source": [ - "public class NestedLoopsDemo {\n", - " public static void main(String[] args) {\n", - " int n = 3; //numb of times the outside loop runs\n", - " int m = 2; //numb of times the inside loop runs\n", - "\n", - " //the nested loops\n", - " for (int i = 1; i <= n; i++) {\n", - " System.out.println(\"Outer loop iteration: \" + i);\n", - " for (int j = 1; j <= m; j++) {\n", - " System.out.println(\"Inner loop iteration: \" + j);\n", - " }\n", - " }\n", - " }\n", - "}\n", - "NestedLoopsDemo.main(null)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "QVPEF82jiFbW" - }, - "outputs": [], - "source": [ - "// CODE EXAMPLE #2 (for loop)\n", - "public class InformalCodeAnalysis {\n", - " public static void main(String[] args) {\n", - " int count = 0;\n", - " for (int k = 4; k < 30; k+=3)\n", - " {\n", - " count++; // statement 3\n", - " }\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "ZfFLuOHqiFbW" - }, - "source": [ - "<b>How many times will statement 3 execute?</b>\n", - "\n", - "Answer:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "fv6VvS8AiFbW" - }, - "outputs": [], - "source": [ - "// Rewrite the code segment below to have a faster run-time based on statement execution counts\n", - "for (int k = 0; k < 135; k++)\n", - "{\n", - " if (k % 5 == 0)\n", - " {\n", - " System.out.println(k);\n", - " }\n", - "}" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "PAtLyFjKiFbX" - }, - "outputs": [], - "source": [ - "// CODE EXAMPLE #3 (while loop)\n", - "\n", - "int num = (int)(Math.random() * 10);\n", - "while (num % 2 != 0)\n", - "{\n", - " num = (int)(Math.random() * 10) // statement 4\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "id": "AaMr4kc3iFbX" - }, - "source": [ - "<b>What is the min/max number of times statement 4 will execute?</b>\n", - "\n", - "Answer:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "87I7g-oKiFbg" - }, - "outputs": [], - "source": [ - "// CODE EXAMPLE #4 (nested loop)\n", - "\n", - "for (int outer = 0; outer < 3; outer++)\n", - "{\n", - " for (int inner = 0; inner < 4; inner++)\n", - " {\n", - " // statement #5\n", - " }\n", - "}" - ] - } - ], - "metadata": { - "colab": { - "provenance": [] - }, - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "21" - } - }, - "nbformat": 4, - "nbformat_minor": 0 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.8.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.8.ipynb deleted file mode 100644 index 8ff42916e5..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.8.ipynb +++ /dev/null @@ -1,128 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "616b68b9", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, For-Loops]\n", - "lesson_language: Java\n", - "lesson_topic: For-Loops\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: for Loops\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_8\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "147eeb6b", - "metadata": {}, - "source": [ - "# 4.2 for Loops" - ] - }, - { - "cell_type": "markdown", - "id": "b893b1b6", - "metadata": {}, - "source": [ - "- Iterative statement that checks for condition\n", - "- Repeatedly execute a a block of code as long as the condition is met\n", - "- Condition specifies amount of times\n", - "\n", - "# for Loops vs. while Loops\n", - "- while Loops: use when number of iterations is unknown\n", - "- for Loops: use when number of iterations is known" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c0e51cc7", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "int i = 0;\n", - "while (i < 5) {\n", - " System.out.println(i);\n", - " i++;\n", - "}" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6b9b9eb7", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "for (int i = 0; i < 5; i++) {\n", - " System.out.println(i);\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "f9226dc1", - "metadata": {}, - "source": [ - "- Three parts in for loop header: variable initialization, Boolean (conditional) expression, and increment/decrement statement\n", - "\n", - "Question: Which part is which?\n", - "\n", - "- variable initialization (int i=0): sets variable before loop starts\n", - "- Boolean (conditional) expression (i < 5): defines condition for loop to run, in this case, the loop continues as long as i is less than 5, so loops 5 times i 05\n", - "- increment/decrement statement (i++): increases variable each time code block in the loop is executed, in this case it increases by 1\n", - "- variable can be used in the code block for other various reasons besides specifying how many times the loop will repeat\n", - "- Boolean (conditional) expression and increment/decrement statement together determine how many times the loop will repeat\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9433db74", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "\n", - "int sum = 0;\n", - "int sum_all = 0;\n", - "\n", - "for (int i = 0; i < 10; i++) {\n", - " if (i % 2 == 0)\n", - " sum += i;\n", - " sum_all += i;\n", - "}\n", - "\n", - "System.out.println(sum);\n", - "System.out.println(sum_all);" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.9.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.9.ipynb deleted file mode 100644 index 82aeeb2821..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-2.9.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "e9042be9", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Selection-and-Iteration-Algorithms]\n", - "lesson_language: Java\n", - "lesson_topic: Selection-and-Iteration-Algorithms\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Implementing Selection and Iteration Algorithms\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/2_9\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.1.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.1.ipynb deleted file mode 100644 index 00cadeb1e1..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.1.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "7dacfc7f", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Abstraction-and-Program-Design]\n", - "lesson_language: Java\n", - "lesson_topic: Abstraction-and-Program-Design\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Abstraction and Program Design\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_1\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.2.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.2.ipynb deleted file mode 100644 index 98dfd49b2e..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.2.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "afa16d85", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Program-Design-Impact]\n", - "lesson_language: Java\n", - "lesson_topic: Program-Design-Impact\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Impact of Program Design\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_2\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.3.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.3.ipynb deleted file mode 100644 index f0cbfc496d..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.3.ipynb +++ /dev/null @@ -1,445 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Anatomy-of-a-Class]\n", - "lesson_language: Java\n", - "lesson_topic: Anatomy-of-a-Class\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Anatomy of a Class\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_3\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Console Based Menu\n", - "Java imports allow user input and console output to be displayed in Terminal \n", - "\n", - "Objects Used\n", - "- Makes Object from Scanner Class to obtain inputs / menu selection from User\n", - "- Use System Class, to call static methods System.out.print and System.out.println to output to console\n", - "- User Math Class, to call static method Math.random() to generate random number\n", - "\n", - "Other College Board Topics\n", - "- A 2D array is used to store COLORS\n", - "- A Control Structure, Switch, is used to process Menu select to code that performs related action\n", - "\n", - "Key PBL Topic\n", - "- Menu class when instantiated with new Menu() takes over Frontend experience with user. This is relevant to Draw Lab in this article and how Spring Boot works in Web programming. Objects are intended to encapsulate Frontend, Backend or experience ... Web Site control flow, Database CRUD operations, or a Menu in terminal (this example) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// imports allow you to use code already written by others. It is good to explore and learn libraries. The names around the dots often give you a hint to the originator of the code.\n", - "import java.util.Scanner; //library for user input\n", - "import java.lang.Math; //library for random numbers\n", - "\n", - "\n", - "public class Menu {\n", - " // Instance Variables\n", - " public final String DEFAULT = \"\\u001B[0m\"; // Default Terminal Color\n", - " public final String[][] COLORS = { // 2D Array of ANSI Terminal Colors\n", - " {\"Default\",DEFAULT},\n", - " {\"Red\", \"\\u001B[31m\"}, \n", - " {\"Green\", \"\\u001B[32m\"}, \n", - " {\"Yellow\", \"\\u001B[33m\"}, \n", - " {\"Blue\", \"\\u001B[34m\"}, \n", - " {\"Purple\", \"\\u001B[35m\"}, \n", - " {\"Cyan\", \"\\u001B[36m\"}, \n", - " {\"White\", \"\\u001B[37m\"}, \n", - " };\n", - " // 2D column location for data\n", - " public final int NAME = 0;\n", - " public final int ANSI = 1; // ANSI is the \"standard\" for terminal codes\n", - "\n", - " // Constructor on this Object takes control of menu events and actions\n", - " public Menu() {\n", - " Scanner sc = new Scanner(System.in); // using Java Scanner Object\n", - " \n", - " this.print(); // print Menu\n", - " boolean quit = false;\n", - " while (!quit) {\n", - " try { // scan for Input\n", - " int choice = sc.nextInt(); // using method from Java Scanner Object\n", - " System.out.print(\"\" + choice + \": \");\n", - " quit = this.action(choice); // take action\n", - " } catch (Exception e) {\n", - " sc.nextLine(); // error: clear buffer\n", - " System.out.println(e + \": Not a number, try again.\");\n", - " }\n", - " }\n", - " sc.close();\n", - " }\n", - "\n", - " // Print the menu options to Terminal\n", - " private void print() {\n", - " //System.out.println commands below is used to present a Menu to the user. \n", - " System.out.println(\"-------------------------\\n\");\n", - " System.out.println(\"Choose from these choices\");\n", - " System.out.println(\"-------------------------\\n\");\n", - " System.out.println(\"1 - Say Hello\");\n", - " System.out.println(\"2 - Output colors\");\n", - " System.out.println(\"3 - Loading in color\");\n", - " System.out.println(\"0 - Quit\");\n", - " System.out.println(\"-------------------------\\n\");\n", - " }\n", - "\n", - " // Private method to perform action and return true if action is to quit/exit\n", - " private boolean action(int selection) {\n", - " boolean quit = false;\n", - "\n", - " switch (selection) { // Switch or Switch/Case is Control Flow statement and is used to evaluate the user selection\n", - " case 0: \n", - " System.out.print(\"Goodbye, World!\");\n", - " quit = true;\n", - " break;\n", - " case 1:\n", - " System.out.print(\"Hello, World!\");\n", - " break;\n", - " case 2:\n", - " for(int i = 0; i < COLORS.length; i++) // loop through COLORS array\n", - " System.out.print(COLORS[i][ANSI] + COLORS[i][NAME]);\n", - " break;\n", - " case 3:\n", - " System.out.print(\"Loading...\");\n", - " for (int i = 0; i < 20; i++) { // fixed length loading bar\n", - " int random = (int) (Math.random() * COLORS.length); // random logic\n", - " try {\n", - " Thread.sleep(100); // delay for loading\n", - " } catch (Exception e) {\n", - " System.out.println(e);\n", - " }\n", - " System.out.print(COLORS[random][ANSI] + \"#\");\n", - " }\n", - " break;\n", - " \n", - " default:\n", - " //Prints error message from console\n", - " System.out.print(\"Unexpected choice, try again.\");\n", - " }\n", - " System.out.println(DEFAULT); // make sure to reset color and provide new line\n", - " return quit;\n", - " }\n", - "\n", - " // Static driver/tester method\n", - " static public void main(String[] args) { \n", - " new Menu(); // starting Menu object\n", - " }\n", - "\n", - "}\n", - "Menu.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Desktop GUI Menu\n", - "Swing and AWT imports allow Java to provide a Graphical User Interface on the desktop.\n", - "\n", - "Other College Board Topics\n", - "- A 1D array is used to store MENUS\n", - "- A Control Structure, if-else if-else, is used to process Menu selection to code that performs related action\n", - "\n", - "Using Objects\n", - "- Javax Swing UI (JFrame)\n", - "- Timer with a TimerTask to allow action to repeatedly occur without halting thread." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "import java.awt.*;\n", - "import java.awt.event.*;\n", - "import javax.swing.*;\n", - "import java.util.Timer;\n", - "import java.util.TimerTask;\n", - "// Graphical-User-Interface for Desktop in Java using Java Swing. \n", - "public class MenuJFrame extends JFrame implements ActionListener {\n", - " private JFrame frame;\n", - " private JMenuBar menubar;\n", - " private JMenu menu;\n", - " private JLabel message = new JLabel(\"Click on Menu to select an action.\");\n", - " public final String[] MENUS = { // 1D Array of Menu Choices\n", - " \"Hello\", \"Colors\", \"Loading bar\", \n", - " };\n", - " // Statics to assist with timer and messaging, single copy (no instance)\n", - " private\tstatic int delay = 20;\n", - " private\tstatic int step = 1;\n", - " private static String hashes = \"\";\n", - "\n", - " // Constructor enables the Frame instance, the object \"this.frame\"\n", - " public MenuJFrame(String title) {\n", - "\t // Initializing Key Objects\n", - " frame = new JFrame(title);\n", - "\t menubar = new JMenuBar();\n", - "\t menu = new JMenu(\"Menu\");\n", - "\n", - " // Initializing Menu objects and adding actions\n", - " for (String mx : MENUS) {\n", - " JMenuItem m = new JMenuItem(mx);\n", - " m.addActionListener(this);\n", - " menu.add(m); \n", - " }\n", - "\n", - " // Adding / Connecting Objects\n", - " menubar.add(menu);\n", - " frame.setJMenuBar(menubar);\n", - " frame.add(message);\n", - "\n", - " // Sets JFrame close operation to Class variable JFrame.EXIT_ON_CLOSE\n", - " frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n", - " \n", - " // set the size of window based on objects\n", - " frame.setSize(300,200);\n", - "\n", - " // makes the frame object visible according to properties previously set\n", - " frame.setVisible(true); // flow of control shifts to frame object\n", - " }\n", - "\n", - " // event from user selecting a menu option\n", - " public void actionPerformed(ActionEvent e) {\n", - " // local variable to ActinEvent\n", - " String selection = e.getActionCommand(); // menu selection\n", - " String msg; // local variable to create response from action\n", - " final String[] COLORS = {\"Red\", \"Green\", \"Blue\"}; // add more colors here\n", - " \t final String start_msg = \"<html>\"; // html building\n", - " \tfinal String end_msg = \"</html>\";\n", - " \tfinal String hash = \"#\";\n", - "\n", - " // run code based on the menuItem that was selected\n", - " if ( selection.equals(MENUS[0]) ) { // Hello Action\n", - " msg = \"Hello, World\";\n", - " message.setText(msg);\n", - " } else if ( selection.equals(MENUS[1]) ) { // Color Action\n", - " msg = start_msg + \"<p>\" + selection + \"</p>\";\n", - " for (String color : COLORS) {\n", - " msg += \"<font color=\" + color + \">\" + color + \" </font>\";\n", - " }\n", - " msg += end_msg;\n", - " message.setText(msg);\n", - " } else { // Loading Bar Action\n", - "\t String loading = \"<p>Loading</p>\";\n", - " // Code to run on a Timer\n", - " Timer timer = new Timer();\n", - " TimerTask task = new TimerTask() {\n", - " public void run() { // Method for TimerTask\n", - " // Static and Local variables used to manage message building\n", - " int random = (int) (Math.random() * COLORS.length); // random logic\n", - " MenuJFrame.hashes += \"<font color=\" + COLORS[random] + \">\" + hash + \"</font>\";\n", - " String msg = start_msg + loading + hashes + end_msg;\n", - " message.setText(msg);\n", - " \n", - "\t \t // Shutdown timer and reset data\n", - " if(MenuJFrame.step++ > MenuJFrame.delay) {\n", - " MenuJFrame.step = 1; MenuJFrame.hashes=\"\";\n", - " timer.cancel();\n", - " }\n", - " };\n", - " };\n", - " // Schedule task and interval\n", - " timer.schedule(task, 200, 200);\n", - " message.setText(start_msg + loading + hash + end_msg); // prime/initial display\n", - " }\n", - " }\n", - "\n", - " // Driver turn over control the GUI\n", - " public static void main(String[] args) {\n", - " // Activates an instance of MenuJFrame class, which makes a JFrame object\n", - " new MenuJFrame(\"Menu\");\n", - " }\n", - "}\n", - "MenuJFrame.main(null);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Hacks\n", - "College Board and CTE competences. \n", - "- Documentation / Analysis. Describe with Markdown Cell(s) and triple backtick code fragments that answers to the following from your work...\n", - " - Explain where a Class is defined \n", - " - Explain where an instances of a Class is defined\n", - " - Explain where an object is Calling a Method\n", - " - Explain where an object is Mutating data\n", - " - Describe Console and GUI differences differences.\n", - "- Build a new Console or GUI menu for your FRQs. This allows sharing a single project with each person working on a different FRQ, The menu visualization and organization can make it easier for team to present in a unified manner.\n", - " - Use constructors and instance data. The two menus are activated by a `new`, understand what that means.\n", - " - Use static methods and data. The [Math Class](https://www.javatpoint.com/java-math) typically performs calculations using static methods." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Object Superclass" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Learning Targets: \n", - " * What is the *Object* class\n", - " * Why is the *Object* class important to remember" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "***" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Every class and object created **without** the ```extends``` keyword will be implicitly extended from the **[Object Superclass](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html)**. This means it will inherit some basic methods. Some notable methods are:\n", - "1. ```getClass()```\n", - "2. ```toString()```\n", - "3. ```equals()```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### So What?\n", - "Well its important to keep in mind when writing out your class. If you are planning to have a **method** in your class/object that **matches** the basic **Object**, then it **must** be a ```public override``` because all of the Object methods are public.\n", - "* are some methods from Object such as **getClass()** that you **cannot** override." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// this will return an error\n", - "class Shape {\n", - " String toString(){\n", - " return \"Shape\";\n", - " }\n", - "}" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// this will be fine\n", - "class Shape{\n", - " @Override\n", - " public String toString(){\n", - " return \"Shape\";\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hacks\n", - "Create an example where you execute an unchanged method from *Object*, then execute a different method from *Object* that you changed." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Introduction to Inheritance in Java\n", - "\n", - "Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class (the subclass) to inherit fields and methods from another class (the superclass). This promotes code reusability and establishes a natural hierarchical relationship between classes.\n", - "\n", - "### Key Concepts of Inheritance:\n", - "\n", - "1. **Superclass and Subclass**:\n", - " - **Superclass (Parent Class)**: The class whose features are inherited. It provides common attributes and behaviors that can be shared by subclasses.\n", - " - **Subclass (Child Class)**: The class that inherits from the superclass. It can extend or modify the behavior of the superclass and add its own unique features.\n", - "\n", - "2. **Basic Syntax**:\n", - " - To declare a subclass, use the `extends` keyword.\n", - " ```java\n", - " public class Subclass extends Superclass {\n", - " // Subclass-specific fields and methods\n", - " }\n", - "\n", - "**Topics to Explore**:\n", - "To learn more, you can explore the tabs on the navigation bar to explore additional units within the CollegeBoard curriculum." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Vehicle {\n", - " float miles = 0;\n", - " float milesTraveled(float milesToAdd){\n", - " this.miles += milesToAdd;\n", - " return this.miles;\n", - " }\n", - " boolean hasMovement = true;\n", - "}\n", - "\n", - "public class Car extends Vehicle {\n", - " boolean canFly = true;\n", - "}\n", - "\n", - "public class Plane extends Vehicle {\n", - " boolean canFly = true;\n", - "}\n", - "\n", - "Car myCar = new Car();\n", - "System.out.println(\"As you can see my Car also has the inherited varible hasMovement\");\n", - "System.out.println(\"myCar.hasMovement: \"+(new Boolean(myCar.hasMovement)).toString());" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "17.0.3+7" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.4.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.4.ipynb deleted file mode 100644 index 6d99c92f0a..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.4.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "96ef51cf", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Constructors]\n", - "lesson_language: Java\n", - "lesson_topic: Constructors\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Constructors\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_4\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.5.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.5.ipynb deleted file mode 100644 index f3091561c8..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.5.ipynb +++ /dev/null @@ -1,538 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Methods]\n", - "lesson_language: Java\n", - "lesson_topic: Methods\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Methods How to Write Them\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_5\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Method Overrides" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Every class inherits methods from its **parent class**. These methods can be called in the child class and can also be **overridden**." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Shape Class\n", - "This is the same shape class from before." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "metadata": {}, - "outputs": [], - "source": [ - "public class Shape {\n", - " protected String name;\n", - " private int length;\n", - " private int width;\n", - "\n", - " // Default constructor\n", - " public Shape() {\n", - " this.name = \"shape\";\n", - " this.length = 10;\n", - " this.width = 5;\n", - " }\n", - "\n", - " // Parameterized constructor\n", - " public Shape(String name, int length, int width) {\n", - " this.name = name;\n", - " this.length = length;\n", - " this.width = width;\n", - " }\n", - "\n", - " // Getter methods\n", - " public String get_name() {\n", - " return this.name;\n", - " }\n", - "\n", - " public int get_length() {\n", - " return this.length;\n", - " }\n", - "\n", - " public int get_width() {\n", - " return this.width;\n", - " }\n", - "\n", - " // Setter methods\n", - " public void set_name(String n) {\n", - " this.name = n;\n", - " }\n", - "\n", - " public void set_length(int a) {\n", - " this.length = a;\n", - " }\n", - "\n", - " public void set_width(int b) {\n", - " this.width = b;\n", - " }\n", - "\n", - " // Method to calculate the area\n", - " public double calc_area() {\n", - " return this.length * this.width;\n", - " }\n", - "\n", - " // Method to calculate the perimeter\n", - " public double calc_perimeter(){\n", - " return 2*this.length + 2*this.width;\n", - " }\n", - "\n", - " // Method to print the shape\n", - " public void print_shape() {\n", - " System.out.println(\"Shape: \" + this.name);\n", - " }\n", - "\n", - " // Additional method to print something\n", - " public void print_something() {\n", - " System.out.println(\"This is a shape\");\n", - " }\n", - "}\n", - "\n", - "public class Driver {\n", - " public static void main(String[] args) {\n", - " Shape s1 = new Shape();\n", - " }\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "plaintext" - } - }, - "source": [ - "### Creating a Triangle:\n", - "\n", - "Currently Our shape class only takes in length and width parameters. This works fine for squares and rectangles, but what if we wanted to make a different shape? To define a Triangle we can use the 3 side lengths. while still inheriting the same behavior from the base Shape class." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [], - "source": [ - "public class Triangle extends Shape {\n", - " private int side1;\n", - " private int side2;\n", - " private int side3;\n", - "\n", - "\n", - " public Triangle() {\n", - " this.name = \"triangle\";\n", - " this.side1 = 1;\n", - " this.side2 = 2;\n", - " this.side3 = 3;\n", - " }\n", - "\n", - " // Constructor that takes a name and three side lengths\n", - " public Triangle(String name, int s1, int s2, int s3) {\n", - " super(name, 0, 0); // Call to Shape constructor to set the name\n", - " this.name = \"triangle\";\n", - " this.side1 = s1;\n", - " this.side2 = s2;\n", - " this.side3 = s3;\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Here's our Triangle\n", - "\n", - "![](https://github.com/user-attachments/assets/69377fe6-8bf2-497b-98b5-576db179f5ad)\n", - "\n", - "\n", - "As seen above, we're creating a new child class: Triangle\n", - "This class inherits name parameter from the parent shape class and takes in 3 new side length paramiters to define the triangle's geometry.\n", - "\n", - "Lets try to create a new triangle with the side lengths 3, 4, and 5. We can also check to see if we inherited correctly from shape by callign the calc_area and print_shape methods.\n", - "\n", - "Triangle t1 = new Triangle(\"triangle\", 3, 4, 5);\n", - "t1.print_shape();\n", - "System.out.println(\"Area of t1 = \" + t1.calc_area());" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "source": [ - "## We have a problem...\n", - "\n", - "We were able to make a new triangle from the inherited triangle class, however, our area is not being calculated correctly. We inherited the default shape class' calc_area method:\n", - "\n", - "**area = length x width**\n", - "\n", - "This is defaulting to an area of 0 when we create a new triangle without specifying the length and width. Instead, we can use **Heron's formula** to calculate the area of a triangle given 3 side lengths. \n", - "\n", - "**area = sqrt(s(s-s1)(s-s2)(s-s3))** where s is the semi-perimiter **(s1+s2+s3)/2**\n", - "\n", - "## Popcorn Hack 1\n", - "Lets re-define the Triangle class but this time override the default area method with the **Heron's formula**\n" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "metadata": {}, - "outputs": [], - "source": [ - "public class Triangle extends Shape {\n", - " private int side1;\n", - " private int side2;\n", - " private int side3;\n", - "\n", - "\n", - " public Triangle() {\n", - " this.name = \"triangle\";\n", - " this.side1 = 1;\n", - " this.side2 = 2;\n", - " this.side3 = 3;\n", - " }\n", - "\n", - " // Constructor that takes a name and three side lengths\n", - " public Triangle(String name, int s1, int s2, int s3) {\n", - " super(name, 0, 0); // Call to Shape constructor to set the name\n", - " this.name = \"triangle\";\n", - " this.side1 = s1;\n", - " this.side2 = s2;\n", - " this.side3 = s3;\n", - " }\n", - "\n", - " @Override\n", - " public double calc_area() {\n", - " double area = 0.0;\n", - " //Write Code Here\n", - " return area;\n", - " //expected output 6\n", - " }\n", - " \n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "The **@Override** annotation tells Java that the following method will be a method override. If the following method does not override an existing method the compiler will throw an error. This is useful to catch mistakes in method name spelling and ensuring that a method override takes place. The annotation is not necessary, but is good practice. \n", - "\n", - "***Note it is essential to type the name of the function to be overridden exactly**" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Shape: triangle\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Area of t1 = 0.0\n" - ] - } - ], - "source": [ - "Triangle t1 = new Triangle(\"triangle\", 3, 4, 5);\n", - "t1.print_shape();\n", - "System.out.println(\"Area of t1 = \" + t1.calc_area());" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "If done correctly the area of Triangle t1 should be 6." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Important things to note\n", - "1. using the **final** keyword in the parent method will make that method unable to be overridden\n", - "2. methods can be overidden to give more access but cannot restrict acces: private -> public, but not public -> private\n", - "3. use of **@Override** is highly encouraged" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hack 2\n", - "\n", - "re-write the Triangle sublcass so that it also overrides the calc_perimeter()" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [], - "source": [ - "public class Triangle extends Shape {\n", - " private int side1;\n", - " private int side2;\n", - " private int side3;\n", - "\n", - "\n", - " public Triangle() {\n", - " this.name = \"triangle\";\n", - " this.side1 = 1;\n", - " this.side2 = 2;\n", - " this.side3 = 3;\n", - " }\n", - "\n", - " // Constructor that takes a name and three side lengths\n", - " public Triangle(String name, int s1, int s2, int s3) {\n", - " super(name, 0, 0); // Call to Shape constructor to set the name\n", - " this.name = \"triangle\";\n", - " this.side1 = s1;\n", - " this.side2 = s2;\n", - " this.side3 = s3;\n", - " }\n", - "\n", - " @Override\n", - " public double calc_area() {\n", - " double area = 0;\n", - " //your previous area code\n", - " return area;\n", - " }\n", - "\n", - " // Add perimeter method override here\n", - " //expected output 12\n", - " \n", - "}" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0.0\n" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0.0\n" - ] - } - ], - "source": [ - "Triangle ti84 = new Triangle(\"triangle\", 3, 4, 5);\n", - "System.out.println(ti84.calc_area());\n", - "System.out.println(ti84.calc_perimeter());" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Super keyword" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "What if we wanted to create our child triangle class, but also use overridden methods from the parent shape class?\n", - "For example, what if we wanted to print out not only that our shape is a triangle, but also that it is a shape. We could accomplish this with the super keyword." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "This is a shape\n", - "This is a triangle\n", - "Shape: triangle\n" - ] - } - ], - "source": [ - "public class Triangle extends Shape {\n", - " private int side1;\n", - " private int side2;\n", - " private int side3;\n", - "\n", - "\n", - " public Triangle() {\n", - " this.name = \"triangle\";\n", - " this.side1 = 1;\n", - " this.side2 = 2;\n", - " this.side3 = 3;\n", - " }\n", - "\n", - " // Constructor that takes a name and three side lengths\n", - " public Triangle(String name, int s1, int s2, int s3) {\n", - " super(name, 0, 0); // Call to Shape constructor to set the name\n", - " this.name = \"triangle\";\n", - " this.side1 = s1;\n", - " this.side2 = s2;\n", - " this.side3 = s3;\n", - " }\n", - " public void print_shape() {\n", - " super.print_something();\n", - " print_something();\n", - " System.out.println(\"Shape: \" + this.name);\n", - " }\n", - "\n", - "\n", - " @Override\n", - " public void print_something() {\n", - " System.out.println(\"This is a triangle\");\n", - " }\n", - "\n", - "}\n", - "\n", - "Triangle t2 = new Triangle(\"triangle\", 3, 4, 5);\n", - "t2.print_shape();" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "source": [ - "## The Super Keyword\n", - "\n", - "As seen above, using the super.method calls the parent class' method. Something to note is that calling a super method inside annother method will first complete the parent method before moving on to the next line. \n", - "\n", - "As seen above, the parent print something is called first, then the triangle's print something, and lastly print shape. \n", - "\n", - "Something to be aware of is not to call a method in itself without the super keyword. This will cause an error/" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Triangle extends Shape {\n", - " private int side1;\n", - " private int side2;\n", - " private int side3;\n", - "\n", - "\n", - " public Triangle() {\n", - " this.name = \"triangle\";\n", - " this.side1 = 1;\n", - " this.side2 = 2;\n", - " this.side3 = 3;\n", - " }\n", - "\n", - " // Constructor that takes a name and three side lengths\n", - " public Triangle(String name, int s1, int s2, int s3) {\n", - " super(name, 0, 0); // Call to Shape constructor to set the name\n", - " this.name = \"triangle\";\n", - " this.side1 = s1;\n", - " this.side2 = s2;\n", - " this.side3 = s3;\n", - " }\n", - " public void print_shape() {\n", - " print_shape();\n", - " }\n", - "\n", - "\n", - " @Override\n", - " public void print_something() {\n", - " System.out.println(\"This is a triangle\");\n", - " }\n", - "\n", - "}\n", - "\n", - "Triangle t2 = new Triangle(\"triangle\", 3, 4, 5);\n", - "t2.print_shape();" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "As seen above, this results in an infinite loop" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "java (IJava/j!)", - "language": "java", - "name": "jbang-ijava" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "22.0.2" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.6.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.6.ipynb deleted file mode 100644 index 2b056db925..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.6.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "8239df1c", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Object-References]\n", - "lesson_language: Java\n", - "lesson_topic: Object-References\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Methods Passing and Returning References of an Object\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_6\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.7.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.7.ipynb deleted file mode 100644 index cc964e757c..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.7.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "0cbccff1", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Class-Variables-and-Methods]\n", - "lesson_language: Java\n", - "lesson_topic: Class-Variables-and-Methods\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Class Variables and Methods\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_7\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.8.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.8.ipynb deleted file mode 100644 index 034970ee54..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.8.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "141a509d", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Scope-and-Access]\n", - "lesson_language: Java\n", - "lesson_topic: Scope-and-Access\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Scope and Access\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_8\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.9.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.9.ipynb deleted file mode 100644 index aef24c7bd8..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-3.9.ipynb +++ /dev/null @@ -1,608 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, This-Keyword]\n", - "lesson_language: Java\n", - "lesson_topic: This-Keyword\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: this Keyword\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/3_9\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Polymorphism" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Learning Targets:\n", - "* What is Polymorphism\n", - "* Difference between Static and Dynamic Data Types\n", - "* Compile Time vs Run time" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "***" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "* \"A reference variable is **polymorphic** when it can refer to objects of different classes in the code\"\n", - "* \"A method is **polymorphic** when it is overriden in at least one subclass\"\n", - "* \"**Polymorphism** is the act of executing an overriden ```non-static``` method from the correct class at runtime based on the actual object type\"" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "public class Shape {\n", - " protected String name;\n", - " private int length;\n", - " private int width;\n", - "\n", - " // Parameterized constructor\n", - " public Shape(String name, int length, int width) {\n", - " this.name = name;\n", - " this.length = length;\n", - " this.width = width;\n", - " }\n", - "\n", - " // Method to calculate the area\n", - " public double calc_area() {\n", - " return this.length * this.width;\n", - " }\n", - "}\n", - "\n", - "public class Triangle extends Shape {\n", - " private int side1;\n", - " private int side2;\n", - " private int side3;\n", - "\n", - " // Constructor that takes a name and three side lengths\n", - " public Triangle(String name, int s1, int s2, int s3) {\n", - " super(name, 0, 0); // Call to Shape constructor to set the name\n", - " this.name = \"triangle\";\n", - " this.side1 = s1;\n", - " this.side2 = s2;\n", - " this.side3 = s3;\n", - " }\n", - "\n", - " @Override\n", - " public double calc_area() {\n", - " double s = (side1 + side2 + side3) / 2.0; // Semi-perimeter\n", - " return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));\n", - " }\n", - "}\n", - "\n", - "//creates a \"Shape\" class using a \"Triangle\" constructor\n", - "Shape triangle = new Triangle(\"Equilateral\",1,1,1); \n", - "// Therefore the calc_area is overriden\n", - "System.out.println(triangle.calc_area()); " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## How Does This Work?\n", - "\n", - "<img width=\"441\" alt=\"Screenshot 2024-09-24 at 3 41 23 PM\" src=\"https://github.com/user-attachments/assets/11a11c1e-df70-4b9d-9d40-fc0720363d30\">\n", - "\n", - "\n", - "Let's start with this line:\n", - "``` Shape myObject = new Triangle();```\n", - "\n", - "It may seem like you are magically creating a Shape Object with the Triangle, but you are not. Instead you actually are creating a Triangle Object. The difference is that the Shape variable is referencing the Shape parts of the Triangle.\n", - "* \"A reference variable can store a refernece to its declared class or any subclass of its declared class\"\n", - "\n", - "\n", - "This also means that if the data type is the SuperClass and you try to call a method that doesn't exist in the SuperClass, it will return an error. But you can cast the variable to the SubClass because the refrence is the SubClass. After casting if you call a method that is only in the subclass then it won't return an error.\n", - "\n", - "Next running methods:\n", - "```myObject.calc_area() == Triangle.calc_area();```\n", - "\n", - "When you run a method that the Shape has, it starts at the referenced object and checks if there is an override, if not it moves up the ancestry chain until it either finds an override or finds the orginal method." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hacks\n", - "* Create an example of Polymorphism in your own project.\n", - "\n", - "If you want some more information and examples of Polymorphism see the examples further down" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Static vs Dynamic Types" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**static types**: static types is simply the type.\n", - "\n", - "**dynamic types**: dynamic type is the type of the value during runtime" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Shape {\n", - " String getName(){\n", - " return \"Shape\"\n", - " }\n", - "}\n", - "\n", - "class Square extends Shape{\n", - " @Override\n", - " String getName(){\n", - " return \"Square\"\n", - " }\n", - "}\n", - "\n", - "Shape myShape = new Square();" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<img width=\"643\" alt=\"Screenshot 2024-09-24 at 3 41 56 PM\" src=\"https://github.com/user-attachments/assets/2cf84906-8a22-4c0d-aa4f-096e85eb822c\">" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Shape** is a static type, but at runtime ```myShape``` is referencing **Sqaure**, so my ```myShape``` is the dynamic type of **Square**.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hacks\n", - "\n", - "Using your previous polymorphism example, explain which parts are the static types and which are the dynamic types\n", - "\n", - "*Read [this](https://www.cs.cornell.edu/courses/JavaAndDS/files/staticType.pdf) for more information*" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Compile-Time vs Run-Time methods" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "Compile time is when you are writing your code. Once you have written your code it is *compiled* into something the computer can run.\n", - "\n", - "Run-time is when you are actually running the code. This is after the compiler is complete and when the code starts exectuting.\n", - "\n", - "There are some differences between Compile-Time and Run-Time. The case we will be going over breifly is the difference in methods. When you create a Shape with a Square you can't run the methods built solely into the square, it must be methods from the shape first. **But why?**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "This is the difference between Compile-Time and Run-Time\n", - "\n", - "During Runtime: \n", - "When you are creating a dynamic reference of a different with a type than the static type, it searches the superclass for the attributes of the static type, then overrides any that the child has overriden. But it doesn't include the methods from the child.\n", - "\n", - "So basically even if you have methods that exist on the referenced object, in run-time those methods may be ignored because the static type doesn't include them.\n", - "\n", - "If you want to run a method that is only in the child class then you can use **down-casting**." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Shape {\n", - " String getName(){\n", - " return \"Shape\";\n", - " }\n", - "}\n", - "\n", - "class Square extends Shape{\n", - " @Override\n", - " String getName(){\n", - " return \"Square\";\n", - " }\n", - "\n", - " int getSides(){\n", - " return 4;\n", - " }\n", - "}\n", - "\n", - "Shape myShape = new Square(); //this does not have access to the Sqaure methods despite referencing a sqaure\n", - "\n", - "Square mySquare = (Square)myShape; //down-cast the Shape to a Sqaure to run the Sqaure specific methods\n", - "System.out.println(mySquare.getSides());//after down-casting you can now run the Square methods" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<img width=\"366\" alt=\"Screenshot 2024-09-24 at 3 40 55 PM\" src=\"https://github.com/user-attachments/assets/08415e0b-0bbc-403d-be4c-e16731e08ad2\">\n" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hacks\n", - "* Define **down-casting** in your own words\n", - "* add an example of down-casting to your previous polymorphism example" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "***\n", - "***" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Examples of Polymorphism and the effects\n", - "Here are some examples of Polymorphism." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "1- Executing the overriden method from the referenced subclass in the datatype of the superclass." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Water {\n", - " public String typeOfWater(){\n", - " return \"water\";\n", - " }\n", - "}\n", - "\n", - "class Lake extends Water {\n", - " @Override\n", - " public String typeOfWater(){\n", - " return \"lake\";\n", - " }\n", - "}\n", - "\n", - "//creates a \"Water\" class using a \"Lake\" constructor\n", - "Water lake = new Lake(); \n", - "// Therefore the typeOfWater method is overriden\n", - "System.out.println(lake.typeOfWater()); " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "2- You can pass a subclass into an argument that is asking for the parent class. " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Shape{\n", - " public int getSize(){\n", - " return 1;\n", - " }\n", - "}\n", - "\n", - "class Square extends Shape{\n", - " @Override\n", - " public int getSize(){\n", - " return 2;\n", - " }\n", - "}\n", - "\n", - "int getSizePlusOne(Shape s){ //argument of class \"Shape\"\n", - " return s.getSize() +1;\n", - "}\n", - "\n", - "Shape myShape = new Shape();\n", - "//passes through a \"Shape\"\n", - "System.out.println(getSizePlusOne(myShape)); \n", - "\n", - "Square mySquare = new Square();\n", - "//passes through a \"Square\" as a \"Shape\" with the square's \"getSize()\" method\n", - "System.out.println(getSizePlusOne(mySquare)); " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "3- You can cast from the superclass to the subclass (**down-casting**). The superclass **must** be referencing the subclass." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Electronic{\n", - " public void playSound(){\n", - " System.out.println(\"Beep boop\");\n", - " }\n", - "}\n", - "\n", - "class Computer extends Electronic{\n", - " @Override\n", - " public void playSound(){\n", - " System.out.println(\"Click clack\");\n", - " }\n", - "}\n", - "\n", - "//creates a \"Electronic\" class using a \"Computer\" constructor\n", - "Electronic device = new Computer(); \n", - "\n", - "//casts the \"Electronic\" to a \"Computer\"\n", - "Computer computer = (Computer)device; \n", - "\n", - "computer.playSound();" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Electronic{\n", - " public void playSound(){\n", - " System.out.println(\"Beep boop\");\n", - " }\n", - "}\n", - "\n", - "class Computer extends Electronic{\n", - " @Override\n", - " public void playSound(){\n", - " System.out.println(\"Click clack\");\n", - " }\n", - "}\n", - "\n", - "Electronic device = new Electronic(); //creates a \"Electronic\" class using a \"Electronic\" constructor\n", - "\n", - "Computer computer = (Computer)device; //cannot cast the \"Electronic\" to a \"Computer\"" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "4- Down-casting doesn't mean changing the reference to the obejct, so polymorphism will still apply" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Furniture{\n", - " String getName(){\n", - " return \"Furniture\";\n", - " }\n", - "}\n", - "\n", - "class Table extends Furniture{\n", - " @Override\n", - " String getName(){\n", - " return \"Table\";\n", - " }\n", - "}\n", - "\n", - "class CoffeeTable extends Table{\n", - " @Override\n", - " String getName(){\n", - " return super.getName() + \" Coffee\";\n", - " }\n", - "}\n", - "\n", - "Furniture myTable = new CoffeeTable();\n", - " //runs \"CoffeeTable\" method\n", - "System.out.println(myTable.getName());\n", - "\n", - "Table myOtherTable = (Table)myTable;\n", - "//method exectuted doesn't change despite casting-down\n", - "System.out.println(myOtherTable.getName()); " - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "5- you can cast upward and polymorphic behaviour will apply." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Sport{\n", - " public int numberOfPlayers(){\n", - " return (int)Double.NaN; //ends up being 0 but whatever\n", - " }\n", - " public String name(){\n", - " return \"Sport\";\n", - " }\n", - "}\n", - "\n", - "class Soccer extends Sport{\n", - " @Override\n", - " public int numberOfPlayers(){\n", - " return 11;\n", - " }\n", - " @Override\n", - " public String name(){\n", - " return \"Soccer\";\n", - " }\n", - "}\n", - "\n", - "//creates a a soccer object\n", - "Soccer mySoccer = new Soccer();\n", - "\n", - "Sport mySoccerSport = (Sport)mySoccer;\n", - "System.out.println(mySoccerSport.numberOfPlayers());" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Polymorphism with the Object class\n", - "* see the lesson 9.7 about [Object Superclass](linkHere)\n", - "\n", - "Polymorphism also applies with the **Object Superclass**.\n", - "Techically any class or object is an ```Object```." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "class Fruit{\n", - " @Override\n", - " public String toString(){\n", - " return \"I'm a Fruit!\";\n", - " }\n", - "}\n", - "class Banana extends Fruit{\n", - " @Override\n", - " public boolean equals(Object obj){ //overrides the equals\n", - " return true;\n", - " }\n", - "}\n", - "\n", - "\n", - "Object banana = new Banana();\n", - "System.out.println(banana.toString());\n", - "//if \".equals()\" was not overriden from the \"Object\" this should always return false\n", - "System.out.println(banana.equals(null)); " - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "17.0.12+7-Ubuntu-1ubuntu222.04" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.1.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.1.ipynb deleted file mode 100644 index 0e14203244..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.1.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "61b924a7", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Data-Collection-Ethics]\n", - "lesson_language: Java\n", - "lesson_topic: Data-Collection-Ethics\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Ethical and Social Issues Around Data Collection\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_1\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.10.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.10.ipynb deleted file mode 100644 index 64a03e81fd..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.10.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "6ef31a64", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, ArrayList-Algorithms]\n", - "lesson_language: Java\n", - "lesson_topic: ArrayList-Algorithms\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Implementing `ArrayList` Algorithms\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_10\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.11.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.11.ipynb deleted file mode 100644 index eee7c3c2a7..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.11.ipynb +++ /dev/null @@ -1,830 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "efcf1717", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Two-Dimensional-Arrays]\n", - "lesson_language: Java\n", - "lesson_topic: Two-Dimensional-Arrays\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: 2D Array Creation and Access\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_11\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "11b9db03", - "metadata": {}, - "source": [ - "## What is a 2D array\n", - "\n", - "A 2D array is an array of arrays.\n", - "\n", - "![image.png](https://github.com/Krishiv111/KPNSTeam/assets/111609656/fc04c520-ec82-414e-897c-0b0753c73f8d)\n", - "\n", - "## Why use 2D arrays?\n", - "\n", - "1D array of people \n", - "```\n", - "{\n", - "\"Patrick Mahomes\"\n", - "\"Mr. Mortensen\"\n", - "\"Taylor Swift\"\n", - "\"Margot Robbie\"\n", - "}\n", - "```\n", - "\n", - "2D array of men and women \n", - "```\n", - "{\n", - "{ \"Patrick Mahomes\", \"Mr. Mortensen\"} ,\n", - "{\"Taylor Swift\", \"Margot Robbie\"}\n", - "}\n", - "```\n", - "\n", - "## Declaring a 2D Array\n", - "\n", - "Very similar to declaring a 1D array.\n", - "\n", - "```\n", - "DataType[] name // 1D array\n", - "DataType[][] name // 2D array\n", - "```\n", - "\n", - "int[][] intArray; //primitive\n", - "String[][] stringArray; //object\n", - "## Initalizing a 2D Array\n", - "\n", - "public class TwoDArrayExample {\n", - " public static void main(String[] args) {\n", - " int rows = 3;\n", - " int cols = 4;\n", - " \n", - " // Declare and initialize a 2D array\n", - " int[][] myArray = {\n", - " {1, 2, 3, 4},\n", - " {5, 6, 7, 8},\n", - " {9, 10, 11, 12}\n", - " };\n", - " \n", - " // Access and print elements\n", - " for (int i = 0; i < rows; i++) {\n", - " for (int j = 0; j < cols; j++) {\n", - " System.out.print(myArray[i][j] + \" \");\n", - " }\n", - " System.out.println();\n", - " }\n", - " }\n", - "}\n", - "TwoDArrayExample.main(null)\n", - "# Popcorn HACK 1\n", - "public class TwoDArrayHack1 {\n", - " public static void main(String[] args) {\n", - " // Declare and initialize a 2D array with 5 rows (arrays) and 4 columns (elements per array) of int data type.\n", - " }\n", - "\n", - "}\n", - "# More Initializing and Accessing Array Elements of a 2D Array\n", - "class Student {\n", - " private String name;\n", - " private int age;\n", - "\n", - " // Constructor to initialize a Student object\n", - " public Student(String name, int age) {\n", - " this.name = name;\n", - " this.age = age;\n", - " }\n", - "\n", - " // Getter method to retrieve the student's name\n", - " public String getName() {\n", - " return name;\n", - " }\n", - "\n", - " // Getter method to retrieve the student's age\n", - " public int getAge() {\n", - " return age;\n", - " }\n", - "\n", - " // Method to print student information\n", - " public void printInfo() {\n", - " System.out.println(\"Name: \" + name);\n", - " System.out.println(\"Age: \" + age);\n", - " }\n", - "}\n", - "\n", - "public class TwoDArrayHack2 {\n", - " public static void main(String[] args) {\n", - " // Declare and initialize a 2D array with 6 rows and 6 columns of Student objects\n", - " Student[][] studentArray = new Student[6][6];\n", - "\n", - " // Creating and initializing Student objects in the array\n", - " studentArray[0][0] = new Student(\"Yuri\", 16);\n", - " studentArray[1][2] = new Student(\"Gorlcok\", 135);\n", - "\n", - " // Accessing and using the Student objects' methods\n", - " String studentName = studentArray[0][0].getName();\n", - " int studentAge = studentArray[0][0].getAge();\n", - "\n", - " System.out.println(\"Student Name: \" + studentName);\n", - " System.out.println(\"Student Age: \" + studentAge);\n", - "\n", - " studentArray[1][2].printInfo();\n", - " }\n", - "}\n", - "TwoDArrayHack2.main(null)\n", - "# More Initializing + Accessing + Popcorn HACK 2\n", - "class NFLTeams {\n", - " private String teamName;\n", - " private String city;\n", - " private int championships;\n", - "\n", - " // Constructor to initialize NFL team data\n", - " public NFLTeams(String teamName, String city, int championships) {\n", - " this.teamName = teamName;\n", - " this.city = city;\n", - " this.championships = championships;\n", - " }\n", - "\n", - " // Method to display team information\n", - " public void displayTeamInfo() {\n", - " System.out.println(\"Team: \" + teamName);\n", - " System.out.println(\"City: \" + city);\n", - " System.out.println(\"Championships: \" + championships);\n", - " }\n", - "}\n", - "\n", - "public class NFLTeams2DArray {\n", - " public static void main(String[] args) {\n", - " // Declare a 2D array of NFLTeams to store data for 5 teams and 5 columns\n", - " NFLTeams[][] nflArray = {\n", - " {new NFLTeams(\"Team1\", \"City1\", 2), new NFLTeams(\"Team2\", \"City2\", 3), new NFLTeams(\"Team3\", \"City3\", 1), new NFLTeams(\"Team4\", \"City4\", 0), new NFLTeams(\"Team5\", \"City5\", 5)},\n", - " {new NFLTeams(\"Team6\", \"City6\", 3), new NFLTeams(\"Team7\", \"City7\", 4), new NFLTeams(\"Team8\", \"City8\", 0), new NFLTeams(\"Team9\", \"City9\", 1), new NFLTeams(\"Team10\", \"City10\", 2)},\n", - " {new NFLTeams(\"Team11\", \"City11\", 1), new NFLTeams(\"Team12\", \"City12\", 0), new NFLTeams(\"Team13\", \"City13\", 3), new NFLTeams(\"Team14\", \"City14\", 2), new NFLTeams(\"Team15\", \"City15\", 4)},\n", - " {new NFLTeams(\"Team16\", \"City16\", 2), new NFLTeams(\"Team17\", \"City17\", 4), new NFLTeams(\"Team18\", \"City18\", 1), new NFLTeams(\"Team19\", \"City19\", 5), new NFLTeams(\"Team20\", \"City20\", 3)},\n", - " {new NFLTeams(\"Team21\", \"City21\", 0), new NFLTeams(\"Team22\", \"City22\", 2), new NFLTeams(\"Team23\", \"City23\", 5), new NFLTeams(\"Team24\", \"City24\", 3), new NFLTeams(\"Team25\", \"City25\", 1)}\n", - " };\n", - "\n", - " // Print out Team 17's Team info\n", - " nflArray[3][1].displayTeamInfo();\n", - " \n", - " // Print out Team 21's Team Info\n", - "\n", - " // Print out Team 3's team Info\n", - "\n", - " }\n", - "}\n", - "NFLTeams2DArray.main(null)\n", - "## Updating 2D Arrays\n", - "public class Update2DArray {\n", - " public static void main(String[] args) {\n", - " // Create a 3x3 2D array of integers\n", - " int[][] matrix = {\n", - " {1, 2, 3},\n", - " {4, 5, 6},\n", - " {7, 8, 9}\n", - " };\n", - "\n", - " // Display the original 2D array\n", - " System.out.println(\"Original 2D Array:\");\n", - " printArray(matrix);\n", - "\n", - " // Update specific elements in the array\n", - " matrix[0][0] = 11; // Update the element in the first row, first column\n", - " matrix[1][1] = 22; // Update the element in the second row, second column\n", - " matrix[2][2] = 33; // Update the element in the third row, third column\n", - "\n", - " // Display the updated 2D array\n", - " System.out.println(\"\\nUpdated 2D Array:\");\n", - " printArray(matrix);\n", - " }\n", - "\n", - " // Helper method to print the 2D array\n", - " public static void printArray(int[][] arr) {\n", - " for (int i = 0; i < arr.length; i++) {\n", - " for (int j = 0; j < arr[i].length; j++) {\n", - " System.out.print(arr[i][j] + \" \");\n", - " }\n", - " System.out.println();\n", - " }\n", - " }\n", - "}\n", - "Update2DArray.main(null)\n", - "\n", - "# Popcorn HACK 3\n", - "public class Update2DArrayHACK {\n", - "\n", - " // Helper method to print the 2D integer array\n", - " public static void printIntArray(int[][] arr) {\n", - " for (int i = 0; i < arr.length; i++) {\n", - " for (int j = 0; j < arr[i].length; j++) {\n", - " System.out.print(arr[i][j] + \" \");\n", - " }\n", - " System.out.println();\n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - "\n", - " // Declare and Initialize a 2D integer array with the same dimensions (5x5)\n", - " int[][] integerArray = {\n", - " {1, 2, 3, 4, 5},\n", - " {6, 7, 8, 9, 10},\n", - " {11, 12, 13, 14, 15},\n", - " {16, 17, 18, 19, 20},\n", - " {21, 22, 23, 24, 25}\n", - " };\n", - "\n", - " // Update the element in the first row, first column to 250\n", - " // Update the element in the third row, third column to 69\n", - " // Update the element in the fifth row, fifth column to 96\n", - " // Update the element in the first row, fifth column to 125\n", - " // Update the element in the second row, third column to 135 \n", - "\n", - " // Display the updated 2D integer array\n", - " printIntArray(integerArray);\n", - " }\n", - "}\n", - "Update2DArrayHACK.main(null)\n", - "## Popcorn HACK 4 - Review Quiz\n", - "\n", - "```\n", - "What is a 2D array?\n", - "A. A single row of elements.\n", - "B. A data structure with rows and columns.\n", - "C. A list of 2 elements.\n", - "D. A binary representation of data.\n", - "\n", - "How do you declare a 2D array in Java?\n", - "A. int myArray = new int[3][3];\n", - "B. 2DArray myArray = new 2DArray[3][3];\n", - "C. int[][] myArray;\n", - "D. myArray = declare 2D array;\n", - "\n", - "How do you access an element in a 2D array at row 2 and column 3?\n", - "A. myArray[3][2]\n", - "B. myArray[2][3]\n", - "C. myArray[1][2]\n", - "D. myArray[2][1]\n", - "\n", - "What is the purpose of initializing a 2D array?\n", - "A. To specify its data type.\n", - "B. To allocate memory for the array.\n", - "C. To access its elements.\n", - "D. To declare the number of rows and columns.\n", - "\n", - "In a 2D array, what does myArray[2][3] represent?\n", - "A. The element in the second row and third column.\n", - "B. The element in the third row and second column.\n", - "C. The element in the third row and third column.\n", - "D. The element in the second column and third row.\n", - "\n", - "What happens when you update an element in a 2D array in Java?\n", - "A. The entire array is cleared.\n", - "B. Only the updated element is affected.\n", - "C. The entire row is shifted.\n", - "D. The element is removed from the array.\n", - "\n", - "Which of the following represents a 2D array with 4 rows and 3 columns in Java?\n", - "A. int[4][3] myArray;\n", - "B. myArray[4,3] = int;\n", - "C. int[3][4] myArray;\n", - "D. myArray[3][4] = int;\n", - "```\n", - "## HACKS\n", - "## Finish Popcorn HACKS, type DONE Here when you finish\n", - "\n", - "## HACK 1\n", - "- Create a class (for object 2D arrays), and declare and initialize a 2D array\n", - "- Show updating a 2D array with object functionality\n", - "## Traversing\n", - "- Traversing is known to acsess each element in a array also known as itteration, in the case of 2D Arrays we will acsess elements in the 2D array, but we will need to use specfiic methods of nested for loops, and enhanced for loops.\n", - "# Nested For Loop\n", - "- A nested for loop is a type of loop that contains an inner loop and outer loop, allowing to create a two dimensional piece that will now allow us to traverse through 2D Arrays.\n", - "public class NestedLoops {\n", - " public static void main(String[] args) {\n", - " for (int outer = 1; outer < 5; outer++) {\n", - " for (int inner = 1; inner < 3; inner++) {\n", - " System.out.print(inner + \" \");\n", - " }\n", - " System.out.println();\n", - " }\n", - " }\n", - "}\n", - "NestedLoops.main(null)\n", - "# Enhanced For Loop\n", - "\n", - "public class EnhancedForLoopExample {\n", - " public static void main(String[] args) {\n", - " String[] fruits = {\"Apple\", \"Banana\", \"Cherry\", \"Date\", \"Fig\"};\n", - "\n", - " // Here you use a en enhanced for loop to itterate through the array of strings\n", - " for (String fruit : fruits) {\n", - " System.out.println(fruit);\n", - " }\n", - " }\n", - "}\n", - "EnhancedForLoopExample.main(null)\n", - "## Cumulative Knowledge \n", - "- Hint: Popcorn Hacks\n", - "- From the class discussion fill these out\n", - "\n", - "- **What does traverse mean?**\n", - "- **What is a nested loop**\n", - "- **What is an enhanced for loop**\n", - "# Nested Loops traversing through a 2D Array\n", - "public class TwoDArrayTraversal {\n", - " public static void main(String[] args) {\n", - " // First Create the 2D array\n", - " int[][] twoDArray = {\n", - " {1, 2, 3},\n", - " {4, 5, 6},\n", - " {7, 8, 9}\n", - " };\n", - " \n", - " // Using a Nested loops to traverse the 2D array\n", - " for (int row = 0; row < 3; row++) {\n", - " for (int col = 0; col < 3; col++) {\n", - " int element = twoDArray[row][col];\n", - " System.out.print(element + \" \");\n", - " }\n", - " System.out.println(); \n", - " }\n", - " }\n", - "}\n", - "TwoDArrayTraversal.main(null)\n", - "### Popcorn Hack\n", - "- What would you replace the question marks with if we didnt know the dimensions of this 2D Array\n", - "public class TwoDArrayTraversal {\n", - " public static void main(String[] args) {\n", - " // First Create the 2D array\n", - " int[][] twoDArray = {\n", - " {1, 2, 3},\n", - " {4, 5, 6},\n", - " {7, 8, 9}\n", - " };\n", - " \n", - " // Using a Nested loops to traverse the 2D array\n", - " for (int row = 0; row < ???; row++) { //grid makes sense becuase it gives you dimension\n", - " for (int col = 0; col < ???; col++) { // colliumn makes senseas it starts at 0 \n", - " int element = twoDArray[row][col];\n", - " System.out.print(element + \" \");\n", - " }\n", - " System.out.println(); \n", - " }\n", - " }\n", - "}\n", - "TwoDArrayTraversal.main(null)\n", - "### Practice\n", - "- Create a 2D Array Based and Traverse through it using a nested loop based on this problem\n", - "public class 2DPractice {\n", - " public static void main(String[] args) {\n", - " \n", - " int[][] complexIntArray = {\n", - " {1, 2, 3, 4},\n", - " {5, 6, 7, 8},\n", - " {9, 10, 11, 12}\n", - " };\n", - "\n", - " // MISSING CODE HERE \n", - " }\n", - " }\n", - "## Using Enhanced For- Loops to Traverse an Array\n", - "public class EnhancedForLoop2DArray {\n", - " public static void main(String[] args) {\n", - " // Define and initialize a 2D array\n", - " int[][] twoDArray = {\n", - " {1, 2, 3},\n", - " {4, 5, 6},\n", - " {7, 8, 9}\n", - " };\n", - "\n", - " // Use nested enhanced for loops to traverse the 2D array\n", - " for (int[] row : twoDArray) {\n", - " for (int element : row) {\n", - " System.out.print(element + \" \");\n", - " }\n", - " System.out.println(); // Move to the next row\n", - " }\n", - " }\n", - "}\n", - "EnhancedForLoop2DArray.main(null)\n", - "# Row Major Order Vs Column Major Order \n", - "\n", - "- PopCorn Hacks \n", - "\n", - "- **Whats the difference between row major order and column major order**\n", - "public class PrintArray {\n", - " public static void printArray(String[][] grid) {\n", - " for (int row = 0; row < grid.length; row++) {\n", - " for (int col = 0; col < grid[0].length; col++) {\n", - " System.out.print(grid[row][col] + \" \");\n", - " }\n", - " System.out.println(); \n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " String[][] myGrid = {\n", - " {\"A\", \"B\", \"C\"},\n", - " {\"D\", \"E\", \"F\"},\n", - " {\"G\", \"H\", \"I\"}\n", - " };\n", - " printArray(myGrid);\n", - " }\n", - "}\n", - "PrintArray.main(null)\n", - "public class PrintArray {\n", - " public static void printArray(String[][] grid) {\n", - " for (int col = 0; col < grid[0].length; col++) // outer loop for collums switched\n", - " { for (int row = 0; row < grid.length; row++) //notice the outer is switched with the inner loop for rows\n", - " {\n", - " System.out.print(grid[row][col] + \" \");\n", - " }\n", - " System.out.println(); \n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " String[][] myGrid = {\n", - " {\"A\", \"B\", \"C\"},\n", - " {\"D\", \"E\", \"F\"},\n", - " {\"G\", \"H\", \"I\"}\n", - " };\n", - " printArray(myGrid);\n", - " }\n", - "}\n", - "PrintArray.main(null)\n", - "# Practice\n", - "- Print My AP CS A Class Rocks Using a column major traversal.\n", - "public class PrintArray {\n", - " public static void printArray(String[][] grid) {\n", - " for (???) {\n", - " for (???) {\n", - " System.out.print(grid[???][???] + \" \");\n", - " }\n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " String[][] message = {\n", - " {\"My\", \"Ap\", \"Cs\", \"R\"},\n", - " {\"AP\", \"A\", \"Class\", \"o\"},\n", - " {\"C\", \"p\", \" \", \"c\"},\n", - " {\"S\", \" \", \" \", \"k\"},\n", - " {\"s\", \" \", \"s\", \"!\"},\n", - " };\n", - "\n", - " printArray(message);\n", - " }\n", - "}\n", - "\n", - "\n", - "PrintArray.main(null)\n", - "# Algorithms That use 2D Arrays Traversing \n", - "public class SearchExample {\n", - " public static boolean search(String[][] chart, String name) {\n", - " for (int r = 0; r < chart.length; r++) {\n", - " for (int c = 0; c < chart[0].length; c++) {\n", - " if (chart[r][c].equals(name)) {\n", - " return true;\n", - " }\n", - " }\n", - " }\n", - " return false; // Name not found in the array\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " String[][] chart = {\n", - " {\"Alice\", \"Bob\", \"Charlie\"},\n", - " {\"David\", \"Eve\", \"Frank\"},\n", - " {\"Grace\", \"Hannah\", \"Isaac\"}\n", - " };\n", - "\n", - " String nameToSearch = \"Krishiv\";\n", - " boolean found = search(chart, nameToSearch);\n", - "\n", - " if (found) {\n", - " System.out.println(nameToSearch + \" is in the array.\");\n", - " } else {\n", - " System.out.println(nameToSearch + \" is not in the array.\");\n", - " }\n", - " }\n", - "}\n", - "SearchExample.main(null)\n", - "# Hacks 8.2\n", - "- Complete the popcorn hacks \n", - "- Main Hack:\n", - " - Traverse Through a 2D Array Using Any of the following methods that we learned \n", - " - Traverse Through A 2D Array Using Specfically The Collumn Major Order. (Make Sure your using correct type of nested loop )\n", - " - Create your own situration of an Algorthm that needs to traverse a 2D array and then write the code for it \n", - " - Extra: Create an Extra Problem or Go further in depth about something we learned (MUST HAVE CODE FOR CREDIT!)\n", - "# Image Representation with 2D Arrays\n", - "\n", - "Digital images are essentially a collection of small, discrete elements called pixels. Pixels are organized in a 2D grid, where each pixel represents a single point of color or intensity. Each element (pixel) in the 2D array corresponds to one pixel in the image. In a color image, each pixel contains three color components: Red, Green, and Blue (RGB), while in grayscale images, each pixel has a single intensity value.\n", - "## Traversing and Processing an Image\n", - "\n", - "Traversing an image's 2D array involves systematically visiting every pixel in the image grid. This process often uses nested loops, with the outer loop iterating over the rows and the inner loop iterating over the columns. By traversing the array, you gain access to each pixel's information, such as color values or intensity. This structured access is fundamental for various image processing tasks.\n", - "import java.io.*;\n", - "import java.net.URL;\n", - "import javax.imageio.ImageIO; // ImageIO is a class in Java libraries which gives an easy way to use different image formats\n", - "import java.awt.image.BufferedImage; // BufferedImage is a class in Java libraries to help perform operations on images (read + write)\n", - "\n", - "public class ImageProcessing {\n", - " public static void main(String[] args) {\n", - " String imageUrl = \"https://user-images.githubusercontent.com/111609656/277895130-d15b0768-01d9-4522-8ef7-4f8bcf69c42e.png\";\n", - " String outputFolder = \"../images\";\n", - " String customFileName = \"MORT1.png\"; \n", - "\n", - " try {\n", - " String outputPath = outputFolder + File.separator + customFileName;\n", - "\n", - " URL url = new URL(imageUrl); // create URL object\n", - "\n", - " try (InputStream in = url.openStream(); // try-catch block where errors are handled\n", - " OutputStream out = new FileOutputStream(outputPath)) { // input stream reads data and output stream writes the data\n", - "\n", - " byte[] buffer = new byte[1024];\n", - " int bytesRead;\n", - "\n", - " while ((bytesRead = in.read(buffer)) != -1) {\n", - " out.write(buffer, 0, bytesRead);\n", - " } // reading the data from the URL and writes in 1024 byte chunks\n", - " }\n", - "\n", - " System.out.println(\"Image downloaded and saved to: \" + outputPath);\n", - "\n", - " File imageFile = new File(outputPath);\n", - " BufferedImage image = ImageIO.read(imageFile); \n", - " int width = image.getWidth();\n", - " int height = image.getHeight(); // get the image dimensions\n", - "\n", - " System.out.println(\"Success! Image Dimensions (Width x Height): \" + width + \" x \" + height);\n", - "\n", - " // Process the image using a 2D array\n", - " int[][] pixels = new int[width][height];\n", - "\n", - " for (int x = 0; x < width; x++) {\n", - " for (int y = 0; y < height; y++) {\n", - " int pixel = image.getRGB(x, y);\n", - " // Process the pixel here, e.g., apply filters or transformations\n", - " pixels[x][y] = pixel;\n", - " }\n", - " }\n", - "\n", - " // Calculate resolution in pixels per inch (PPI)\n", - " int ppi = (int) (image.getWidth() / (width * 0.0254));\n", - " System.out.println(\"Resolution: \" + ppi + \" pixels per inch (PPI)\");\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "}\n", - "ImageProcessing.main(null)\n", - "## Grayscale Conversion with Images\n", - "\n", - "Grayscale conversion is a fundamental image processing operation. When converting an image to grayscale, you effectively remove color information and retain only the pixel intensity. This is typically done by calculating the average intensity from the RGB components of each pixel. The result is a grayscale image where variations in pixel intensity represent the image's features and details. This operation can serve as a starting point for more complex image processing techniques.\n", - "import java.awt.image.BufferedImage;\n", - "import java.awt.image.ColorConvertOp;\n", - "import java.io.*;\n", - "import java.net.URL;\n", - "import javax.imageio.ImageIO;\n", - "\n", - "public class ImageToGrayscaleWithArray {\n", - " public static void main(String[] args) {\n", - " String imageUrl = \"https://user-images.githubusercontent.com/111609656/277895164-5f93f1d8-88b5-4b08-b9a1-b54fb6d55d96.png\"; // Replace with the actual image URL\n", - " String outputFolder = \"../images\";\n", - " String customFileName = \"MORT2_Grayscale.png\"; // Change this to your desired file name for the grayscale image\n", - "\n", - " try {\n", - " // Define the output file path\n", - " String outputPath = outputFolder + File.separator + customFileName;\n", - "\n", - " // Create a URL object from the image URL\n", - " URL url = new URL(imageUrl);\n", - "\n", - " // Open a connection to the URL and get the input stream\n", - " try (InputStream in = url.openStream();\n", - " OutputStream out = new FileOutputStream(outputPath)) {\n", - "\n", - " // Read data from the URL and save it to the output file\n", - " byte[] buffer = new byte[1024];\n", - " int bytesRead;\n", - "\n", - " while ((bytesRead = in.read(buffer)) != -1) {\n", - " out.write(buffer, 0, bytesRead);\n", - " }\n", - " }\n", - "\n", - " // Read the downloaded image\n", - " BufferedImage originalImage = ImageIO.read(new File(outputPath));\n", - " int width = originalImage.getWidth();\n", - " int height = originalImage.getHeight();\n", - "\n", - " // Create a 2D array to store grayscale values\n", - " int[][] grayscaleArray = new int[width][height];\n", - "\n", - " // Convert the image to grayscale and populate the array\n", - " for (int x = 0; x < width; x++) {\n", - " for (int y = 0; y < height; y++) {\n", - " int pixel = originalImage.getRGB(x, y);\n", - " int red = (pixel >> 16) & 0xFF;\n", - " int green = (pixel >> 8) & 0xFF;\n", - " int blue = pixel & 0xFF;\n", - " int gray = (red + green + blue) / 3;\n", - " grayscaleArray[x][y] = gray;\n", - " }\n", - " }\n", - "\n", - " // Save the grayscale image\n", - " String grayscaleOutputPath = outputFolder + File.separator + customFileName;\n", - " BufferedImage grayscaleImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);\n", - "\n", - " for (int x = 0; x < width; x++) {\n", - " for (int y = 0; y < height; y++) {\n", - " int grayValue = grayscaleArray[x][y];\n", - " int grayPixel = (grayValue << 16) | (grayValue << 8) | grayValue;\n", - " grayscaleImage.setRGB(x, y, grayPixel);\n", - " }\n", - " }\n", - "\n", - " ImageIO.write(grayscaleImage, \"png\", new File(grayscaleOutputPath));\n", - "\n", - " System.out.println(\"Success! Image converted to grayscale, downloaded, and saved to: \" + grayscaleOutputPath);\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "}\n", - "ImageToGrayscaleWithArray.main(null)\n", - "## Image Conversion\n", - "\n", - "\n", - "<br>\n", - "\n", - "\n", - "<b> Why do we Convert Images ? </b>\n", - "\n", - "\n", - "\n", - "#### How Does Image Conversion Work:\n", - "import javax.imageio.ImageIO; // allows you to read and write images in various formats.\n", - "import java.io.File; // allows you to work with files and directories in your file system.\n", - "import java.io.IOException; // allows you to handle input and output exceptions that may occur during file operations.\n", - "import java.awt.image.BufferedImage; // allows you to work with images stored in memory, providing methods to manipulate image data.\n", - "\n", - "public class ImageConverter {\n", - "\n", - " public static void main(String[] args) {\n", - " try {\n", - " // Input and output file paths\n", - " String[] inputPaths = {\n", - " \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/woodworker_mort.png\",\n", - " \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/Mort2.png\"\n", - " };\n", - " String outputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert\";\n", - "\n", - " // Loop through each image in the array\n", - " for (String inputPath : inputPaths) {\n", - " // Read the image\n", - " File inputFile = new File(inputPath);\n", - " BufferedImage img = ImageIO.read(inputFile); // Buffered image is a class in java for handling image data\n", - "\n", - " // Write the image\n", - " String outputFileName = \"converted_\" + new File(inputPath).getName().replace(\".png\", \".gif\");\n", - " String outputFilePath = outputPath + File.separator + outputFileName;\n", - " File outputFile = new File(outputFilePath);\n", - " ImageIO.write(img, \"gif\", outputFile);\n", - "\n", - " System.out.println(\"Image conversion successful for: \" + inputPath);\n", - " }\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "}\n", - "ImageConverter.main(null)\n", - "\n", - "import javax.imageio.ImageIO;\n", - "import java.io.File;\n", - "import java.io.IOException;\n", - "import java.awt.image.BufferedImage;\n", - "\n", - "public class ImageConverter {\n", - "\n", - " public static void main(String[] args) {\n", - " try {\n", - " // Input and output file paths\n", - " String inputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/Mort2.png\";\n", - " String outputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert\";\n", - "\n", - " // Read the PNG image\n", - " BufferedImage img = ImageIO.read(new File(inputPath));\n", - "\n", - " // Convert image to RGB format \n", - " BufferedImage rgbImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);\n", - " rgbImage.createGraphics().drawImage(img, 0, 0, null);\n", - "\n", - " // Define the output file name and path\n", - " String outputFileName = inputPath.substring(inputPath.lastIndexOf(\"/\") + 1).replace(\".png\", \".jpeg\");\n", - " String outputFilePath = outputPath + File.separator + outputFileName;\n", - "\n", - " // Convert and save the image as JPEG\n", - " ImageIO.write(rgbImage, \"jpeg\", new File(outputFilePath));\n", - "\n", - " System.out.println(\"Image conversion successful!\");\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "}\n", - "\n", - "ImageConverter.main(null);\n", - "\n", - "## Scaling the Image\n", - "import javax.imageio.ImageIO;\n", - "import java.awt.*;\n", - "import java.awt.image.BufferedImage;\n", - "import java.io.File;\n", - "import java.io.IOException;\n", - "\n", - "public class ImageScaler {\n", - "\n", - " public static void main(String[] args) {\n", - " try {\n", - " // Input and output file paths\n", - " String inputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/snow_mort.png\";\n", - " String outputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert\";\n", - "\n", - " // Desired width and height of the scaled image\n", - " int scaledWidth = 100;\n", - " int scaledHeight = 100;\n", - "\n", - " // Read the image\n", - " File inputFile = new File(inputPath);\n", - " BufferedImage inputImage = ImageIO.read(inputFile);\n", - "\n", - " // Scale the image\n", - " BufferedImage scaledImage = scaleImage(inputImage, scaledWidth, scaledHeight);\n", - "\n", - " // Write the scaled image\n", - " String outputFileName = \"scaled_\" + new File(inputPath).getName();\n", - " String outputFilePath = outputPath + File.separator + outputFileName;\n", - " File outputFile = new File(outputFilePath);\n", - " ImageIO.write(scaledImage, \"png\", outputFile); \n", - "\n", - " System.out.println(\"Image scaling successful!\");\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "\n", - " public static BufferedImage scaleImage(BufferedImage originalImage, int scaledWidth, int scaledHeight) {\n", - " // Create a new BufferedImage with the desired width and height\n", - " BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());\n", - " \n", - " // g2d more into\n", - " // Create a Graphics2D object and set the rendering hints for scaling\n", - " Graphics2D g2d = scaledImage.createGraphics();\n", - " g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n", - " \n", - " // Draw the original image on the new BufferedImage with the desired width and height\n", - " g2d.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);\n", - " \n", - " // Dispose of the Graphics2D object\n", - " g2d.dispose();\n", - " \n", - " return scaledImage;\n", - " }\n", - "}\n", - "\n", - "ImageScaler.main(null);\n", - "\n", - "## Images Hack\n", - "\n", - "Hack: Create a functioning code in which you convert a PNG image to a JPEG image (make it funny).\n", - "\n", - "# Grading for Hacks\n", - "\n", - "- 0.7 for Completing Lesson Hacks\n", - "- 0.2 for Popcorn Hacks + Practice\n", - "- 0.1 for Doing Extra Work" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.12.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.12.ipynb deleted file mode 100644 index 9251e2302f..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.12.ipynb +++ /dev/null @@ -1,830 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "a1e53cc9", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Two-Dimensional-Array-Traversals]\n", - "lesson_language: Java\n", - "lesson_topic: Two-Dimensional-Array-Traversals\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: 2D Array Traversals\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_12\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "879f3b6e", - "metadata": {}, - "source": [ - "## What is a 2D array\n", - "\n", - "A 2D array is an array of arrays.\n", - "\n", - "![image.png](https://github.com/Krishiv111/KPNSTeam/assets/111609656/fc04c520-ec82-414e-897c-0b0753c73f8d)\n", - "\n", - "## Why use 2D arrays?\n", - "\n", - "1D array of people \n", - "```\n", - "{\n", - "\"Patrick Mahomes\"\n", - "\"Mr. Mortensen\"\n", - "\"Taylor Swift\"\n", - "\"Margot Robbie\"\n", - "}\n", - "```\n", - "\n", - "2D array of men and women \n", - "```\n", - "{\n", - "{ \"Patrick Mahomes\", \"Mr. Mortensen\"} ,\n", - "{\"Taylor Swift\", \"Margot Robbie\"}\n", - "}\n", - "```\n", - "\n", - "## Declaring a 2D Array\n", - "\n", - "Very similar to declaring a 1D array.\n", - "\n", - "```\n", - "DataType[] name // 1D array\n", - "DataType[][] name // 2D array\n", - "```\n", - "\n", - "int[][] intArray; //primitive\n", - "String[][] stringArray; //object\n", - "## Initalizing a 2D Array\n", - "\n", - "public class TwoDArrayExample {\n", - " public static void main(String[] args) {\n", - " int rows = 3;\n", - " int cols = 4;\n", - " \n", - " // Declare and initialize a 2D array\n", - " int[][] myArray = {\n", - " {1, 2, 3, 4},\n", - " {5, 6, 7, 8},\n", - " {9, 10, 11, 12}\n", - " };\n", - " \n", - " // Access and print elements\n", - " for (int i = 0; i < rows; i++) {\n", - " for (int j = 0; j < cols; j++) {\n", - " System.out.print(myArray[i][j] + \" \");\n", - " }\n", - " System.out.println();\n", - " }\n", - " }\n", - "}\n", - "TwoDArrayExample.main(null)\n", - "# Popcorn HACK 1\n", - "public class TwoDArrayHack1 {\n", - " public static void main(String[] args) {\n", - " // Declare and initialize a 2D array with 5 rows (arrays) and 4 columns (elements per array) of int data type.\n", - " }\n", - "\n", - "}\n", - "# More Initializing and Accessing Array Elements of a 2D Array\n", - "class Student {\n", - " private String name;\n", - " private int age;\n", - "\n", - " // Constructor to initialize a Student object\n", - " public Student(String name, int age) {\n", - " this.name = name;\n", - " this.age = age;\n", - " }\n", - "\n", - " // Getter method to retrieve the student's name\n", - " public String getName() {\n", - " return name;\n", - " }\n", - "\n", - " // Getter method to retrieve the student's age\n", - " public int getAge() {\n", - " return age;\n", - " }\n", - "\n", - " // Method to print student information\n", - " public void printInfo() {\n", - " System.out.println(\"Name: \" + name);\n", - " System.out.println(\"Age: \" + age);\n", - " }\n", - "}\n", - "\n", - "public class TwoDArrayHack2 {\n", - " public static void main(String[] args) {\n", - " // Declare and initialize a 2D array with 6 rows and 6 columns of Student objects\n", - " Student[][] studentArray = new Student[6][6];\n", - "\n", - " // Creating and initializing Student objects in the array\n", - " studentArray[0][0] = new Student(\"Yuri\", 16);\n", - " studentArray[1][2] = new Student(\"Gorlcok\", 135);\n", - "\n", - " // Accessing and using the Student objects' methods\n", - " String studentName = studentArray[0][0].getName();\n", - " int studentAge = studentArray[0][0].getAge();\n", - "\n", - " System.out.println(\"Student Name: \" + studentName);\n", - " System.out.println(\"Student Age: \" + studentAge);\n", - "\n", - " studentArray[1][2].printInfo();\n", - " }\n", - "}\n", - "TwoDArrayHack2.main(null)\n", - "# More Initializing + Accessing + Popcorn HACK 2\n", - "class NFLTeams {\n", - " private String teamName;\n", - " private String city;\n", - " private int championships;\n", - "\n", - " // Constructor to initialize NFL team data\n", - " public NFLTeams(String teamName, String city, int championships) {\n", - " this.teamName = teamName;\n", - " this.city = city;\n", - " this.championships = championships;\n", - " }\n", - "\n", - " // Method to display team information\n", - " public void displayTeamInfo() {\n", - " System.out.println(\"Team: \" + teamName);\n", - " System.out.println(\"City: \" + city);\n", - " System.out.println(\"Championships: \" + championships);\n", - " }\n", - "}\n", - "\n", - "public class NFLTeams2DArray {\n", - " public static void main(String[] args) {\n", - " // Declare a 2D array of NFLTeams to store data for 5 teams and 5 columns\n", - " NFLTeams[][] nflArray = {\n", - " {new NFLTeams(\"Team1\", \"City1\", 2), new NFLTeams(\"Team2\", \"City2\", 3), new NFLTeams(\"Team3\", \"City3\", 1), new NFLTeams(\"Team4\", \"City4\", 0), new NFLTeams(\"Team5\", \"City5\", 5)},\n", - " {new NFLTeams(\"Team6\", \"City6\", 3), new NFLTeams(\"Team7\", \"City7\", 4), new NFLTeams(\"Team8\", \"City8\", 0), new NFLTeams(\"Team9\", \"City9\", 1), new NFLTeams(\"Team10\", \"City10\", 2)},\n", - " {new NFLTeams(\"Team11\", \"City11\", 1), new NFLTeams(\"Team12\", \"City12\", 0), new NFLTeams(\"Team13\", \"City13\", 3), new NFLTeams(\"Team14\", \"City14\", 2), new NFLTeams(\"Team15\", \"City15\", 4)},\n", - " {new NFLTeams(\"Team16\", \"City16\", 2), new NFLTeams(\"Team17\", \"City17\", 4), new NFLTeams(\"Team18\", \"City18\", 1), new NFLTeams(\"Team19\", \"City19\", 5), new NFLTeams(\"Team20\", \"City20\", 3)},\n", - " {new NFLTeams(\"Team21\", \"City21\", 0), new NFLTeams(\"Team22\", \"City22\", 2), new NFLTeams(\"Team23\", \"City23\", 5), new NFLTeams(\"Team24\", \"City24\", 3), new NFLTeams(\"Team25\", \"City25\", 1)}\n", - " };\n", - "\n", - " // Print out Team 17's Team info\n", - " nflArray[3][1].displayTeamInfo();\n", - " \n", - " // Print out Team 21's Team Info\n", - "\n", - " // Print out Team 3's team Info\n", - "\n", - " }\n", - "}\n", - "NFLTeams2DArray.main(null)\n", - "## Updating 2D Arrays\n", - "public class Update2DArray {\n", - " public static void main(String[] args) {\n", - " // Create a 3x3 2D array of integers\n", - " int[][] matrix = {\n", - " {1, 2, 3},\n", - " {4, 5, 6},\n", - " {7, 8, 9}\n", - " };\n", - "\n", - " // Display the original 2D array\n", - " System.out.println(\"Original 2D Array:\");\n", - " printArray(matrix);\n", - "\n", - " // Update specific elements in the array\n", - " matrix[0][0] = 11; // Update the element in the first row, first column\n", - " matrix[1][1] = 22; // Update the element in the second row, second column\n", - " matrix[2][2] = 33; // Update the element in the third row, third column\n", - "\n", - " // Display the updated 2D array\n", - " System.out.println(\"\\nUpdated 2D Array:\");\n", - " printArray(matrix);\n", - " }\n", - "\n", - " // Helper method to print the 2D array\n", - " public static void printArray(int[][] arr) {\n", - " for (int i = 0; i < arr.length; i++) {\n", - " for (int j = 0; j < arr[i].length; j++) {\n", - " System.out.print(arr[i][j] + \" \");\n", - " }\n", - " System.out.println();\n", - " }\n", - " }\n", - "}\n", - "Update2DArray.main(null)\n", - "\n", - "# Popcorn HACK 3\n", - "public class Update2DArrayHACK {\n", - "\n", - " // Helper method to print the 2D integer array\n", - " public static void printIntArray(int[][] arr) {\n", - " for (int i = 0; i < arr.length; i++) {\n", - " for (int j = 0; j < arr[i].length; j++) {\n", - " System.out.print(arr[i][j] + \" \");\n", - " }\n", - " System.out.println();\n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - "\n", - " // Declare and Initialize a 2D integer array with the same dimensions (5x5)\n", - " int[][] integerArray = {\n", - " {1, 2, 3, 4, 5},\n", - " {6, 7, 8, 9, 10},\n", - " {11, 12, 13, 14, 15},\n", - " {16, 17, 18, 19, 20},\n", - " {21, 22, 23, 24, 25}\n", - " };\n", - "\n", - " // Update the element in the first row, first column to 250\n", - " // Update the element in the third row, third column to 69\n", - " // Update the element in the fifth row, fifth column to 96\n", - " // Update the element in the first row, fifth column to 125\n", - " // Update the element in the second row, third column to 135 \n", - "\n", - " // Display the updated 2D integer array\n", - " printIntArray(integerArray);\n", - " }\n", - "}\n", - "Update2DArrayHACK.main(null)\n", - "## Popcorn HACK 4 - Review Quiz\n", - "\n", - "```\n", - "What is a 2D array?\n", - "A. A single row of elements.\n", - "B. A data structure with rows and columns.\n", - "C. A list of 2 elements.\n", - "D. A binary representation of data.\n", - "\n", - "How do you declare a 2D array in Java?\n", - "A. int myArray = new int[3][3];\n", - "B. 2DArray myArray = new 2DArray[3][3];\n", - "C. int[][] myArray;\n", - "D. myArray = declare 2D array;\n", - "\n", - "How do you access an element in a 2D array at row 2 and column 3?\n", - "A. myArray[3][2]\n", - "B. myArray[2][3]\n", - "C. myArray[1][2]\n", - "D. myArray[2][1]\n", - "\n", - "What is the purpose of initializing a 2D array?\n", - "A. To specify its data type.\n", - "B. To allocate memory for the array.\n", - "C. To access its elements.\n", - "D. To declare the number of rows and columns.\n", - "\n", - "In a 2D array, what does myArray[2][3] represent?\n", - "A. The element in the second row and third column.\n", - "B. The element in the third row and second column.\n", - "C. The element in the third row and third column.\n", - "D. The element in the second column and third row.\n", - "\n", - "What happens when you update an element in a 2D array in Java?\n", - "A. The entire array is cleared.\n", - "B. Only the updated element is affected.\n", - "C. The entire row is shifted.\n", - "D. The element is removed from the array.\n", - "\n", - "Which of the following represents a 2D array with 4 rows and 3 columns in Java?\n", - "A. int[4][3] myArray;\n", - "B. myArray[4,3] = int;\n", - "C. int[3][4] myArray;\n", - "D. myArray[3][4] = int;\n", - "```\n", - "## HACKS\n", - "## Finish Popcorn HACKS, type DONE Here when you finish\n", - "\n", - "## HACK 1\n", - "- Create a class (for object 2D arrays), and declare and initialize a 2D array\n", - "- Show updating a 2D array with object functionality\n", - "## Traversing\n", - "- Traversing is known to acsess each element in a array also known as itteration, in the case of 2D Arrays we will acsess elements in the 2D array, but we will need to use specfiic methods of nested for loops, and enhanced for loops.\n", - "# Nested For Loop\n", - "- A nested for loop is a type of loop that contains an inner loop and outer loop, allowing to create a two dimensional piece that will now allow us to traverse through 2D Arrays.\n", - "public class NestedLoops {\n", - " public static void main(String[] args) {\n", - " for (int outer = 1; outer < 5; outer++) {\n", - " for (int inner = 1; inner < 3; inner++) {\n", - " System.out.print(inner + \" \");\n", - " }\n", - " System.out.println();\n", - " }\n", - " }\n", - "}\n", - "NestedLoops.main(null)\n", - "# Enhanced For Loop\n", - "\n", - "public class EnhancedForLoopExample {\n", - " public static void main(String[] args) {\n", - " String[] fruits = {\"Apple\", \"Banana\", \"Cherry\", \"Date\", \"Fig\"};\n", - "\n", - " // Here you use a en enhanced for loop to itterate through the array of strings\n", - " for (String fruit : fruits) {\n", - " System.out.println(fruit);\n", - " }\n", - " }\n", - "}\n", - "EnhancedForLoopExample.main(null)\n", - "## Cumulative Knowledge \n", - "- Hint: Popcorn Hacks\n", - "- From the class discussion fill these out\n", - "\n", - "- **What does traverse mean?**\n", - "- **What is a nested loop**\n", - "- **What is an enhanced for loop**\n", - "# Nested Loops traversing through a 2D Array\n", - "public class TwoDArrayTraversal {\n", - " public static void main(String[] args) {\n", - " // First Create the 2D array\n", - " int[][] twoDArray = {\n", - " {1, 2, 3},\n", - " {4, 5, 6},\n", - " {7, 8, 9}\n", - " };\n", - " \n", - " // Using a Nested loops to traverse the 2D array\n", - " for (int row = 0; row < 3; row++) {\n", - " for (int col = 0; col < 3; col++) {\n", - " int element = twoDArray[row][col];\n", - " System.out.print(element + \" \");\n", - " }\n", - " System.out.println(); \n", - " }\n", - " }\n", - "}\n", - "TwoDArrayTraversal.main(null)\n", - "### Popcorn Hack\n", - "- What would you replace the question marks with if we didnt know the dimensions of this 2D Array\n", - "public class TwoDArrayTraversal {\n", - " public static void main(String[] args) {\n", - " // First Create the 2D array\n", - " int[][] twoDArray = {\n", - " {1, 2, 3},\n", - " {4, 5, 6},\n", - " {7, 8, 9}\n", - " };\n", - " \n", - " // Using a Nested loops to traverse the 2D array\n", - " for (int row = 0; row < ???; row++) { //grid makes sense becuase it gives you dimension\n", - " for (int col = 0; col < ???; col++) { // colliumn makes senseas it starts at 0 \n", - " int element = twoDArray[row][col];\n", - " System.out.print(element + \" \");\n", - " }\n", - " System.out.println(); \n", - " }\n", - " }\n", - "}\n", - "TwoDArrayTraversal.main(null)\n", - "### Practice\n", - "- Create a 2D Array Based and Traverse through it using a nested loop based on this problem\n", - "public class 2DPractice {\n", - " public static void main(String[] args) {\n", - " \n", - " int[][] complexIntArray = {\n", - " {1, 2, 3, 4},\n", - " {5, 6, 7, 8},\n", - " {9, 10, 11, 12}\n", - " };\n", - "\n", - " // MISSING CODE HERE \n", - " }\n", - " }\n", - "## Using Enhanced For- Loops to Traverse an Array\n", - "public class EnhancedForLoop2DArray {\n", - " public static void main(String[] args) {\n", - " // Define and initialize a 2D array\n", - " int[][] twoDArray = {\n", - " {1, 2, 3},\n", - " {4, 5, 6},\n", - " {7, 8, 9}\n", - " };\n", - "\n", - " // Use nested enhanced for loops to traverse the 2D array\n", - " for (int[] row : twoDArray) {\n", - " for (int element : row) {\n", - " System.out.print(element + \" \");\n", - " }\n", - " System.out.println(); // Move to the next row\n", - " }\n", - " }\n", - "}\n", - "EnhancedForLoop2DArray.main(null)\n", - "# Row Major Order Vs Column Major Order \n", - "\n", - "- PopCorn Hacks \n", - "\n", - "- **Whats the difference between row major order and column major order**\n", - "public class PrintArray {\n", - " public static void printArray(String[][] grid) {\n", - " for (int row = 0; row < grid.length; row++) {\n", - " for (int col = 0; col < grid[0].length; col++) {\n", - " System.out.print(grid[row][col] + \" \");\n", - " }\n", - " System.out.println(); \n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " String[][] myGrid = {\n", - " {\"A\", \"B\", \"C\"},\n", - " {\"D\", \"E\", \"F\"},\n", - " {\"G\", \"H\", \"I\"}\n", - " };\n", - " printArray(myGrid);\n", - " }\n", - "}\n", - "PrintArray.main(null)\n", - "public class PrintArray {\n", - " public static void printArray(String[][] grid) {\n", - " for (int col = 0; col < grid[0].length; col++) // outer loop for collums switched\n", - " { for (int row = 0; row < grid.length; row++) //notice the outer is switched with the inner loop for rows\n", - " {\n", - " System.out.print(grid[row][col] + \" \");\n", - " }\n", - " System.out.println(); \n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " String[][] myGrid = {\n", - " {\"A\", \"B\", \"C\"},\n", - " {\"D\", \"E\", \"F\"},\n", - " {\"G\", \"H\", \"I\"}\n", - " };\n", - " printArray(myGrid);\n", - " }\n", - "}\n", - "PrintArray.main(null)\n", - "# Practice\n", - "- Print My AP CS A Class Rocks Using a column major traversal.\n", - "public class PrintArray {\n", - " public static void printArray(String[][] grid) {\n", - " for (???) {\n", - " for (???) {\n", - " System.out.print(grid[???][???] + \" \");\n", - " }\n", - " }\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " String[][] message = {\n", - " {\"My\", \"Ap\", \"Cs\", \"R\"},\n", - " {\"AP\", \"A\", \"Class\", \"o\"},\n", - " {\"C\", \"p\", \" \", \"c\"},\n", - " {\"S\", \" \", \" \", \"k\"},\n", - " {\"s\", \" \", \"s\", \"!\"},\n", - " };\n", - "\n", - " printArray(message);\n", - " }\n", - "}\n", - "\n", - "\n", - "PrintArray.main(null)\n", - "# Algorithms That use 2D Arrays Traversing \n", - "public class SearchExample {\n", - " public static boolean search(String[][] chart, String name) {\n", - " for (int r = 0; r < chart.length; r++) {\n", - " for (int c = 0; c < chart[0].length; c++) {\n", - " if (chart[r][c].equals(name)) {\n", - " return true;\n", - " }\n", - " }\n", - " }\n", - " return false; // Name not found in the array\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " String[][] chart = {\n", - " {\"Alice\", \"Bob\", \"Charlie\"},\n", - " {\"David\", \"Eve\", \"Frank\"},\n", - " {\"Grace\", \"Hannah\", \"Isaac\"}\n", - " };\n", - "\n", - " String nameToSearch = \"Krishiv\";\n", - " boolean found = search(chart, nameToSearch);\n", - "\n", - " if (found) {\n", - " System.out.println(nameToSearch + \" is in the array.\");\n", - " } else {\n", - " System.out.println(nameToSearch + \" is not in the array.\");\n", - " }\n", - " }\n", - "}\n", - "SearchExample.main(null)\n", - "# Hacks 8.2\n", - "- Complete the popcorn hacks \n", - "- Main Hack:\n", - " - Traverse Through a 2D Array Using Any of the following methods that we learned \n", - " - Traverse Through A 2D Array Using Specfically The Collumn Major Order. (Make Sure your using correct type of nested loop )\n", - " - Create your own situration of an Algorthm that needs to traverse a 2D array and then write the code for it \n", - " - Extra: Create an Extra Problem or Go further in depth about something we learned (MUST HAVE CODE FOR CREDIT!)\n", - "# Image Representation with 2D Arrays\n", - "\n", - "Digital images are essentially a collection of small, discrete elements called pixels. Pixels are organized in a 2D grid, where each pixel represents a single point of color or intensity. Each element (pixel) in the 2D array corresponds to one pixel in the image. In a color image, each pixel contains three color components: Red, Green, and Blue (RGB), while in grayscale images, each pixel has a single intensity value.\n", - "## Traversing and Processing an Image\n", - "\n", - "Traversing an image's 2D array involves systematically visiting every pixel in the image grid. This process often uses nested loops, with the outer loop iterating over the rows and the inner loop iterating over the columns. By traversing the array, you gain access to each pixel's information, such as color values or intensity. This structured access is fundamental for various image processing tasks.\n", - "import java.io.*;\n", - "import java.net.URL;\n", - "import javax.imageio.ImageIO; // ImageIO is a class in Java libraries which gives an easy way to use different image formats\n", - "import java.awt.image.BufferedImage; // BufferedImage is a class in Java libraries to help perform operations on images (read + write)\n", - "\n", - "public class ImageProcessing {\n", - " public static void main(String[] args) {\n", - " String imageUrl = \"https://user-images.githubusercontent.com/111609656/277895130-d15b0768-01d9-4522-8ef7-4f8bcf69c42e.png\";\n", - " String outputFolder = \"../images\";\n", - " String customFileName = \"MORT1.png\"; \n", - "\n", - " try {\n", - " String outputPath = outputFolder + File.separator + customFileName;\n", - "\n", - " URL url = new URL(imageUrl); // create URL object\n", - "\n", - " try (InputStream in = url.openStream(); // try-catch block where errors are handled\n", - " OutputStream out = new FileOutputStream(outputPath)) { // input stream reads data and output stream writes the data\n", - "\n", - " byte[] buffer = new byte[1024];\n", - " int bytesRead;\n", - "\n", - " while ((bytesRead = in.read(buffer)) != -1) {\n", - " out.write(buffer, 0, bytesRead);\n", - " } // reading the data from the URL and writes in 1024 byte chunks\n", - " }\n", - "\n", - " System.out.println(\"Image downloaded and saved to: \" + outputPath);\n", - "\n", - " File imageFile = new File(outputPath);\n", - " BufferedImage image = ImageIO.read(imageFile); \n", - " int width = image.getWidth();\n", - " int height = image.getHeight(); // get the image dimensions\n", - "\n", - " System.out.println(\"Success! Image Dimensions (Width x Height): \" + width + \" x \" + height);\n", - "\n", - " // Process the image using a 2D array\n", - " int[][] pixels = new int[width][height];\n", - "\n", - " for (int x = 0; x < width; x++) {\n", - " for (int y = 0; y < height; y++) {\n", - " int pixel = image.getRGB(x, y);\n", - " // Process the pixel here, e.g., apply filters or transformations\n", - " pixels[x][y] = pixel;\n", - " }\n", - " }\n", - "\n", - " // Calculate resolution in pixels per inch (PPI)\n", - " int ppi = (int) (image.getWidth() / (width * 0.0254));\n", - " System.out.println(\"Resolution: \" + ppi + \" pixels per inch (PPI)\");\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "}\n", - "ImageProcessing.main(null)\n", - "## Grayscale Conversion with Images\n", - "\n", - "Grayscale conversion is a fundamental image processing operation. When converting an image to grayscale, you effectively remove color information and retain only the pixel intensity. This is typically done by calculating the average intensity from the RGB components of each pixel. The result is a grayscale image where variations in pixel intensity represent the image's features and details. This operation can serve as a starting point for more complex image processing techniques.\n", - "import java.awt.image.BufferedImage;\n", - "import java.awt.image.ColorConvertOp;\n", - "import java.io.*;\n", - "import java.net.URL;\n", - "import javax.imageio.ImageIO;\n", - "\n", - "public class ImageToGrayscaleWithArray {\n", - " public static void main(String[] args) {\n", - " String imageUrl = \"https://user-images.githubusercontent.com/111609656/277895164-5f93f1d8-88b5-4b08-b9a1-b54fb6d55d96.png\"; // Replace with the actual image URL\n", - " String outputFolder = \"../images\";\n", - " String customFileName = \"MORT2_Grayscale.png\"; // Change this to your desired file name for the grayscale image\n", - "\n", - " try {\n", - " // Define the output file path\n", - " String outputPath = outputFolder + File.separator + customFileName;\n", - "\n", - " // Create a URL object from the image URL\n", - " URL url = new URL(imageUrl);\n", - "\n", - " // Open a connection to the URL and get the input stream\n", - " try (InputStream in = url.openStream();\n", - " OutputStream out = new FileOutputStream(outputPath)) {\n", - "\n", - " // Read data from the URL and save it to the output file\n", - " byte[] buffer = new byte[1024];\n", - " int bytesRead;\n", - "\n", - " while ((bytesRead = in.read(buffer)) != -1) {\n", - " out.write(buffer, 0, bytesRead);\n", - " }\n", - " }\n", - "\n", - " // Read the downloaded image\n", - " BufferedImage originalImage = ImageIO.read(new File(outputPath));\n", - " int width = originalImage.getWidth();\n", - " int height = originalImage.getHeight();\n", - "\n", - " // Create a 2D array to store grayscale values\n", - " int[][] grayscaleArray = new int[width][height];\n", - "\n", - " // Convert the image to grayscale and populate the array\n", - " for (int x = 0; x < width; x++) {\n", - " for (int y = 0; y < height; y++) {\n", - " int pixel = originalImage.getRGB(x, y);\n", - " int red = (pixel >> 16) & 0xFF;\n", - " int green = (pixel >> 8) & 0xFF;\n", - " int blue = pixel & 0xFF;\n", - " int gray = (red + green + blue) / 3;\n", - " grayscaleArray[x][y] = gray;\n", - " }\n", - " }\n", - "\n", - " // Save the grayscale image\n", - " String grayscaleOutputPath = outputFolder + File.separator + customFileName;\n", - " BufferedImage grayscaleImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);\n", - "\n", - " for (int x = 0; x < width; x++) {\n", - " for (int y = 0; y < height; y++) {\n", - " int grayValue = grayscaleArray[x][y];\n", - " int grayPixel = (grayValue << 16) | (grayValue << 8) | grayValue;\n", - " grayscaleImage.setRGB(x, y, grayPixel);\n", - " }\n", - " }\n", - "\n", - " ImageIO.write(grayscaleImage, \"png\", new File(grayscaleOutputPath));\n", - "\n", - " System.out.println(\"Success! Image converted to grayscale, downloaded, and saved to: \" + grayscaleOutputPath);\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "}\n", - "ImageToGrayscaleWithArray.main(null)\n", - "## Image Conversion\n", - "\n", - "\n", - "<br>\n", - "\n", - "\n", - "<b> Why do we Convert Images ? </b>\n", - "\n", - "\n", - "\n", - "#### How Does Image Conversion Work:\n", - "import javax.imageio.ImageIO; // allows you to read and write images in various formats.\n", - "import java.io.File; // allows you to work with files and directories in your file system.\n", - "import java.io.IOException; // allows you to handle input and output exceptions that may occur during file operations.\n", - "import java.awt.image.BufferedImage; // allows you to work with images stored in memory, providing methods to manipulate image data.\n", - "\n", - "public class ImageConverter {\n", - "\n", - " public static void main(String[] args) {\n", - " try {\n", - " // Input and output file paths\n", - " String[] inputPaths = {\n", - " \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/woodworker_mort.png\",\n", - " \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/Mort2.png\"\n", - " };\n", - " String outputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert\";\n", - "\n", - " // Loop through each image in the array\n", - " for (String inputPath : inputPaths) {\n", - " // Read the image\n", - " File inputFile = new File(inputPath);\n", - " BufferedImage img = ImageIO.read(inputFile); // Buffered image is a class in java for handling image data\n", - "\n", - " // Write the image\n", - " String outputFileName = \"converted_\" + new File(inputPath).getName().replace(\".png\", \".gif\");\n", - " String outputFilePath = outputPath + File.separator + outputFileName;\n", - " File outputFile = new File(outputFilePath);\n", - " ImageIO.write(img, \"gif\", outputFile);\n", - "\n", - " System.out.println(\"Image conversion successful for: \" + inputPath);\n", - " }\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "}\n", - "ImageConverter.main(null)\n", - "\n", - "import javax.imageio.ImageIO;\n", - "import java.io.File;\n", - "import java.io.IOException;\n", - "import java.awt.image.BufferedImage;\n", - "\n", - "public class ImageConverter {\n", - "\n", - " public static void main(String[] args) {\n", - " try {\n", - " // Input and output file paths\n", - " String inputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/Mort2.png\";\n", - " String outputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert\";\n", - "\n", - " // Read the PNG image\n", - " BufferedImage img = ImageIO.read(new File(inputPath));\n", - "\n", - " // Convert image to RGB format \n", - " BufferedImage rgbImage = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);\n", - " rgbImage.createGraphics().drawImage(img, 0, 0, null);\n", - "\n", - " // Define the output file name and path\n", - " String outputFileName = inputPath.substring(inputPath.lastIndexOf(\"/\") + 1).replace(\".png\", \".jpeg\");\n", - " String outputFilePath = outputPath + File.separator + outputFileName;\n", - "\n", - " // Convert and save the image as JPEG\n", - " ImageIO.write(rgbImage, \"jpeg\", new File(outputFilePath));\n", - "\n", - " System.out.println(\"Image conversion successful!\");\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "}\n", - "\n", - "ImageConverter.main(null);\n", - "\n", - "## Scaling the Image\n", - "import javax.imageio.ImageIO;\n", - "import java.awt.*;\n", - "import java.awt.image.BufferedImage;\n", - "import java.io.File;\n", - "import java.io.IOException;\n", - "\n", - "public class ImageScaler {\n", - "\n", - " public static void main(String[] args) {\n", - " try {\n", - " // Input and output file paths\n", - " String inputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/images/snow_mort.png\";\n", - " String outputPath = \"/Users/nikhilchakravarthula/vscode/KPNSLESSON/imagesConvert\";\n", - "\n", - " // Desired width and height of the scaled image\n", - " int scaledWidth = 100;\n", - " int scaledHeight = 100;\n", - "\n", - " // Read the image\n", - " File inputFile = new File(inputPath);\n", - " BufferedImage inputImage = ImageIO.read(inputFile);\n", - "\n", - " // Scale the image\n", - " BufferedImage scaledImage = scaleImage(inputImage, scaledWidth, scaledHeight);\n", - "\n", - " // Write the scaled image\n", - " String outputFileName = \"scaled_\" + new File(inputPath).getName();\n", - " String outputFilePath = outputPath + File.separator + outputFileName;\n", - " File outputFile = new File(outputFilePath);\n", - " ImageIO.write(scaledImage, \"png\", outputFile); \n", - "\n", - " System.out.println(\"Image scaling successful!\");\n", - " } catch (IOException e) {\n", - " e.printStackTrace();\n", - " }\n", - " }\n", - "\n", - " public static BufferedImage scaleImage(BufferedImage originalImage, int scaledWidth, int scaledHeight) {\n", - " // Create a new BufferedImage with the desired width and height\n", - " BufferedImage scaledImage = new BufferedImage(scaledWidth, scaledHeight, originalImage.getType());\n", - " \n", - " // g2d more into\n", - " // Create a Graphics2D object and set the rendering hints for scaling\n", - " Graphics2D g2d = scaledImage.createGraphics();\n", - " g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n", - " \n", - " // Draw the original image on the new BufferedImage with the desired width and height\n", - " g2d.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);\n", - " \n", - " // Dispose of the Graphics2D object\n", - " g2d.dispose();\n", - " \n", - " return scaledImage;\n", - " }\n", - "}\n", - "\n", - "ImageScaler.main(null);\n", - "\n", - "## Images Hack\n", - "\n", - "Hack: Create a functioning code in which you convert a PNG image to a JPEG image (make it funny).\n", - "\n", - "# Grading for Hacks\n", - "\n", - "- 0.7 for Completing Lesson Hacks\n", - "- 0.2 for Popcorn Hacks + Practice\n", - "- 0.1 for Doing Extra Work" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.2.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.2.ipynb deleted file mode 100644 index 51df3f797d..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.2.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "a76c5cb0", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Data-Sets]\n", - "lesson_language: Java\n", - "lesson_topic: Data-Sets\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Introduction to Using Data Sets\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_2\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.3.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.3.ipynb deleted file mode 100644 index e3fc56344e..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.3.ipynb +++ /dev/null @@ -1,283 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Array-Creation-and-Access]\n", - "lesson_language: Java\n", - "lesson_topic: Array-Creation-and-Access\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Array Creation and Access\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_3\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Intro into Arrays\n", - "\n", - "- An **array** is a data structure used to implement a collection (list) of primitive or object reference data.\n", - "\n", - "- An **element** is a single value in the **array**\n", - "\n", - "- The __**index**__ of an **element** is the position of the element in the **array**\n", - "\n", - " - In java, the **first element** of an array is at **index 0**.\n", - "\n", - "- The **length** of an **array** is the number of elements in the array.\n", - "\n", - " - **`length`** is a `public final` data member of an array\n", - "\n", - " - Since `length` is `public`, we can access it in **any class**!\n", - "\n", - " - Since `length` is `final` we cannot change an array's `length` after it has been created\n", - " - In Java, the **last element** of an array named `list` is at **index** `list.length -1`" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## A look into list Memory\n", - "`int [] listOne = new int[5];`\n", - "\n", - "This will allocate a space in memory for 5 integers.\n", - "\n", - "```\n", - "ARRAY: [0, 0, 0, 0, 0]\n", - "INDEX: 0 1 2 3 4\n", - "```\n", - "\n", - "Using the keyword new uses the default values for the data type. The default values are as follows:\n", - "\n", - "| Data Type | Default Value |\n", - "| --------- | ------------- |\n", - "| byte | (byte) 0 |\n", - "| short | (short) 0 |\n", - "| int | 0 |\n", - "| double | 0.0 |\n", - "| boolean | false |\n", - "| char | '\\u0000' |\n", - "\n", - "What do we do if we want to insert a value into the array?\n", - "\n", - "`listOne[0] = 5;`\n", - "\n", - "Gives us the following array:\n", - "\n", - "```\n", - "ARRAY: [0, 0, 0, 0, 0]\n", - "INDEX: 0 1 2 3 4\n", - "```\n", - "\n", - "What if we want to initialize our own values? We can use an initializer list!\n", - "\n", - "`int [] listTwo = {1, 2, 3, 4, 5};`\n", - "\n", - "Gives us the following array:\n", - "\n", - "```\n", - "ARRAY: [1, 2, 3, 4, 5]\n", - "INDEX: 0 1 2 3 4\n", - "```\n", - "\n", - "If we try to access an index outside of the range of existing indexes, we will get an error. But why? Remember the basis of all programming languages is memory. Because we are trying to access a location in memory that does not exist, java will throw an error (`ArrayIndexOutOfBoundsException`).\n", - "\n", - "How do we print the array? Directly printing the array will not work, it just prints the value of the array in memory. We need to iterate through the array and print each value individually!" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Error at listOne[5] = 13\n", - "ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!\n", - "[I@620c6ceb\n", - "0\n" - ] - } - ], - "source": [ - "/* lets take a look at the above */\n", - "\n", - "int [] listOne = new int[5]; // Our list looks like [0, 0, 0, 0, 0]\n", - "\n", - "listOne[2] = 33; // Our list looks like [0, 0, 33, 0, 0]\n", - "listOne[3] = listOne[2] * 3; // Our list looks like [0, 0, 33, 99, 0]\n", - "\n", - "try {\n", - " listOne[5] = 13; // This will return an error\n", - "} catch (Exception e) {\n", - " System.out.println(\"Error at listOne[5] = 13\");\n", - " System.out.println(\"ArrayIndexOutOfBoundsException: We can't access a memory index that doesn't exist!\");\n", - "}\n", - "\n", - "\n", - "System.out.println(listOne); // THIS DOES NOT PRINT THE LIST!! It prints the value in memory\n", - "System.out.println(listOne[4]); // This will actually print the vaules in the array" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn Hacks!\n", - "\n", - "Write code to print out every element of listOne the following" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "/* popcorn hacks go here */" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Reference elements\n", - "\n", - "Lists can be made up of elements other than the default data types! We can make lists of objects, or even lists of lists! Lets say I have a class `Student` and I want to make a list of all students in the class. I can do this by creating a list of `Student` objects.\n", - "\n", - "```\n", - "Student [] classList;\n", - "classList new Student [3];\n", - "```\n", - "\n", - "Keep in mind, however, that the list won't be generated with any students in it. They are initialized to `null` by default, and We need to create the students and then add them to the list ourselves.\n", - "\n", - "```\n", - "classList[0] = new Student(\"Bob\", 12, 3.5);\n", - "classList[1] = new Student(\"John\", 11, 4.0);\n", - "classList[2] = new Student(\"Steve\", 10, 3.75);\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Popcorn hacks!\n", - "\n", - "Use a class that you have already created and create a list of objects of that class. Then, iterate through the list and print out each object using:\n", - " 1) a for loop\n", - " 2) a while loop" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "/* Popcorn hacks go here */" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Enhanced for loops\n", - "\n", - "The enhanced `for` loop is also called a for-each loop. Unlike a \"traditional\" indexed `for` loop with three parts separated by semicolons, there are only two parts to the enhanced `for` loop header and they are separated by a colon.\n", - "\n", - "The first half of an enhanced `for` loop signature is the type of name for the variable that is a copy of the value stored in the structure. Next a colon separates the variable section from the data structure being traversed with the loop.\n", - "\n", - "Inside the body of the loop you are able to access the value stored in the variable. A key point to remember is that you are unable to assign into the variable defined in the header (the signature)\n", - "\n", - "You also do not have access to the indices of the array or subscript notation when using the enhanced `for` loop.\n", - "\n", - "These loops have a structure similar to the one shown below:\n", - "\n", - "```js\n", - "for (type declaration : structure )\n", - "{\n", - " // statement one;\n", - " // statement two;\n", - " // ...\n", - "}\n", - "```\n", - "\n", - "## Popcorn Hacks!\n", - "\n", - "Create an array, then use a enhanced for loop to print out each element of the array." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "/* Popcorn hacks go here */" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Min maxing\n", - "\n", - "It is a common task to determine what the largest or smallest value stored is inside an array. in order to do this, we need a method that can ake a parameter of an array of primitive values (`int` or `double`) and return the item that is at the appropriate extreme.\n", - "\n", - "Inside the method of a local variable is needed to store the current max of min value that will be compared against all the values in the array. you can assign the current value to be either the opposite extreme or the first item you would be looking at.\n", - "\n", - "You can use either a standard `for` loop or an enhanced `for` loop to determine the max or min. Assign the temporary variable a starting value based on what extreme you are searching for.\n", - "\n", - "Inside the `for` loop, compare the current value against the local variable, if the current value is better, assign it to the temporary variable. When the loop is over, the local variable will contain the approximate value and is still available and within scope and can be returned from the method.\n", - "\n", - "## Popcorn Hacks!\n", - "Create two lists: one of ints and one of doubles. Use both a standard for loop and an enhanced for loop to find the max and min of each list." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "/* Popcorn hacks go here! */" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "18.0.2.1+1-1" - }, - "orig_nbformat": 4 - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.4.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.4.ipynb deleted file mode 100644 index 76802a4252..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.4.ipynb +++ /dev/null @@ -1,225 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "6a20ad81", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Array-Traversals]\n", - "lesson_language: Java\n", - "lesson_topic: Array-Traversals\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Array Traversals\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_4\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "fd94e0a0", - "metadata": {}, - "source": [ - "# Traversing Array (1D)\n", - "> Using iteration statements (standard for loops and while loops) to access each element in an array. \n", - "\n", - "# For loop : Accessing Some Elements of a List\n", - "# 6.3 Enhanced for loop for Arrays (Vivian)\n", - "- the enhanced for loop is also known as the “for each” loop\n", - "- provides a simplified way to loop through elements in an array, collection, or other iterable data structures.\n", - "\n", - "## Standard For Loop\n", - "- An array in java is indexed from _ to the number of elements - _. \n", - "\n", - "**Review on For Loops**\n", - "- init: The init expression is used for initializing a variable, and it is executed only once.\n", - "- condition: It executes the condition statement for every iteration\n", - "- incr/decr: It is the increment or decrement statement applied to the variable, updates the initial expression.\n", - "\n", - "![image](https://github.com/tanishapatil1234/student/assets/111611921/ec109b9d-f3be-451f-9d87-6488a1c96e2b)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6c465a9b", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "import java.util.Random;\n", - "\n", - "/* public class RandomArray {\n", - " public static void main(String[] args){\n", - " int [] list = new int[6];\n", - " Random rand = new Random(); \n", - "*/\n", - " // FOR LOOP 1\n", - " for (int i = 0; i < list.length; i++){\n", - " list[i] = rand.nextInt(4);\n", - " }\n", - "\n", - " // FOR LOOP 2\n", - " for(int element: list){\n", - " System.out.println(element);\n", - " }\n", - "\n", - "/* }\n", - "\n", - " }\n", - "\n", - " RandomArray.main(null);\n", - "*/" - ] - }, - { - "cell_type": "markdown", - "id": "78237087", - "metadata": {}, - "source": [ - "![download](https://github.com/tanishapatil1234/student/assets/111611921/39e2f50d-6eca-4dcd-9d57-489662a26391)\n" - ] - }, - { - "cell_type": "markdown", - "id": "947e9481", - "metadata": {}, - "source": [ - "**Class Discussion-Take Notes, these will count for points in your hacks!**\n", - "\n", - "4. If I only wanted to access the elements at even indices of the list (0, 2, 4), what could I change in the statement below to accomplish that? \n", - "\n", - "5. What about odd? " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d2ab10c3", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// EVEN\n", - "int[] list = {0, 1, 2, 3, 4, 5};\n", - "System.out.println(\"Even Index\");\n", - "for(int index = 0; index < list.length; index++){\n", - " System.out.println(list[index]);\n", - "}\n", - "\n", - "// ODD\n", - "int[] list = {0, 1, 2, 3, 4, 5};\n", - "System.out.println(\"Odd Index\");\n", - "for(int index = 0; index < list.length; index++){\n", - " System.out.println(list[index]);\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "c1c0e1be", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "source": [ - "**Note: These are NOT traversals, even though these are for loops. This is because not every element in the array is accessed.**" - ] - }, - { - "cell_type": "markdown", - "id": "f33f99be", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "source": [ - "6. Does the following loop accomplish traversing the array? " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "afd5cfa1", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "int [] list = new int[5];\n", - "int index = 0; \n", - "\n", - "while (index < list.length) \n", - "{\n", - " // Do something\n", - " index ++; \n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "6dad9dc7", - "metadata": {}, - "source": [ - "7. This while loop and the for loop we used earlier accomplish the same task. The main difference is that after the loop is completed, the variable 'index' in the while loop will still exist. The variable 'i' in the for loop will not. Why? \n", - "\n", - "__________________________________" - ] - }, - { - "cell_type": "markdown", - "id": "b5a54337", - "metadata": {}, - "source": [ - "## Bounds Errors" - ] - }, - { - "cell_type": "markdown", - "id": "098cbce4", - "metadata": {}, - "source": [ - "When traversing an array, we need to be careful with the indices to avoid an ArrayIndexOutOfBoundsException being thrown. " - ] - }, - { - "cell_type": "markdown", - "id": "4c80039c", - "metadata": {}, - "source": [ - "**ATTENTION: MOST COMMON MISTAKE:**\n", - "8. What is wrong with the for loop and while loop below? Why does this produce an ArrayIndexOutOfBoundsException error? ____" - ] - }, - { - "cell_type": "markdown", - "id": "950967a7", - "metadata": {}, - "source": [ - "for(int i = 0; i <= list.length; i ++)" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.5.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.5.ipynb deleted file mode 100644 index 7885ee2f1f..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.5.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "0d8d98b3", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Array-Algorithms]\n", - "lesson_language: Java\n", - "lesson_topic: Array-Algorithms\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Implementing Array Algorithms\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_5\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.6.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.6.ipynb deleted file mode 100644 index 6abd2e5a55..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.6.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "12993e6f", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Text-Files]\n", - "lesson_language: Java\n", - "lesson_topic: Text-Files\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Using Text Files\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_6\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.7.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.7.ipynb deleted file mode 100644 index 71fb0ae7d7..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.7.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "44cd38d1", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Wrapper-Classes]\n", - "lesson_language: Java\n", - "lesson_topic: Wrapper-Classes\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Wrapper Classes\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_7\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.8.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.8.ipynb deleted file mode 100644 index 0e135b4df4..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.8.ipynb +++ /dev/null @@ -1,658 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "30d4fc07", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, ArrayList-Methods]\n", - "lesson_language: Java\n", - "lesson_topic: ArrayList-Methods\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: ArrayList Methods\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_8\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "a4de9279", - "metadata": {}, - "source": [ - "# Unit 7: ArrayList\n", - "> Mastering the concept of Java's ArrayList. AP Exam weighting: 2.5-7.5%.\n", - "# 7.1: ArrayList Intro\n", - "- ArrayLists are dynamic, meaning their size can grow or shrink as needed, but arrays are static in size\n", - "- Instead of creating a new array of a different size and copying the data from the initial array to the new one, we can use ArrayLists\n", - "\n", - "|Arrays|ArrayLists|\n", - "|-------|---------|\n", - "|Fixed Length|Resizable Length|\n", - "|Fundamental Java feature|Part of a framework|\n", - "|An object with no methods|Class with many methods|\n", - "|Not as flexible|Designed to be very flexible|\n", - "|Can store primitive data|Not designed to store primitives|\n", - "||Slightly slower than arrays|\n", - "||Need an import statement|\n", - "In order to use the ArrayList class, the ArrayList class needs to be imported from the java util package. This can be done by writing import java.util.ArrayList at the top of the class file.\n", - "import java.util.ArrayList; // Import the ArrayList class\n", - "\n", - "// Declare and initialize an ArrayList of integers\n", - "ArrayList<Integer> numbersList = new ArrayList<>();\n", - "ArrayList objects are created in the same fashion as other object classes. The primary difference with ArrayLists is that the element type of the ArrayList must be specified using angled bracket <>. In this example, E represents the data type that will be used in the ArrayList. This can be replaced by an object data type:\n", - "ArrayList<E> list = new ArrayList<E>();\n", - "We can actually declare ArrayLists without specifying the type that will be included in the ArrayList, but specifying the data type is smarter because it allows the compiler to find errors before run time, so its more efficient and easy to spot errors.\n", - "ArrayList list = new ArrayList();\n", - "#### Quick lil popcorn hack\n", - "\n", - "Create 2 ArrayLists, 1 called `studentName` and 1 called `studentAge`\n", - "public class Student\n", - "{\n", - " public static void main(String[] args)\n", - " {\n", - " //Initialize your ArrayLists\n", - " \n", - " }\n", - "}\n", - "# 7.2: ArrayList Methods\n", - "### Learning Objectives\n", - "\n", - "Students will be able to represent collections of related object reference data using `ArrayList` objects.\n", - "\n", - "### Essential Knowledge\n", - "\n", - "- Iteration statements provide a means to access all the elements stored within an `ArrayList`. This process is referred to as \"traversing the `ArrayList`.\"\n", - "\n", - "- The following `ArrayList` methods, including what they do and when they are used, are part of the Java Quick Reference:\n", - "\n", - " * `int size()` - Returns the count of elements within the list.\n", - " * `boolean add(E obj)` - Appends the object `obj` to the end of the list and returns `true`.\n", - " * `void add(int index, E obj)` - Inserts `obj` at the specified `index`, shifting elements at and above that position to the right (incrementing their indices by 1) and increasing the list's size by 1.\n", - " * `E get(int index)` - Retrieves the element at the given `index` in the list.\n", - " * `E set(int index, E obj)` - Replaces the element at the specified `index` with `obj` and returns the previous element at that index.\n", - " * `E remove(int index)` - Deletes the element at the specified `index`, shifting all subsequent elements one index to the left, reducing the list's size by one, and returning the removed element.\n", - "\n", - "- Java allows the generic `ArrayList<E>`, where the generic type `E` specifies the type of element.\n", - "\n", - "- When `ArrayList<E>` is specified, the types of the reference parameters and return type when using the methods are type `E`.\n", - "\n", - "- `ArrayList<E>` is preferred over `ArrayList` because it allows the compiler to find errors that would otherwise be found at runtime.\n", - "### Size of the `ArrayList`\n", - "\n", - "* `int size();` : Returns the number of elements in the list.\n", - "\n", - "Consider the following code:\n", - "ArrayList<Integer> a1 = new ArrayList<>();\n", - "System.out.println(a1.size());\n", - "### Adding Items to an `ArrayList`\n", - "\n", - "* `boolean add(E obj);` : Appends `obj` to the end of the list and returns true.\n", - "* `void add(int index, E obj)` : Inserts `obj` at position `index`, as long as `index` is within the list's length. It moves each element in the list 1 index higher and adds 1 to the list's size.\n", - "\n", - "Consider the following code:\n", - "ArrayList<Double> a2 = new ArrayList<>();\n", - "a2.add(1.0);\n", - "a2.add(2.0);\n", - "a2.add(3.0);\n", - "a2.add(1, 4.0);\n", - "System.out.println(a2);\n", - "### Let's Look at an Example\n", - "\n", - "Consider the following code:\n", - "ArrayList<String> h = new ArrayList<>();\n", - "\n", - "h.add(\"Hello\");\n", - "h.add(\"Hello\");\n", - "h.add(\"HeLLO\");\n", - "h.add(\"Hello\");\n", - "h.add(1, \"Hola\");\n", - "\n", - "h.add(26.2);\n", - "h.add(new String(\"Hello\"));\n", - "h.add(false);\n", - "Now, consider this code:\n", - "ArrayList<String> g = new ArrayList<>();\n", - "\n", - "g.add(\"Hello\");\n", - "g.add(\"Hello\");\n", - "g.add(\"HeLLO\");\n", - "g.add(\"Hello\");\n", - "g.add(1, \"Hola\");\n", - "\n", - "g.add(new String(\"Hello\"));\n", - "\n", - "System.out.println(g);\n", - "**Question:** Why does this code work?\n", - "### Deleting Items from an `ArrayList`\n", - "\n", - "`E remove(int index)` : Removes the element at position `index`, and moves the elements at position `index + 1` and higher to the left. It also subtracts one from the list's size. The return value is the element formerly at position `index`.\n", - "// If you are confused of what list g is, look back at the previous code.\n", - "g.remove(3);\n", - "String former = g.remove(0);\n", - "System.out.println(former);\n", - "### Updating Items in an `ArrayList`\n", - "\n", - "`E set(int index, E obj)` : Replaces the element at position `index` with `obj` and returns the element formerly at position `index`.\n", - "String helloFormer = g.set(1, \"Bonjour\");\n", - "System.out.println(helloFormer);\n", - "System.out.println(g);\n", - "### Accessing Items in an `ArrayList`\n", - "\n", - "`E get(int index)` Returns the element at position `index` in the list.\n", - "String hello = g.get(3);\n", - "System.out.println(hello);\n", - "System.out.println(g);\n", - "### Passing an `ArrayList` as a Method Parameter\n", - "The only time that it is wise to use `ArrayList` instead of `ArrayList<E>` is when it is as a function parameter and it is only using `ArrayList<>.get(E)` or `ArrayList<>.size()`. Consider the following code:\n", - "private void accessOnly(ArrayList arr) {\n", - " if (arr.size() > 0) {\n", - " System.out.println(arr.get(0)); // Change the index to the one you want to access\n", - " } else {\n", - " System.out.println(\"Array is empty\");\n", - " }\n", - "}\n", - "\n", - "ArrayList<Integer> myList = new ArrayList<Integer>();\n", - "accessOnly(myList);\n", - "### Returning an `ArrayList` from a Method\n", - "\n", - "In order for you to return an `ArrayList`, the data type must be specified, and the return type must be the same as the return value. Consider the following code:\n", - "private ArrayList<String> returnTheSame() {\n", - " ArrayList<String> arr = new ArrayList<String>(); // Initialize the ArrayList\n", - " arr.add(\"Hello\");\n", - " return arr;\n", - "}\n", - "\n", - "ArrayList<String> result = returnTheSame();\n", - "System.out.println(result);\n", - "\n", - "### Hacks\n", - "\n", - "- The learning objective is that \"Students will be able to represent collections of related object reference data using `ArrayList` objects.\" What does this mean to you?\n", - "\n", - "- Answer the following questions:\n", - "\n", - " * Look back at *Size of the `ArrayList`*. What does the code output and why?\n", - " * Look back at *Adding items to an `ArrayList`*. What does the code output and why? What type of function is `void`, and what will be the return value?\n", - " * Look back at Example 1. What two lines did we remove? Why?\n", - " * If an `ArrayList` is being used as a parameter, what are the only two methods I can use from it? What would happen if I tried to use any other methods?\n", - "\n", - "- Using the Hack Helper, write code that will:\n", - "\n", - " * Add 2 items to the list.\n", - " * Remove an item from the list anywhere of the user's choice.\n", - " * Replace am item anywhere in the list of the user's choice.\n", - " * Get the first and last element of the list, no matter the length.\n", - " * Return the items added, removed, replaced, and the list's size, in one string.\n", - "### Hack Helper\n", - "public class ArrayListMethodsExample {\n", - " private String manipulateList(/* You can put parameters here if you want to... */) {\n", - " // Your code here\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " ArrayList<Integer> nums = new ArrayList<>();\n", - " ArrayListMethodsExample example = new ArrayListMethodsExample();\n", - " \n", - " String output = example.manipulateList();\n", - " System.out.println(output);\n", - " }\n", - "}\n", - "# 7.3: Traversing Arraylists\n", - "### Learning Objectives:\n", - "- With an Arraylist you can traverse objects using a for or while loop.\n", - "\n", - "- Traversing objects is similar to iterating through objects.\n", - "\n", - "### Essential Knowledge:\n", - "- Iteration statements can be used to accsess all the elements in an Arraylist. This is called traversing the Arraylist.\n", - "\n", - "- Deleting elements during a traversal of an Arraylist requires special techniques to avoid skiping elements. This is called traversing the Arraylist.\n", - "\n", - "- The indicies of an Arraylist start at 0; If you try to use any value lower than 0, you will get an *ArrayIndexOutOfBoundsException* error\n", - "import java.util.ArrayList;\n", - "import java.util.List;\n", - "\n", - "public class Main {\n", - " public static void main(String[] args) {\n", - " ArrayList<String> roster = new ArrayList<>();\n", - " roster.add(\"Hello\");\n", - " roster.add(\"World\");\n", - " roster.add(\"Java\");\n", - " \n", - " int sum = 0;\n", - " for (int i = 0; i < roster.size(); i++) {\n", - " String element = roster.get(i);\n", - " if (element != null) {\n", - " sum += element.length();\n", - " }\n", - " }\n", - " System.out.println(sum);\n", - " }\n", - "}\n", - "\n", - "\n", - "#### Breakdown:\n", - "- We are first declaring a new arraylist and adding a few elements.\n", - "\n", - "- Next, we set the \"sum\" variable as 0.\n", - "\n", - "- We set a for loop to traverse through the arraylist, iterating through all the indices in the arraylist and adding up the lengths of all the values.\n", - "\n", - "- Lastly, we print it out.\n", - "\n", - "#### Loop Conditions:\n", - "\n", - "- There are a few diffrent loop conditions you can use to traverse an Arraylist:\n", - "\n", - ">First, there are three major parts of a for loop:\n", - ">Initialisation, in which you declare the index, can be modified to change where you want to traverse from.\n", - "\n", - ">Boolean condition, in which you declare the stop condition, can be modified in order to change the index you want to stop traversing in.\n", - "\n", - ">Update, in which you declare how many indexes to go through, can be modified to skip certain indicies and traverse in a certain direction.\n", - "#### Practice:\n", - "Suppose we have an arraylist named grades, and we want to remove the entries that are lower than 70.\n", - "replace the question marks with code to solve the problem:\n", - "import java.util.ArrayList;\n", - "import java.util.List;\n", - "\n", - "public class Main {\n", - " public static void main(String[] args) {\n", - " ArrayList<int> grades = new ArrayList<>();\n", - " grades.add(68.9);\n", - " grades.add(71);\n", - " grades.add(100);\n", - " grades.add(80);\n", - " for(int i = 0; i<???; i???){\n", - " if(grades.get(i)<70){\n", - " ???\n", - " }\n", - " }\n", - " System.out.println(grades);\n", - " }\n", - "}\n", - "#### Using Enhanced For-Loop With Traversing:\n", - "\n", - "- Using Enhanced for loop is easier to read and write and is also more concise and avoids errors.\n", - "\n", - "- Indexes are not explicitly used and copies of the current element are made at each iteration.\n", - "import java.util.ArrayList;\n", - "import java.util.List;\n", - "\n", - "public class Main {\n", - " public static void main(String[] args) {\n", - " List<String> roster = new ArrayList<>();\n", - " roster.add(\"Hello\");\n", - " roster.add(\"World\");\n", - " roster.add(\"Java\");\n", - "\n", - " // Using an enhanced for loop to iterate through the ArrayList\n", - " for (String element : roster) {\n", - " System.out.println(element);\n", - " }\n", - " }\n", - "}\n", - "#### Common mistakes:\n", - "- Using the Wrong Data Type: Ensure that you declare your ArrayList with the correct data type. Using the wrong data type can lead to type mismatches and errors.\n", - "\n", - "- Incorrect Indexing: Be cautious when using a standard for loop. Off-by-one errors or accessing elements that don't exist can lead to runtime exceptions.\n", - "\n", - "- Modifying the List During Iteration: Modifying an ArrayList (adding or removing elements) while iterating over it can lead to a ConcurrentModificationException. To avoid this, use an Iterator or create a copy of the list if modifications are needed.\n", - "\n", - "- Not Checking for Null Elements: When using enhanced for loops or iterators, check for null elements if there's a possibility that your list contains them to avoid NullPointerExceptions.\n", - "\n", - "- Inefficient Searching: If you need to find a specific element, avoid using a linear search within a loop. Use appropriate methods like contains() or indexOf() to find elements efficiently.\n", - "## Hacks:\n", - "- Create a scenario which requires the use of arraylist traversal and create code to solve it. \n", - "- Extra points to creative scenarios\n", - "- 90% credit to any working code and scenario\n", - "- 80% credit to incomplete code if you provide explanation of it\n", - "- -10% deduction for late submition\n", - "# 7.4: Developing Algorithms Using ArrayLists\n", - "### Learning Objectives\n", - "\n", - "In the context of `ArrayList` objects, this module aims to teach the following skills:\n", - "\n", - "a. Iterating through `ArrayLists` using `for` or `while` loops.\n", - "\n", - "b. Iterating through `ArrayLists` using enhanced `for` loops.\n", - "\n", - "In the realm of algorithms, within the context of specific requirements that demand the utilization of `ArrayList` traversals, students will be able to:\n", - "\n", - "- Recognize established algorithms.\n", - "- Customize existing algorithms.\n", - "- Create new algorithms.\n", - "\n", - "### Essential Knowledge\n", - "\n", - "- Iteration statements provide a means to access all the elements stored within an `ArrayList`. This process is referred to as \"traversing the `ArrayList`.\"\n", - "\n", - "- The following methods related to `ArrayLists`, their functions, and appropriate use are covered in the Java Quick Reference:\n", - "\n", - " * `int size()` - Returns the count of elements within the list.\n", - " * `boolean add(E obj)` - Appends the object `obj` to the end of the list and returns `true`.\n", - " * `void add(int index, E obj)` - Inserts `obj` at the specified `index`, shifting elements at and above that position to the right (incrementing their indices by 1) and increasing the list's size by 1.\n", - " * `E get(int index)` - Retrieves the element at the given `index` in the list.\n", - " * `E set(int index, E obj)` - Replaces the element at the specified `index` with `obj` and returns the previous element at that index.\n", - " * `E remove(int index)` - Deletes the element at the specified `index`, shifting all subsequent elements one index to the left, reducing the list's size by one, and returning the removed element.\n", - "\n", - "- There exist established algorithms for `ArrayLists` that make use of traversals to:\n", - "\n", - " * Insert elements.\n", - " * Remove elements.\n", - " * Apply the same algorithms commonly used with 1D arrays.\n", - "## Popcorn Hacks:\n", - "\n", - "Before you uncomment the code and run it, guess what the code will do based on what you've learned.\n", - "### Let's Look at an Example (Example 1)\n", - "public class ArrayListExample {\n", - " private double findMax(double[] values) {\n", - " // double max = values[0];\n", - " \n", - " //for (int index = 1; index < values.length; index++) {\n", - " // if (values[index] > max) {\n", - " // max = values[index];\n", - " // }\n", - " //}\n", - " \n", - " // return max;\n", - " }\n", - " \n", - " public static void main(String[] args) {\n", - " double[] nums = {1.0, 3.0, 2.0, 2.0, 1.0, 69.0, 2.0, 4.0, 6.0, 2.0, 5.0, 10.0};\n", - " ArrayListExample example = new ArrayListExample();\n", - " double max = example.findMax(nums);\n", - " System.out.println(\"Maximum value: \" + max);\n", - " }\n", - "}\n", - "\n", - "ArrayListExample.main(null);\n", - "Take a closer look at the `findMax()` method. It takes in a list of doubles as parameters. It will then use a `for` loop to find the maximum value in the list. Now, using what we know, can we replace the list of doubles with an ArrayList of Doubles? We sure can! Take a look at how we can use ArrayList to do just that:\n", - "public class ArrayListExample {\n", - " private double findMax(ArrayList<Double> values) {\n", - " // double max = values.get(0);\n", - " \n", - " //for (int index = 1; index < values.size(); index++) {\n", - " // if (values.get(index) > max) {\n", - " // max = values.get(index);\n", - " // }\n", - " //}\n", - " \n", - " //return max;\n", - " }\n", - " \n", - " public static void main(String[] args) {\n", - " ArrayList<Double> nums = new ArrayList<>();\n", - " nums.add(1.0);\n", - " nums.add(3.0);\n", - " nums.add(2.0);\n", - " nums.add(2.0);\n", - " nums.add(1.0);\n", - " nums.add(69.0);\n", - " nums.add(2.0);\n", - " nums.add(4.0);\n", - " nums.add(6.0);\n", - " nums.add(2.0);\n", - " nums.add(5.0);\n", - " nums.add(10.0);\n", - " \n", - " ArrayListExample example = new ArrayListExample();\n", - " double max = example.findMax(nums);\n", - " System.out.println(\"Maximum value: \" + max);\n", - " }\n", - "}\n", - "\n", - "ArrayListExample.main(null);\n", - "### Let's Look at an Example (Example 2)\n", - "\n", - "Take a look at this code:\n", - "public class ArrayListExample {\n", - " private int findMin(int[] values) {\n", - " //int min = Integer.MAX_VALUE;\n", - " //for (int currentValue : values) {\n", - " // if (currentValue < min) {\n", - " // min = currentValue;\n", - " // }\n", - " //}\n", - " return min;\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " int[] nums = {420, 703, 2034, 582, 1047, 4545};\n", - " ArrayListExample example = new ArrayListExample();\n", - " int min = example.findMin(nums);\n", - " System.out.println(\"Minimum value: \" + min);\n", - " }\n", - "}\n", - "\n", - "ArrayListExample.main(null);\n", - "Now, can we use ArrayLists to make this code better? We sure can! Take a look at the new and improved code that uses ArrayLists:\n", - "public class ArrayListExample {\n", - " private int findMin(ArrayList<Integer> values) {\n", - " //int min = Integer.MAX_VALUE;\n", - " //for (int currentValue : values) {\n", - " // if (currentValue < min) {\n", - " // min = currentValue;\n", - " // }\n", - " //}\n", - " return min;\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " ArrayList<Integer> nums = new ArrayList<>();\n", - " nums.add(420);\n", - " nums.add(703);\n", - " nums.add(2034);\n", - " nums.add(582);\n", - " nums.add(1047);\n", - " nums.add(4545);\n", - " ArrayListExample example = new ArrayListExample();\n", - " int min = example.findMin(nums);\n", - " System.out.println(\"Minimum value: \" + min);\n", - " }\n", - "}\n", - "\n", - "ArrayListExample.main(null);\n", - "### Hacks\n", - "\n", - "- Answer the questions: \n", - " * Look back at the examples. What's similar? What's different?\n", - " * Why do we use `ArrayList`? Why not just regular lists?\n", - "- Demonstrate at least two `ArrayList` methods that aren't `ArrayList<>.size()` and `ArrayList<>.get()`.\n", - "- Write the method `findSum()` using the Hack Helper and incorporating `ArrayList`.\n", - "### Hack Helper\n", - "public class ArrayListHacks {\n", - " private int findSum(ArrayList<Integer> values) {\n", - " // Your code here\n", - " return 0;\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " ArrayList<Integer> nums = new ArrayList<>();\n", - " nums.add(0);\n", - " nums.add(1);\n", - " nums.add(2);\n", - " nums.add(3);\n", - " nums.add(5);\n", - " nums.add(8);\n", - "\n", - " ArrayListHacks hacks = new ArrayListHacks();\n", - " hacks.findSum(nums);\n", - " }\n", - "}\n", - "\n", - "ArrayListHacks.main(null);\n", - "# 7.5 Searching\n", - "\n", - "### Learning Objectives\n", - "- Apply sequential/linear search algorithms to search for specific information in array or ``arraylist`` objects\n", - "\n", - "### Essential Knowledge:\n", - "- Sequential/linear search alogorithms check each element in order untill the desired value is found or all elementsin the array or ``arraylist`` have been checked\n", - "\n", - "### Search Process\n", - "- Linear searching fits a standard for loop perfectly! We need to specify each element, one at a time, and do not need to track the index after execution\n", - "\n", - "- Inside the for loop, we retrieve the value from the structure at the specified index and compare it to the searched value\n", - "\n", - "- If it matches we return the index, otherwise we keep looking!\n", - "### Searching Linear Structures\n", - "\n", - "#### Finding information with a computer is something we need to know how to do. Linear search algorithms are BEST used when we do not have any idea about the order of the data and so we need to look at each element to determine if what we are looking for is in fact inside the array or ``ArrayList``.\n", - "\n", - "#### When searching, we do need to remember that different data types require comparisons!\n", - "- When looking at ``int`` values, the == operator is the tool to use!\n", - "- When searching for a ``double`` value, we need to make sure the value is close enough by doing some math!\n", - "- ``Object`` instances should always use the ``.equals(otheThing)`` method to check for a match!\n", - "## Searching an ``ArrayList`` of Double\n", - "public int where(double magicNumber, ArrayList<Double> realNumbers, double delta)\n", - "{\n", - " for (int index = 0; index < realNumbers.size(); index++)\n", - " {\n", - " if (Math.abs(magicNumber - realNumbers.get(index)) < delta)\n", - " {\n", - " return index;\n", - " }\n", - " }\n", - " return -1;\n", - "}\n", - "### Explanation\n", - "> The where function searches through a list of numbers to find and return the position of the first number that is very close to a specific target number, known as magicNumber. If no number in the list is close enough to the target number, the function returns -1, indicating that no match was found.\n", - "## Searching an ``ArrayList`` of book for a ``String``\n", - "public int findTheWord(String searchedPhrase, ArrayList<Book> myBooks)\n", - "{\n", - " for (int index = 0; index < myBooks.size(); index++)\n", - " {\n", - " Book currentBook = myBooks.get(index);\n", - " String currentPhrase = currentBook.getDescription();\n", - " if(currentPhrase.equals(searchedPhrase))\n", - " {\n", - " return index;\n", - " }\n", - " }\n", - " return -1;\n", - "}\n", - "### Explanation\n", - ">This little code snippet is like a treasure hunt through a collection of books; it's on a mission to find the one book whose description matches exactly with a special phrase you're looking for. If it finds the perfect match, it'll excitedly tell you where it is in the collection, but if not, it'll sadly let you know with a -1 that the search was a bust.\n", - "\n", - "\n", - "\n", - "\n", - "## Questions\n", - "\n", - "#### Should we use == when looking for an Object?\n", - "> No, that only will return true if the variable and the element stored at that index point to the same memory, are aliases of each other\n", - "\n", - "#### Why did we subtract the double values?\n", - "> To make sure that the lack of preciosin that is inherit in the data type is handled within our code\n", - "## Why does order sometimes matter?\n", - "\n", - "#### When searching for a value to remove from a list, if we search forward we have to make sure to adjust the loop control variable, or we might skip what we are looking for when removing!\n", - "# 7.6 Sorting\n", - "\n", - "### Learning Objectives\n", - "- Apply selection sort and insertion sort algorithms to sort the elements of array or ``ArrayList`` objects.\n", - "\n", - "### Essential Knowledge:\n", - "- Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ``ArrayList``.\n", - "\n", - "\n", - "## Selection Sort\n", - "> This is one of the easiest sorts to demonstrate. The selection sort identifies either the maximum or minimum of the compared values and iterates over the structure checking if the item stored at the index matches that condition, if so, it will swap the value stored at that index and continue. This implementation uses a helper method to perform the swap operation since variables can hold only one value at a time!\n", - "\n", - "Example:\n", - "// with normal arrays\n", - "for (int outerLoop = 0; outerLoop < myDucks.length; outerLoop ++)\n", - "{\n", - " int minIndex = outerLoop;\n", - " for (int inner = outerLoop +1; inner < myDucks.length; inner++)\n", - " {\n", - " if (myDucks[inner].compareT(myDucks[minIndex]) < 0)\n", - " {\n", - " minIndex = inner;\n", - " }\n", - " }\n", - " if (minIndex != outerLoop)\n", - " {\n", - " swapItems(minIndex, outerloop, myDucks);\n", - " }\n", - "}\n", - "\n", - "// with array lists\n", - "for (int outerLoop = 0; outerLoop < myDucks.size(); outerLoop++) {\n", - " int minIndex = outerLoop;\n", - " for (int inner = outerLoop + 1; inner < myDucks.size(); inner++) \n", - " {\n", - " if (myDucks.get(inner).compareT(myDucks.get(minIndex)) < 0) \n", - " {\n", - " minIndex = inner;\n", - " }\n", - " }\n", - " if (minIndex != outerLoop) {\n", - " swapItems(minIndex, outerLoop, myDucks); \n", - " }\n", - "}\n", - "/*\n", - "This code performs a selection sort on the myDucks ArrayList, ordering its elements based on the compareT method. \n", - "During each iteration of the outer loop, it finds the index of the minimum element in the unsorted portion of the list and swaps it with the first element of the unsorted portion.\n", - " */ \n", - "## Insertion Sort Algorithm\n", - "> The insertion sort is characterized by building a sorted structure as it proceeds. It inserts each value it finds at the appropriate location in the data structure. This is often accomplished by using a while loop as the inner loop.\n", - "\n", - "Example:\n", - "for (int outer = 1; outer < randomList.size(); outer++)\n", - "{\n", - " DebugDuck tested = randomList.get(outer);\n", - " int inner = outer -1;\n", - "\n", - " while ( innter >= 0 && tested.compareTo(randomList.get(inner)) < 0)\n", - " {\n", - " ramdomList.set(inner +1, randomList.get(inner));\n", - " inner--;\n", - " }\n", - " randomList.set(inner +1, tested)\n", - "}\n", - "// This code arranges a list of DebugDuck objects in order using the insertion sort method, \n", - "// by moving through the list and putting each item in its proper place one by one.\n", - "# 7.7: Ethical Issues around Data Collection\n", - "### Learning Objectives:\n", - "- Explaining the risks of privacy from collecting and storing personal data on computer systems.\n", - "\n", - "### Essential Knowledge:\n", - "- When using the computer, personal privacy is at risk. Programmers should attempt to safeguard personal privacy.\n", - "#### Privacy Protection:\n", - "- A simple way to protect privacy is to delete personal user info after done using it.\n", - "- Another way is to minimize the amount of data used by the program in order to protect privacy.\n", - "- Anonymizing personal data via the object method *hashCode()* is another way.\n", - "## Hacks:\n", - "- Think of other ways to safeguard user privacy (any other method not listed is fine)\n", - "- Extra points to creative solutions\n", - "- 90% credit to any solution\n", - "- 80% credit to incomplete solution (how did you do that?)\n", - "- -10% deduction for late submition\n", - "# Grading:\n", - "\n", - "- 7.2 Hacks (0.19)\n", - "- 7.3 Hacks (0.19)\n", - "- 7.4 Hacks (0.19)\n", - "- 7.7 Hacks (0.19)\n", - "- Popcorn Hacks (0.19)\n", - "- Anything else creative or above-and-beyond showing your understanding of ArrayLists (0.05)" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.9.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.9.ipynb deleted file mode 100644 index 00f92dc3fd..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-4.9.ipynb +++ /dev/null @@ -1,658 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "e34c503c", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, ArrayList-Traversals]\n", - "lesson_language: Java\n", - "lesson_topic: ArrayList-Traversals\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: ArrayList Traversals\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/4_9\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "12d4cae9", - "metadata": {}, - "source": [ - "# Unit 7: ArrayList\n", - "> Mastering the concept of Java's ArrayList. AP Exam weighting: 2.5-7.5%.\n", - "# 7.1: ArrayList Intro\n", - "- ArrayLists are dynamic, meaning their size can grow or shrink as needed, but arrays are static in size\n", - "- Instead of creating a new array of a different size and copying the data from the initial array to the new one, we can use ArrayLists\n", - "\n", - "|Arrays|ArrayLists|\n", - "|-------|---------|\n", - "|Fixed Length|Resizable Length|\n", - "|Fundamental Java feature|Part of a framework|\n", - "|An object with no methods|Class with many methods|\n", - "|Not as flexible|Designed to be very flexible|\n", - "|Can store primitive data|Not designed to store primitives|\n", - "||Slightly slower than arrays|\n", - "||Need an import statement|\n", - "In order to use the ArrayList class, the ArrayList class needs to be imported from the java util package. This can be done by writing import java.util.ArrayList at the top of the class file.\n", - "import java.util.ArrayList; // Import the ArrayList class\n", - "\n", - "// Declare and initialize an ArrayList of integers\n", - "ArrayList<Integer> numbersList = new ArrayList<>();\n", - "ArrayList objects are created in the same fashion as other object classes. The primary difference with ArrayLists is that the element type of the ArrayList must be specified using angled bracket <>. In this example, E represents the data type that will be used in the ArrayList. This can be replaced by an object data type:\n", - "ArrayList<E> list = new ArrayList<E>();\n", - "We can actually declare ArrayLists without specifying the type that will be included in the ArrayList, but specifying the data type is smarter because it allows the compiler to find errors before run time, so its more efficient and easy to spot errors.\n", - "ArrayList list = new ArrayList();\n", - "#### Quick lil popcorn hack\n", - "\n", - "Create 2 ArrayLists, 1 called `studentName` and 1 called `studentAge`\n", - "public class Student\n", - "{\n", - " public static void main(String[] args)\n", - " {\n", - " //Initialize your ArrayLists\n", - " \n", - " }\n", - "}\n", - "# 7.2: ArrayList Methods\n", - "### Learning Objectives\n", - "\n", - "Students will be able to represent collections of related object reference data using `ArrayList` objects.\n", - "\n", - "### Essential Knowledge\n", - "\n", - "- Iteration statements provide a means to access all the elements stored within an `ArrayList`. This process is referred to as \"traversing the `ArrayList`.\"\n", - "\n", - "- The following `ArrayList` methods, including what they do and when they are used, are part of the Java Quick Reference:\n", - "\n", - " * `int size()` - Returns the count of elements within the list.\n", - " * `boolean add(E obj)` - Appends the object `obj` to the end of the list and returns `true`.\n", - " * `void add(int index, E obj)` - Inserts `obj` at the specified `index`, shifting elements at and above that position to the right (incrementing their indices by 1) and increasing the list's size by 1.\n", - " * `E get(int index)` - Retrieves the element at the given `index` in the list.\n", - " * `E set(int index, E obj)` - Replaces the element at the specified `index` with `obj` and returns the previous element at that index.\n", - " * `E remove(int index)` - Deletes the element at the specified `index`, shifting all subsequent elements one index to the left, reducing the list's size by one, and returning the removed element.\n", - "\n", - "- Java allows the generic `ArrayList<E>`, where the generic type `E` specifies the type of element.\n", - "\n", - "- When `ArrayList<E>` is specified, the types of the reference parameters and return type when using the methods are type `E`.\n", - "\n", - "- `ArrayList<E>` is preferred over `ArrayList` because it allows the compiler to find errors that would otherwise be found at runtime.\n", - "### Size of the `ArrayList`\n", - "\n", - "* `int size();` : Returns the number of elements in the list.\n", - "\n", - "Consider the following code:\n", - "ArrayList<Integer> a1 = new ArrayList<>();\n", - "System.out.println(a1.size());\n", - "### Adding Items to an `ArrayList`\n", - "\n", - "* `boolean add(E obj);` : Appends `obj` to the end of the list and returns true.\n", - "* `void add(int index, E obj)` : Inserts `obj` at position `index`, as long as `index` is within the list's length. It moves each element in the list 1 index higher and adds 1 to the list's size.\n", - "\n", - "Consider the following code:\n", - "ArrayList<Double> a2 = new ArrayList<>();\n", - "a2.add(1.0);\n", - "a2.add(2.0);\n", - "a2.add(3.0);\n", - "a2.add(1, 4.0);\n", - "System.out.println(a2);\n", - "### Let's Look at an Example\n", - "\n", - "Consider the following code:\n", - "ArrayList<String> h = new ArrayList<>();\n", - "\n", - "h.add(\"Hello\");\n", - "h.add(\"Hello\");\n", - "h.add(\"HeLLO\");\n", - "h.add(\"Hello\");\n", - "h.add(1, \"Hola\");\n", - "\n", - "h.add(26.2);\n", - "h.add(new String(\"Hello\"));\n", - "h.add(false);\n", - "Now, consider this code:\n", - "ArrayList<String> g = new ArrayList<>();\n", - "\n", - "g.add(\"Hello\");\n", - "g.add(\"Hello\");\n", - "g.add(\"HeLLO\");\n", - "g.add(\"Hello\");\n", - "g.add(1, \"Hola\");\n", - "\n", - "g.add(new String(\"Hello\"));\n", - "\n", - "System.out.println(g);\n", - "**Question:** Why does this code work?\n", - "### Deleting Items from an `ArrayList`\n", - "\n", - "`E remove(int index)` : Removes the element at position `index`, and moves the elements at position `index + 1` and higher to the left. It also subtracts one from the list's size. The return value is the element formerly at position `index`.\n", - "// If you are confused of what list g is, look back at the previous code.\n", - "g.remove(3);\n", - "String former = g.remove(0);\n", - "System.out.println(former);\n", - "### Updating Items in an `ArrayList`\n", - "\n", - "`E set(int index, E obj)` : Replaces the element at position `index` with `obj` and returns the element formerly at position `index`.\n", - "String helloFormer = g.set(1, \"Bonjour\");\n", - "System.out.println(helloFormer);\n", - "System.out.println(g);\n", - "### Accessing Items in an `ArrayList`\n", - "\n", - "`E get(int index)` Returns the element at position `index` in the list.\n", - "String hello = g.get(3);\n", - "System.out.println(hello);\n", - "System.out.println(g);\n", - "### Passing an `ArrayList` as a Method Parameter\n", - "The only time that it is wise to use `ArrayList` instead of `ArrayList<E>` is when it is as a function parameter and it is only using `ArrayList<>.get(E)` or `ArrayList<>.size()`. Consider the following code:\n", - "private void accessOnly(ArrayList arr) {\n", - " if (arr.size() > 0) {\n", - " System.out.println(arr.get(0)); // Change the index to the one you want to access\n", - " } else {\n", - " System.out.println(\"Array is empty\");\n", - " }\n", - "}\n", - "\n", - "ArrayList<Integer> myList = new ArrayList<Integer>();\n", - "accessOnly(myList);\n", - "### Returning an `ArrayList` from a Method\n", - "\n", - "In order for you to return an `ArrayList`, the data type must be specified, and the return type must be the same as the return value. Consider the following code:\n", - "private ArrayList<String> returnTheSame() {\n", - " ArrayList<String> arr = new ArrayList<String>(); // Initialize the ArrayList\n", - " arr.add(\"Hello\");\n", - " return arr;\n", - "}\n", - "\n", - "ArrayList<String> result = returnTheSame();\n", - "System.out.println(result);\n", - "\n", - "### Hacks\n", - "\n", - "- The learning objective is that \"Students will be able to represent collections of related object reference data using `ArrayList` objects.\" What does this mean to you?\n", - "\n", - "- Answer the following questions:\n", - "\n", - " * Look back at *Size of the `ArrayList`*. What does the code output and why?\n", - " * Look back at *Adding items to an `ArrayList`*. What does the code output and why? What type of function is `void`, and what will be the return value?\n", - " * Look back at Example 1. What two lines did we remove? Why?\n", - " * If an `ArrayList` is being used as a parameter, what are the only two methods I can use from it? What would happen if I tried to use any other methods?\n", - "\n", - "- Using the Hack Helper, write code that will:\n", - "\n", - " * Add 2 items to the list.\n", - " * Remove an item from the list anywhere of the user's choice.\n", - " * Replace am item anywhere in the list of the user's choice.\n", - " * Get the first and last element of the list, no matter the length.\n", - " * Return the items added, removed, replaced, and the list's size, in one string.\n", - "### Hack Helper\n", - "public class ArrayListMethodsExample {\n", - " private String manipulateList(/* You can put parameters here if you want to... */) {\n", - " // Your code here\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " ArrayList<Integer> nums = new ArrayList<>();\n", - " ArrayListMethodsExample example = new ArrayListMethodsExample();\n", - " \n", - " String output = example.manipulateList();\n", - " System.out.println(output);\n", - " }\n", - "}\n", - "# 7.3: Traversing Arraylists\n", - "### Learning Objectives:\n", - "- With an Arraylist you can traverse objects using a for or while loop.\n", - "\n", - "- Traversing objects is similar to iterating through objects.\n", - "\n", - "### Essential Knowledge:\n", - "- Iteration statements can be used to accsess all the elements in an Arraylist. This is called traversing the Arraylist.\n", - "\n", - "- Deleting elements during a traversal of an Arraylist requires special techniques to avoid skiping elements. This is called traversing the Arraylist.\n", - "\n", - "- The indicies of an Arraylist start at 0; If you try to use any value lower than 0, you will get an *ArrayIndexOutOfBoundsException* error\n", - "import java.util.ArrayList;\n", - "import java.util.List;\n", - "\n", - "public class Main {\n", - " public static void main(String[] args) {\n", - " ArrayList<String> roster = new ArrayList<>();\n", - " roster.add(\"Hello\");\n", - " roster.add(\"World\");\n", - " roster.add(\"Java\");\n", - " \n", - " int sum = 0;\n", - " for (int i = 0; i < roster.size(); i++) {\n", - " String element = roster.get(i);\n", - " if (element != null) {\n", - " sum += element.length();\n", - " }\n", - " }\n", - " System.out.println(sum);\n", - " }\n", - "}\n", - "\n", - "\n", - "#### Breakdown:\n", - "- We are first declaring a new arraylist and adding a few elements.\n", - "\n", - "- Next, we set the \"sum\" variable as 0.\n", - "\n", - "- We set a for loop to traverse through the arraylist, iterating through all the indices in the arraylist and adding up the lengths of all the values.\n", - "\n", - "- Lastly, we print it out.\n", - "\n", - "#### Loop Conditions:\n", - "\n", - "- There are a few diffrent loop conditions you can use to traverse an Arraylist:\n", - "\n", - ">First, there are three major parts of a for loop:\n", - ">Initialisation, in which you declare the index, can be modified to change where you want to traverse from.\n", - "\n", - ">Boolean condition, in which you declare the stop condition, can be modified in order to change the index you want to stop traversing in.\n", - "\n", - ">Update, in which you declare how many indexes to go through, can be modified to skip certain indicies and traverse in a certain direction.\n", - "#### Practice:\n", - "Suppose we have an arraylist named grades, and we want to remove the entries that are lower than 70.\n", - "replace the question marks with code to solve the problem:\n", - "import java.util.ArrayList;\n", - "import java.util.List;\n", - "\n", - "public class Main {\n", - " public static void main(String[] args) {\n", - " ArrayList<int> grades = new ArrayList<>();\n", - " grades.add(68.9);\n", - " grades.add(71);\n", - " grades.add(100);\n", - " grades.add(80);\n", - " for(int i = 0; i<???; i???){\n", - " if(grades.get(i)<70){\n", - " ???\n", - " }\n", - " }\n", - " System.out.println(grades);\n", - " }\n", - "}\n", - "#### Using Enhanced For-Loop With Traversing:\n", - "\n", - "- Using Enhanced for loop is easier to read and write and is also more concise and avoids errors.\n", - "\n", - "- Indexes are not explicitly used and copies of the current element are made at each iteration.\n", - "import java.util.ArrayList;\n", - "import java.util.List;\n", - "\n", - "public class Main {\n", - " public static void main(String[] args) {\n", - " List<String> roster = new ArrayList<>();\n", - " roster.add(\"Hello\");\n", - " roster.add(\"World\");\n", - " roster.add(\"Java\");\n", - "\n", - " // Using an enhanced for loop to iterate through the ArrayList\n", - " for (String element : roster) {\n", - " System.out.println(element);\n", - " }\n", - " }\n", - "}\n", - "#### Common mistakes:\n", - "- Using the Wrong Data Type: Ensure that you declare your ArrayList with the correct data type. Using the wrong data type can lead to type mismatches and errors.\n", - "\n", - "- Incorrect Indexing: Be cautious when using a standard for loop. Off-by-one errors or accessing elements that don't exist can lead to runtime exceptions.\n", - "\n", - "- Modifying the List During Iteration: Modifying an ArrayList (adding or removing elements) while iterating over it can lead to a ConcurrentModificationException. To avoid this, use an Iterator or create a copy of the list if modifications are needed.\n", - "\n", - "- Not Checking for Null Elements: When using enhanced for loops or iterators, check for null elements if there's a possibility that your list contains them to avoid NullPointerExceptions.\n", - "\n", - "- Inefficient Searching: If you need to find a specific element, avoid using a linear search within a loop. Use appropriate methods like contains() or indexOf() to find elements efficiently.\n", - "## Hacks:\n", - "- Create a scenario which requires the use of arraylist traversal and create code to solve it. \n", - "- Extra points to creative scenarios\n", - "- 90% credit to any working code and scenario\n", - "- 80% credit to incomplete code if you provide explanation of it\n", - "- -10% deduction for late submition\n", - "# 7.4: Developing Algorithms Using ArrayLists\n", - "### Learning Objectives\n", - "\n", - "In the context of `ArrayList` objects, this module aims to teach the following skills:\n", - "\n", - "a. Iterating through `ArrayLists` using `for` or `while` loops.\n", - "\n", - "b. Iterating through `ArrayLists` using enhanced `for` loops.\n", - "\n", - "In the realm of algorithms, within the context of specific requirements that demand the utilization of `ArrayList` traversals, students will be able to:\n", - "\n", - "- Recognize established algorithms.\n", - "- Customize existing algorithms.\n", - "- Create new algorithms.\n", - "\n", - "### Essential Knowledge\n", - "\n", - "- Iteration statements provide a means to access all the elements stored within an `ArrayList`. This process is referred to as \"traversing the `ArrayList`.\"\n", - "\n", - "- The following methods related to `ArrayLists`, their functions, and appropriate use are covered in the Java Quick Reference:\n", - "\n", - " * `int size()` - Returns the count of elements within the list.\n", - " * `boolean add(E obj)` - Appends the object `obj` to the end of the list and returns `true`.\n", - " * `void add(int index, E obj)` - Inserts `obj` at the specified `index`, shifting elements at and above that position to the right (incrementing their indices by 1) and increasing the list's size by 1.\n", - " * `E get(int index)` - Retrieves the element at the given `index` in the list.\n", - " * `E set(int index, E obj)` - Replaces the element at the specified `index` with `obj` and returns the previous element at that index.\n", - " * `E remove(int index)` - Deletes the element at the specified `index`, shifting all subsequent elements one index to the left, reducing the list's size by one, and returning the removed element.\n", - "\n", - "- There exist established algorithms for `ArrayLists` that make use of traversals to:\n", - "\n", - " * Insert elements.\n", - " * Remove elements.\n", - " * Apply the same algorithms commonly used with 1D arrays.\n", - "## Popcorn Hacks:\n", - "\n", - "Before you uncomment the code and run it, guess what the code will do based on what you've learned.\n", - "### Let's Look at an Example (Example 1)\n", - "public class ArrayListExample {\n", - " private double findMax(double[] values) {\n", - " // double max = values[0];\n", - " \n", - " //for (int index = 1; index < values.length; index++) {\n", - " // if (values[index] > max) {\n", - " // max = values[index];\n", - " // }\n", - " //}\n", - " \n", - " // return max;\n", - " }\n", - " \n", - " public static void main(String[] args) {\n", - " double[] nums = {1.0, 3.0, 2.0, 2.0, 1.0, 69.0, 2.0, 4.0, 6.0, 2.0, 5.0, 10.0};\n", - " ArrayListExample example = new ArrayListExample();\n", - " double max = example.findMax(nums);\n", - " System.out.println(\"Maximum value: \" + max);\n", - " }\n", - "}\n", - "\n", - "ArrayListExample.main(null);\n", - "Take a closer look at the `findMax()` method. It takes in a list of doubles as parameters. It will then use a `for` loop to find the maximum value in the list. Now, using what we know, can we replace the list of doubles with an ArrayList of Doubles? We sure can! Take a look at how we can use ArrayList to do just that:\n", - "public class ArrayListExample {\n", - " private double findMax(ArrayList<Double> values) {\n", - " // double max = values.get(0);\n", - " \n", - " //for (int index = 1; index < values.size(); index++) {\n", - " // if (values.get(index) > max) {\n", - " // max = values.get(index);\n", - " // }\n", - " //}\n", - " \n", - " //return max;\n", - " }\n", - " \n", - " public static void main(String[] args) {\n", - " ArrayList<Double> nums = new ArrayList<>();\n", - " nums.add(1.0);\n", - " nums.add(3.0);\n", - " nums.add(2.0);\n", - " nums.add(2.0);\n", - " nums.add(1.0);\n", - " nums.add(69.0);\n", - " nums.add(2.0);\n", - " nums.add(4.0);\n", - " nums.add(6.0);\n", - " nums.add(2.0);\n", - " nums.add(5.0);\n", - " nums.add(10.0);\n", - " \n", - " ArrayListExample example = new ArrayListExample();\n", - " double max = example.findMax(nums);\n", - " System.out.println(\"Maximum value: \" + max);\n", - " }\n", - "}\n", - "\n", - "ArrayListExample.main(null);\n", - "### Let's Look at an Example (Example 2)\n", - "\n", - "Take a look at this code:\n", - "public class ArrayListExample {\n", - " private int findMin(int[] values) {\n", - " //int min = Integer.MAX_VALUE;\n", - " //for (int currentValue : values) {\n", - " // if (currentValue < min) {\n", - " // min = currentValue;\n", - " // }\n", - " //}\n", - " return min;\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " int[] nums = {420, 703, 2034, 582, 1047, 4545};\n", - " ArrayListExample example = new ArrayListExample();\n", - " int min = example.findMin(nums);\n", - " System.out.println(\"Minimum value: \" + min);\n", - " }\n", - "}\n", - "\n", - "ArrayListExample.main(null);\n", - "Now, can we use ArrayLists to make this code better? We sure can! Take a look at the new and improved code that uses ArrayLists:\n", - "public class ArrayListExample {\n", - " private int findMin(ArrayList<Integer> values) {\n", - " //int min = Integer.MAX_VALUE;\n", - " //for (int currentValue : values) {\n", - " // if (currentValue < min) {\n", - " // min = currentValue;\n", - " // }\n", - " //}\n", - " return min;\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " ArrayList<Integer> nums = new ArrayList<>();\n", - " nums.add(420);\n", - " nums.add(703);\n", - " nums.add(2034);\n", - " nums.add(582);\n", - " nums.add(1047);\n", - " nums.add(4545);\n", - " ArrayListExample example = new ArrayListExample();\n", - " int min = example.findMin(nums);\n", - " System.out.println(\"Minimum value: \" + min);\n", - " }\n", - "}\n", - "\n", - "ArrayListExample.main(null);\n", - "### Hacks\n", - "\n", - "- Answer the questions: \n", - " * Look back at the examples. What's similar? What's different?\n", - " * Why do we use `ArrayList`? Why not just regular lists?\n", - "- Demonstrate at least two `ArrayList` methods that aren't `ArrayList<>.size()` and `ArrayList<>.get()`.\n", - "- Write the method `findSum()` using the Hack Helper and incorporating `ArrayList`.\n", - "### Hack Helper\n", - "public class ArrayListHacks {\n", - " private int findSum(ArrayList<Integer> values) {\n", - " // Your code here\n", - " return 0;\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " ArrayList<Integer> nums = new ArrayList<>();\n", - " nums.add(0);\n", - " nums.add(1);\n", - " nums.add(2);\n", - " nums.add(3);\n", - " nums.add(5);\n", - " nums.add(8);\n", - "\n", - " ArrayListHacks hacks = new ArrayListHacks();\n", - " hacks.findSum(nums);\n", - " }\n", - "}\n", - "\n", - "ArrayListHacks.main(null);\n", - "# 7.5 Searching\n", - "\n", - "### Learning Objectives\n", - "- Apply sequential/linear search algorithms to search for specific information in array or ``arraylist`` objects\n", - "\n", - "### Essential Knowledge:\n", - "- Sequential/linear search alogorithms check each element in order untill the desired value is found or all elementsin the array or ``arraylist`` have been checked\n", - "\n", - "### Search Process\n", - "- Linear searching fits a standard for loop perfectly! We need to specify each element, one at a time, and do not need to track the index after execution\n", - "\n", - "- Inside the for loop, we retrieve the value from the structure at the specified index and compare it to the searched value\n", - "\n", - "- If it matches we return the index, otherwise we keep looking!\n", - "### Searching Linear Structures\n", - "\n", - "#### Finding information with a computer is something we need to know how to do. Linear search algorithms are BEST used when we do not have any idea about the order of the data and so we need to look at each element to determine if what we are looking for is in fact inside the array or ``ArrayList``.\n", - "\n", - "#### When searching, we do need to remember that different data types require comparisons!\n", - "- When looking at ``int`` values, the == operator is the tool to use!\n", - "- When searching for a ``double`` value, we need to make sure the value is close enough by doing some math!\n", - "- ``Object`` instances should always use the ``.equals(otheThing)`` method to check for a match!\n", - "## Searching an ``ArrayList`` of Double\n", - "public int where(double magicNumber, ArrayList<Double> realNumbers, double delta)\n", - "{\n", - " for (int index = 0; index < realNumbers.size(); index++)\n", - " {\n", - " if (Math.abs(magicNumber - realNumbers.get(index)) < delta)\n", - " {\n", - " return index;\n", - " }\n", - " }\n", - " return -1;\n", - "}\n", - "### Explanation\n", - "> The where function searches through a list of numbers to find and return the position of the first number that is very close to a specific target number, known as magicNumber. If no number in the list is close enough to the target number, the function returns -1, indicating that no match was found.\n", - "## Searching an ``ArrayList`` of book for a ``String``\n", - "public int findTheWord(String searchedPhrase, ArrayList<Book> myBooks)\n", - "{\n", - " for (int index = 0; index < myBooks.size(); index++)\n", - " {\n", - " Book currentBook = myBooks.get(index);\n", - " String currentPhrase = currentBook.getDescription();\n", - " if(currentPhrase.equals(searchedPhrase))\n", - " {\n", - " return index;\n", - " }\n", - " }\n", - " return -1;\n", - "}\n", - "### Explanation\n", - ">This little code snippet is like a treasure hunt through a collection of books; it's on a mission to find the one book whose description matches exactly with a special phrase you're looking for. If it finds the perfect match, it'll excitedly tell you where it is in the collection, but if not, it'll sadly let you know with a -1 that the search was a bust.\n", - "\n", - "\n", - "\n", - "\n", - "## Questions\n", - "\n", - "#### Should we use == when looking for an Object?\n", - "> No, that only will return true if the variable and the element stored at that index point to the same memory, are aliases of each other\n", - "\n", - "#### Why did we subtract the double values?\n", - "> To make sure that the lack of preciosin that is inherit in the data type is handled within our code\n", - "## Why does order sometimes matter?\n", - "\n", - "#### When searching for a value to remove from a list, if we search forward we have to make sure to adjust the loop control variable, or we might skip what we are looking for when removing!\n", - "# 7.6 Sorting\n", - "\n", - "### Learning Objectives\n", - "- Apply selection sort and insertion sort algorithms to sort the elements of array or ``ArrayList`` objects.\n", - "\n", - "### Essential Knowledge:\n", - "- Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ``ArrayList``.\n", - "\n", - "\n", - "## Selection Sort\n", - "> This is one of the easiest sorts to demonstrate. The selection sort identifies either the maximum or minimum of the compared values and iterates over the structure checking if the item stored at the index matches that condition, if so, it will swap the value stored at that index and continue. This implementation uses a helper method to perform the swap operation since variables can hold only one value at a time!\n", - "\n", - "Example:\n", - "// with normal arrays\n", - "for (int outerLoop = 0; outerLoop < myDucks.length; outerLoop ++)\n", - "{\n", - " int minIndex = outerLoop;\n", - " for (int inner = outerLoop +1; inner < myDucks.length; inner++)\n", - " {\n", - " if (myDucks[inner].compareT(myDucks[minIndex]) < 0)\n", - " {\n", - " minIndex = inner;\n", - " }\n", - " }\n", - " if (minIndex != outerLoop)\n", - " {\n", - " swapItems(minIndex, outerloop, myDucks);\n", - " }\n", - "}\n", - "\n", - "// with array lists\n", - "for (int outerLoop = 0; outerLoop < myDucks.size(); outerLoop++) {\n", - " int minIndex = outerLoop;\n", - " for (int inner = outerLoop + 1; inner < myDucks.size(); inner++) \n", - " {\n", - " if (myDucks.get(inner).compareT(myDucks.get(minIndex)) < 0) \n", - " {\n", - " minIndex = inner;\n", - " }\n", - " }\n", - " if (minIndex != outerLoop) {\n", - " swapItems(minIndex, outerLoop, myDucks); \n", - " }\n", - "}\n", - "/*\n", - "This code performs a selection sort on the myDucks ArrayList, ordering its elements based on the compareT method. \n", - "During each iteration of the outer loop, it finds the index of the minimum element in the unsorted portion of the list and swaps it with the first element of the unsorted portion.\n", - " */ \n", - "## Insertion Sort Algorithm\n", - "> The insertion sort is characterized by building a sorted structure as it proceeds. It inserts each value it finds at the appropriate location in the data structure. This is often accomplished by using a while loop as the inner loop.\n", - "\n", - "Example:\n", - "for (int outer = 1; outer < randomList.size(); outer++)\n", - "{\n", - " DebugDuck tested = randomList.get(outer);\n", - " int inner = outer -1;\n", - "\n", - " while ( innter >= 0 && tested.compareTo(randomList.get(inner)) < 0)\n", - " {\n", - " ramdomList.set(inner +1, randomList.get(inner));\n", - " inner--;\n", - " }\n", - " randomList.set(inner +1, tested)\n", - "}\n", - "// This code arranges a list of DebugDuck objects in order using the insertion sort method, \n", - "// by moving through the list and putting each item in its proper place one by one.\n", - "# 7.7: Ethical Issues around Data Collection\n", - "### Learning Objectives:\n", - "- Explaining the risks of privacy from collecting and storing personal data on computer systems.\n", - "\n", - "### Essential Knowledge:\n", - "- When using the computer, personal privacy is at risk. Programmers should attempt to safeguard personal privacy.\n", - "#### Privacy Protection:\n", - "- A simple way to protect privacy is to delete personal user info after done using it.\n", - "- Another way is to minimize the amount of data used by the program in order to protect privacy.\n", - "- Anonymizing personal data via the object method *hashCode()* is another way.\n", - "## Hacks:\n", - "- Think of other ways to safeguard user privacy (any other method not listed is fine)\n", - "- Extra points to creative solutions\n", - "- 90% credit to any solution\n", - "- 80% credit to incomplete solution (how did you do that?)\n", - "- -10% deduction for late submition\n", - "# Grading:\n", - "\n", - "- 7.2 Hacks (0.19)\n", - "- 7.3 Hacks (0.19)\n", - "- 7.4 Hacks (0.19)\n", - "- 7.7 Hacks (0.19)\n", - "- Popcorn Hacks (0.19)\n", - "- Anything else creative or above-and-beyond showing your understanding of ArrayLists (0.05)" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u1quiz.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u1quiz.ipynb deleted file mode 100644 index 48ce840bc0..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u1quiz.ipynb +++ /dev/null @@ -1,198 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Unit-1-Quiz]\n", - "lesson_language: Java\n", - "lesson_topic: Unit-1-Quiz\n", - "lesson_part: interactive\n", - "lesson_type: quiz\n", - "toc: true\n", - "title: Unit 1 Quiz\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/quiz\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Unit 1: Primitive Types" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Question 1\n", - "\n", - "Which of the following is a valid declaration of a variable of type int in Java?<br>\n", - "a) int 123variable;<br>\n", - "b) int variable123;<br>\n", - "c) int variable#123;<br>\n", - "d) int variable 123;\n", - "\n", - "Answer: b) int variable123;\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// Q1 Hack: Define variables according to Java naming conventions.\n", - "// For instance, is it snake_case, camelCase, or PascalCase?\n", - "\n", - "int variable123 = 123;\n", - "System.out.println(variable123);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Question 2\n", - "\n", - "What is the value of the following expression in Java: 5 / 2?<br>\n", - "a) 2.5<br>\n", - "b) 3<br>\n", - "c) 2<br>\n", - "d) 2.0\n", - "\n", - "Answer: c) 2\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// Q2.1 Hack: Show in code difference between integer and floating point division.\n", - "// Q2.2 Hack: Show in code the differnt number types in Java and how they behave.\n", - "// Behave means definition and assignment." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "### Question 3\n", - "\n", - "Which primitive type is used to represent a single character in Java?<br>\n", - "a) char<br>\n", - "b) String<br>\n", - "c) int<br>\n", - "d) byte\n", - "\n", - "Answer: a) char" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "// Q3.1 Hack: Show in code all the the non-number Java primitive data types and how they behave.\n", - "// Q3.2 Hack: Show in code the String data type and how it behaves." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Question 4\n", - "\n", - "Answer the following questions based on the code cell:\n", - "* a) What kind of types are person1 and person2? \n", - "* Answer: \n", - "* b) Do person1 and person3 point to the same value in memory?\n", - "* Answer:\n", - "* c) Is the integer \"number\" stored in the heap or in the stack?\n", - "* Answer:\n", - "* d) Is the value that \"person1\" points to stored in the heap or in the stack?\n", - "* Answer: " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "public class Person {\n", - " String name;\n", - " int age;\n", - " int height;\n", - " String job;\n", - "\n", - " public Person(String name, int age, int height, String job) {\n", - " this.name = name;\n", - " this.age = age;\n", - " this.height = height;\n", - " this.job = job;\n", - " }\n", - "}\n", - "\n", - "public static void main(String[] args) {\n", - " Person person1 = new Person(\"Carl\", 25, 165, \"Construction Worker\");\n", - " Person person2 = new Person(\"Adam\", 29, 160, \"Truck Driver\");\n", - " Person person3 = person1;\n", - " int number = 16;\n", - " System.out.println(number);\n", - "}\n", - "main(null); // This is required in Jupiter Notebook to run the main method." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Question 5 \n", - "\n", - "(a) Define primitive types and reference types in Java. The application is for banking, where you need to represent customer information.\n", - "\n", - "(b) Add comments for primitive types and reference types. In terms of memory allocation, discuss concepts like instance, stack, and heap where it adds value.\n", - "\n", - "(c) To assist in requirements, here are some required elements:\n", - "- Create multiple customers from the `public class Account`.\n", - "- Consider key class variables that a Bank may require: `name`, `balance`, `accountNumber`.\n", - "- Create a two argument constructor using `name` and `balance`.\n", - "- Consider in constructor how you will create a unique account number using `static int lastAccountNumber`\n", - "- Define a method `calculateInterest` that works with getting and setting `double balance` using `private static double interestRate`." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "java", - "pygments_lexer": "java", - "version": "17.0.12+0" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u2quiz.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u2quiz.ipynb deleted file mode 100644 index 594349b10a..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u2quiz.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "95c59622", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 2} }\n", - "categories: [Java, Unit-2-Quiz]\n", - "lesson_language: Java\n", - "lesson_topic: Unit-2-Quiz\n", - "lesson_part: interactive\n", - "lesson_type: quiz\n", - "toc: true\n", - "title: Unit 2 Quiz\n", - "menu: nav/csa_units/csaunit2.html\n", - "permalink: /csa/unit_02/quiz\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u3quiz.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u3quiz.ipynb deleted file mode 100644 index 28b5ec1475..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u3quiz.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "6d222dff", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 3} }\n", - "categories: [Java, Unit-3-Quiz]\n", - "lesson_language: Java\n", - "lesson_topic: Unit-3-Quiz\n", - "lesson_part: interactive\n", - "lesson_type: quiz\n", - "toc: true\n", - "title: Unit 3 Quiz\n", - "menu: nav/csa_units/csaunit3.html\n", - "permalink: /csa/unit_03/quiz\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u4quiz.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u4quiz.ipynb deleted file mode 100644 index 6adf6bf626..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-09-21-u4quiz.ipynb +++ /dev/null @@ -1,31 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "26a9e413", - "metadata": {}, - "source": [ - "---\n", - "layout: post\n", - "courses: { csa: {week: 4} }\n", - "categories: [Java, Unit-4-Quiz]\n", - "lesson_language: Java\n", - "lesson_topic: Unit-4-Quiz\n", - "lesson_part: interactive\n", - "lesson_type: quiz\n", - "toc: true\n", - "title: Unit 4 Quiz\n", - "menu: nav/csa_units/csaunit4.html\n", - "permalink: /csa/unit_04/quiz\n", - "---" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-12-1.13-homeworkGrinders.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-12-1.13-homeworkGrinders.ipynb deleted file mode 100644 index db0927c15d..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-12-1.13-homeworkGrinders.ipynb +++ /dev/null @@ -1,137 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "354709c5", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Object-Creation-and-Storage]\n", - "lesson_language: Java\n", - "lesson_topic: Object-Creation-and-Storage\n", - "lesson_part: interactive\n", - "lesson_type: homework\n", - "toc: true\n", - "title: Object Creation and Storage (Instantiation)\n", - "permalink: /csa/unit_01/1_13/homework\n", - "authors: Nora, Soni, Avika\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4fa4bd60", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Homework Hack #1: Object Creation Practice\n", - "\n", - "public class ObjectCreation {\n", - " public static void main(String[] args) {\n", - " // 1. Create two Car objects using 'new'\n", - " // Example: Car car1 = new Car(\"Tesla\", 2024);\n", - "\n", - " // 2. Print each car's info\n", - " // Example: System.out.println(car1);\n", - " }\n", - "}\n", - "\n", - "class Car {\n", - " // 1. Declare variables: brand, year\n", - "\n", - " // 2. Create a constructor to set those variables\n", - "\n", - " // 3. Add a method or toString() to display car info\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "5dfeb6ec", - "metadata": {}, - "source": [ - "## Homework Hack #2 — Heap vs Stack Storage Demo\n", - "\n", - "**Goal** - Understand where data is stored in memory — stack vs heap.\n", - "<br>\n", - "Instructions:\n", - "- Create a Book class with one variable: String title.\n", - "- In main(), create:\n", - "- A primitive variable (e.g. int pages = 300;)\n", - "- A Book object (e.g. Book b1 = new Book(\"Java Basics\");)\n", - "- Copy both into new variables (int pagesCopy = pages;, Book b2 = b1;)\n", - "<br>\n", - "Change the original values and print everything — watch what changes." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "87b5929f", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Homework Hack #2: Heap vs Stack Storage Demo\n", - "\n", - "public class HeapVsStack {\n", - " public static void main(String[] args) {\n", - " // 1. Create a primitive variable (int pages)\n", - " \n", - " // 2. Create another primitive variable that copies it\n", - " \n", - " // 3. Create a Book object (Book b1 = new Book(\"Java Basics\");)\n", - " \n", - " // 4. Create another Book reference (Book b2 = b1;)\n", - " \n", - " // 5. Change the original primitive and the Book title\n", - " \n", - " // 6. Print both sets of values to compare behavior\n", - " }\n", - "}\n", - "\n", - "class Book {\n", - " // 1. Declare variable: String title\n", - " \n", - " // 2. Create a constructor to set the title\n", - " \n", - " // 3. Create a toString() to show the title\n", - "}\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv (3.12.5)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.5" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-12-1.13-object_creationGrinders.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-12-1.13-object_creationGrinders.ipynb deleted file mode 100644 index d394bcb614..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-12-1.13-object_creationGrinders.ipynb +++ /dev/null @@ -1,774 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "8a9ce0fe", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Object-Creation-and-Storage]\n", - "lesson_language: Java\n", - "lesson_topic: Object-Creation-and-Storage\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "toc: true\n", - "title: Object Creation and Storage (Instantiation)\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_13\n", - "authors: Nora, Soni, Avika\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "e09ebd64", - "metadata": {}, - "source": [ - "# Learning Objectives\n", - "## By the end of this lesson, you will be able to:\n", - "\n", - "1. Understand how Java assigns memory for objects and primitives\n", - "\n", - "2. Tell the difference between stack and heap memory\n", - "\n", - "3. Explain the difference between pass-by-value and pass-by-reference\n", - "\n", - "4. Create and instantiate objects using constructors" - ] - }, - { - "cell_type": "markdown", - "id": "6ef5fab4", - "metadata": {}, - "source": [ - "## Brief Overview\n", - "| Concept | Easy Explanation |\n", - "|-------------------|---------------------------------------------------|\n", - "| Memory for objects | Java puts tiny toys on your desk, big toy boxes in another room |\n", - "| Stack | Your desk — for small things |\n", - "| Heap | The playroom — for big things |\n", - "| Pass-by-value | You share a copy of your toy |\n", - "| Pass-by-reference | You share the same toy box |\n", - "| Constructor | A machine that builds your toy boxes (objects) |\n" - ] - }, - { - "cell_type": "markdown", - "id": "8d13d437", - "metadata": {}, - "source": [ - "## What is Instantiation?\n", - "Instantiation is the process of creating an actual instance **(object)** of a class. When you instantiate an object, you're allocating memory and initializing it based on the class blueprint." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f72da81f", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "// Class Dog is the blueprint\n", - "class Dog {\n", - " String name;\n", - " int age;\n", - "}\n", - "\n", - "// Instantiation creates objects from the blueprint\n", - "Dog myDog = new Dog(); // Creating an instance\n", - "Dog yourDog = new Dog(); // Creating another instance" - ] - }, - { - "cell_type": "markdown", - "id": "bb803cdc", - "metadata": {}, - "source": [ - "Think of a class as a cookie cutter and objects as the actual cookies you make with it!\n", - "\n", - "<img src=\"{{site.baseur}}/images/Cookie.png\" alt=\"cookie analogy\" width=\"200\" height=\"200\">\n" - ] - }, - { - "cell_type": "markdown", - "id": "a6533bcd", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "1004c6f5", - "metadata": {}, - "source": [ - "# Memory Allocation: Stack and Heap" - ] - }, - { - "cell_type": "markdown", - "id": "27e2fe30", - "metadata": {}, - "source": [ - "In Java, memory allocation for variables occurs in two main areas: \n", - "1. the stack \n", - "2. the heap\n", - "\n", - "Stack and Heap are places where you can send your data to be used later!" - ] - }, - { - "cell_type": "markdown", - "id": "93f13f75", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "52a8704f", - "metadata": {}, - "source": [ - "# Stack Memory" - ] - }, - { - "cell_type": "markdown", - "id": "a4b97f4c", - "metadata": {}, - "source": [ - "Stack memory operates on a Last-In-First-Out idea, like a stack of plates, you can only grab one from the top, not from the middle." - ] - }, - { - "cell_type": "markdown", - "id": "d75aa327", - "metadata": {}, - "source": [ - "### Charecteristics\n", - "\n", - "- Stores primitive data types (int, double, boolean, char, etc.)\n", - "- Each thread has its own stack (thread-safe)\n", - "- Automatically managed - memory is freed when method returns\n", - "- Fast allocation and deallocation\n", - "- Limited in size (can cause StackOverflowError)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "867d5dff", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "public class StackDemo {\n", - " public static void main(String[] args) {\n", - " int number = 100; // Primitive stored in stack\n", - " double price = 49.99; // Primitive stored in stack\n", - " boolean isActive = true; // Primitive stored in stack\n", - " String name; // Reference stored in stack (and in heap)\n", - " \n", - " System.out.println(\"Number: \" + number);\n", - " System.out.println(\"Price: \" + price);\n", - " System.out.println(\"Is Active: \" + isActive);\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "deae96f3", - "metadata": {}, - "source": [ - "**College Board tests these concepts!**\n", - "\n", - "- Primitives point directly to their value - Since primitives are always on the stack they contain their actual value, not a reference.\n", - "\n", - "- Reference types contain an address - A reference variable (like for objects) contains the memory address where the actual object lives on the heap.\n", - "\n", - "- Method parameters create copies - Passing a variable to a method creates a copy of that variable's content.\n", - "\n", - "- Pass-by-value for primitives - Changes to primitive parameters inside a method don't affect the original variable.\n", - "\n", - "- Pass-by-reference for objects - Since references are copied, changes to object contents ARE reflected in the original object.\n" - ] - }, - { - "cell_type": "markdown", - "id": "3ac0b09d", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "591f2c9b", - "metadata": {}, - "source": [ - "# Heap Memory\n" - ] - }, - { - "cell_type": "markdown", - "id": "2418d5e7", - "metadata": {}, - "source": [ - "Heap memory is like a playroom, filled with toys (data/primitives) everywhere that you can grab in any order" - ] - }, - { - "cell_type": "markdown", - "id": "519bedde", - "metadata": {}, - "source": [ - "<img src=\"{{site.baseur}}/images/plates.png\" alt=\"plates analogy\" width=\"256\" height=\"150\">" - ] - }, - { - "cell_type": "markdown", - "id": "64c4425e", - "metadata": {}, - "source": [ - "## Characteristics:\n", - "\n", - "- Used for storing objects and arrays\n", - "- Shared among all threads (requires synchronization)\n", - "- Larger than stack memory\n", - "- Slower allocation compared to stack \n", - "- Objects live here until no references point to them" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5401f6ca", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "public class HeapDemo {\n", - " public static void main(String[] args) {\n", - "\n", - " // Explicit object creation\n", - " String message = new String(\"Hello\"); // Object created on heap, \n", - " // message is referenced in the stack\n", - "\n", - " // Arrays stored on heap\n", - " int[] numbers = new int[5]; // Array object on heap\n", - " // numbers reference is on stack\n", - " \n", - " // Custom objects\n", - " Dog myDog = new Dog(); // Dog object on heap\n", - " // myDog reference is on stack\n", - " \n", - " System.out.println(\"Message: \" + message);\n", - " System.out.println(\"Numbers array length: \" + numbers.length);\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "8b6df5df", - "metadata": {}, - "source": [ - "### Heap Variables --> Tips\n", - "\n", - "- Heap variables stay alive as long as at least one stack variable points to them. \n", - "\n", - "- All reference data types refer to an address on the stack but change content on the heap.\n", - "\n", - "- Objects created in the heap are globally accessible and can be shared among multiple methods" - ] - }, - { - "cell_type": "markdown", - "id": "b244b5ac", - "metadata": {}, - "source": [ - "# Popcorn Hack #1: Stack vs Heap\n", - "Run the following code in your own notebook and observe:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "59798803", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "public class MemoryDemo {\n", - " public static void main(String[] args) {\n", - " // Stack variables\n", - " int a = 10;\n", - " int b = a; // Copy of value\n", - " b = 20; // Changing b doesn't affect a\n", - " \n", - " System.out.println(\"Primitives (Stack):\");\n", - " System.out.println(\"a = \" + a); // Still 10\n", - " System.out.println(\"b = \" + b); // Now it's 20\n", - " \n", - " // Heap variables\n", - " int[] array1 = {1, 2, 3};\n", - " int[] array2 = array1; // Copy of reference (address)\n", - " array2[0] = 99; // Changing array2 DOES affect array1\n", - " \n", - " System.out.println(\"\\nArrays (Heap):\");\n", - " System.out.println(\"array1[0] = \" + array1[0]); // Now it's 99!\n", - " System.out.println(\"array2[0] = \" + array2[0]); // Also 99\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "10f3e55a", - "metadata": {}, - "source": [ - "## Tasks:\n", - "**Answer in a few sentences in your notebook**\n", - "\n", - "1. Why does changing b not affect a, but changing array2 affects array1?\n", - "\n", - "2. Describe what's on the stack vs. the heap for this code." - ] - }, - { - "cell_type": "markdown", - "id": "034e7e4b", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "52991337", - "metadata": {}, - "source": [ - "# Pass-by-Value vs Pass-by-Reference\n", - "This is critical for College Board CSA AP Exam!" - ] - }, - { - "cell_type": "markdown", - "id": "b82f4218", - "metadata": {}, - "source": [ - "## Key Concepts:\n", - "### Pass-by-Value (Primitives):\n", - "\n", - "When you pass a primitive to a method, Java copies the value\n", - "Changes inside the method do NOT affect the original variable\n", - "\n", - "### Pass-by-Reference (Objects):\n", - "\n", - "When you pass an object to a method, Java copies the reference (address)\n", - "Changes to the object's contents ARE reflected in the original object\n", - "However, reassigning the reference itself doesn't affect the original reference" - ] - }, - { - "cell_type": "markdown", - "id": "e5f62f40", - "metadata": {}, - "source": [ - "## Example: pass-by-value" - ] - }, - { - "cell_type": "markdown", - "id": "47005ecd", - "metadata": {}, - "source": [ - "### Pass-by-Value (Copy of the toy)\n", - "\n", - "Imagine you have a toy car.\n", - "You give a copy of it to your friend.\n", - "If your friend paints the copy red, your original toy doesn’t change." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8812325f", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Main method before changeInt(n): n = 5\n", - "In changeInt method\n", - "\tBefore n += 10: n = 5\n", - "\tAfter n += 10: n = 15\n", - "Main method after changeInt(n): n = 5\n" - ] - } - ], - "source": [ - "public class IntByValue {\n", - "\n", - " // Method tries to change the number\n", - " public static void changeInt(int n) {\n", - " n = n + 10; // only changes the copy\n", - " System.out.println(\"Inside method: n = \" + n);\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " int n = 5; // original number\n", - " System.out.println(\"Before method: n = \" + n);\n", - "\n", - " changeInt(n); // pass copy of n\n", - " System.out.println(\"After method: n = \" + n); // still 5\n", - " }\n", - "}\n", - "\n", - "// Run main manually\n", - "IntByValue.main(null);" - ] - }, - { - "cell_type": "markdown", - "id": "13381ac4", - "metadata": {}, - "source": [ - "## Example: pass-by-refrence" - ] - }, - { - "cell_type": "markdown", - "id": "2f5acc25", - "metadata": {}, - "source": [ - "### Pass-by-Reference (Shared toy box)\n", - "\n", - "Now imagine a toy box with many toys inside.\n", - "You give your friend the address of your toy box, not a copy.\n", - "If your friend paints a toy inside the box, your toys also change, because it’s the same box." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d316510d", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Before: 21 16\n", - "After: 16 21\n", - "\n", - "Before: 16 21\n", - "After: 16 21\n", - "\n", - "Before: 16 -1\n", - "After: -1 16\n", - "\n" - ] - } - ], - "source": [ - "// A simple class to hold a number\n", - "class NumberHolder {\n", - " int value;\n", - "\n", - " NumberHolder(int value) {\n", - " this.value = value;\n", - " }\n", - "}\n", - "\n", - "public class PassByReferenceDemo {\n", - " // Method that changes the object's value\n", - " public static void changeValue(NumberHolder n) {\n", - " n.value = n.value + 10; // modify the object\n", - " }\n", - "\n", - " public static void main(String[] args) {\n", - " NumberHolder myNumber = new NumberHolder(5); // create object\n", - " System.out.println(\"Before: \" + myNumber.value); // 5\n", - "\n", - " changeValue(myNumber); // pass object reference\n", - " System.out.println(\"After: \" + myNumber.value); // 15\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "d6dd1cf7", - "metadata": {}, - "source": [ - "# Popcorn Hack #2: Understanding Pass-by-Reference\n", - "Examine the code below and predict the output before running it:" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "5e56fb28", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [], - "source": [ - "public class PersonDemo {\n", - " static class Person {\n", - " String name;\n", - " int age;\n", - " \n", - " Person(String name, int age) {\n", - " this.name = name;\n", - " this.age = age;\n", - " }\n", - " }\n", - " \n", - " public static void haveBirthday(Person p) {\n", - " p.age = p.age + 1; // Modifying object content\n", - " System.out.println(\"Inside method: \" + p.name + \" is now \" + p.age);\n", - " }\n", - " \n", - " public static void reassignPerson(Person p) {\n", - " p = new Person(\"New Person\", 99); // Reassigning reference\n", - " System.out.println(\"Inside reassign: \" + p.name + \" is \" + p.age);\n", - " }\n", - " \n", - " public static void main(String[] args) {\n", - " Person john = new Person(\"John\", 20);\n", - " \n", - " System.out.println(\"Before birthday: \" + john.name + \" is \" + john.age);\n", - " haveBirthday(john);\n", - " System.out.println(\"After birthday: \" + john.name + \" is \" + john.age);\n", - " \n", - " System.out.println(\"\\nBefore reassign: \" + john.name + \" is \" + john.age);\n", - " reassignPerson(john);\n", - " System.out.println(\"After reassign: \" + john.name + \" is \" + john.age);\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "236867fa", - "metadata": {}, - "source": [ - "## Questions:\n", - "\n", - "1. After haveBirthday(john) is called, what is John's age? Why?\n", - "\n", - "2. After reassignPerson(john) is called, what is John's name and age? Why?\n", - "\n", - "3. Explain the difference between modifying an object's contents vs. reassigning a reference." - ] - }, - { - "cell_type": "markdown", - "id": "650660e9", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "a8c8d279", - "metadata": {}, - "source": [ - "# Constructors and Object Creation\n", - "Constructors are special methods that initialize objects when they're created. Understanding constructors is essential for proper object instantiation." - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "2f8679ee", - "metadata": { - "vscode": { - "languageId": "java" - } - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Name: Nora, Grade: 111, GPA: 5.0\n", - "Name: Soni, Grade: 11, GPA: 1.0\n" - ] - } - ], - "source": [ - "// Basics:\n", - "public class Student {\n", - " private String name;\n", - " private int grade;\n", - " private double gpa;\n", - " \n", - " // Default constructor\n", - " public Student() {\n", - " this.name = \"Nora\";\n", - " this.grade = 111;\n", - " this.gpa = 5.0;\n", - " }\n", - " \n", - " // Parameterized constructor\n", - " public Student(String name, int grade, double gpa) {\n", - " this.name = name;\n", - " this.grade = grade;\n", - " this.gpa = gpa;\n", - " }\n", - " \n", - " public void display() {\n", - " System.out.println(\"Name: \" + name + \", Grade: \" + grade + \", GPA: \" + gpa);\n", - " }\n", - " \n", - " public static void main(String[] args) {\n", - " Student s1 = new Student();\n", - " Student s2 = new Student(\"Soni\", 11, 1.0);\n", - " \n", - " s1.display();\n", - " s2.display();\n", - " }\n", - "}\n", - "\n", - "Student.main(null);" - ] - }, - { - "cell_type": "markdown", - "id": "9195e39a", - "metadata": {}, - "source": [ - "## Constructor Types:\n", - "\n", - "1. **Default Constructor**: No parameters, sets default values\n", - "2. **Parameterized Constructor**: Takes parameters to initialize with specific values\n", - "3. **Copy Constructor**: Creates a new object as a copy of an existing object" - ] - }, - { - "cell_type": "markdown", - "id": "edc6c02d", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "bdd3d8f5", - "metadata": {}, - "source": [ - "# Key Takeaways\n", - "- Stack stores primitives and object references; Heap stores actual objects\n", - "\n", - "- Primitives are pass-by-value; Objects are pass-by-reference (reference is copied)\n", - "\n", - "- Understanding memory allocation helps debug issues and write efficient code\n", - "\n", - "- Constructors initialize objects when they're created\n", - "\n", - "- These concepts are frequently tested on the College Board AP CS A exam!" - ] - }, - { - "cell_type": "markdown", - "id": "037adf56", - "metadata": {}, - "source": [ - "----" - ] - }, - { - "cell_type": "markdown", - "id": "e8fd9a01", - "metadata": {}, - "source": [ - "# Homework" - ] - }, - { - "cell_type": "markdown", - "id": "cfddce37", - "metadata": {}, - "source": [ - "### Once you've finished the lesson and ran/wrote all the popcorn hacks in a notebook please start the homework here\n", - "\n", - "<a href=\"{{ site.baseurl }}/csa/unit_01/1_13/homework\">Homework</a>\n", - "\n", - "[Submission Form](https://docs.google.com/forms/d/e/1FAIpQLSezbH1C3-8a_UfyLjJ7vW-ZSZNPtEYFg5FhjMka0VNCpwAcrQ/viewform?usp=header)" - ] - }, - { - "cell_type": "markdown", - "id": "9ef77446", - "metadata": {}, - "source": [ - "---" - ] - }, - { - "cell_type": "markdown", - "id": "f5dbb5f8", - "metadata": {}, - "source": [ - "# Resources\n", - "\n", - "[AP classroom](https://apstudents.collegeboard.org/courses/ap-computer-science-a)\n", - "\n", - "[1.13 lesson (PAGE 53-54)](https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description.pdf)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Java", - "language": "java", - "name": "java" - }, - "language_info": { - "codemirror_mode": "java", - "file_extension": ".jshell", - "mimetype": "text/x-java-source", - "name": "Java", - "pygments_lexer": "java", - "version": "17.0.16+0" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-19-1.3-output-homework.ipynb b/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-19-1.3-output-homework.ipynb deleted file mode 100644 index c90f44e2dc..0000000000 --- a/_notebooks/CSA/ap_mcq_lessons/unit_01/2025-10-19-1.3-output-homework.ipynb +++ /dev/null @@ -1,169 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "45c46435", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Java, Expressions-and-Output]\n", - "lesson_language: Java\n", - "lesson_topic: Expressions-and-Output\n", - "lesson_part: interactive\n", - "lesson_type: homework\n", - "toc: true\n", - "title: Expressions and Output\n", - "menu: nav/csa_units/csaunit1.html\n", - "permalink: /csa/unit_01/1_3/homework\n", - "author: Ahaan, Arnav, Shaurya\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "baecbd6b", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "## Popcorn Hack 1\n", - "<div>\n", - " <label for=\"frq1\">Recall as many key formatting tools as you can without refering to the above section and list them here. Then, explain what each of them does. Finally, write a line of code using as many of the tools as you can.</label><br>\n", - " <textarea id=\"frq1\" rows=\"5\" cols=\"80\"></textarea><br>\n", - " <button onclick=\"saveFRQ('frq1')\">💾 Save Answer</button>\n", - "</div>\n", - "<script>\n", - "function saveFRQ(id) {\n", - " let val = document.getElementById(id).value;\n", - " localStorage.setItem(id, val);\n", - " alert(\"Answer saved!\");\n", - "}\n", - "window.addEventListener(\"load\", () => {\n", - " document.querySelectorAll(\"textarea\").forEach(t => {\n", - " let saved = localStorage.getItem(t.id);\n", - " if (saved) t.value = saved;\n", - " });\n", - "});\n", - "</script>\n", - "<br>" - ] - }, - { - "cell_type": "markdown", - "id": "9ec563b3", - "metadata": {}, - "source": [ - "## Popcorn Hack 2\n", - "<div>\n", - " <label for=\"frq2\">What are the formatting tools used here and what is their purpose? How do they make the output cleaner/better?<</label><br>\n", - " <textarea id=\"frq2\" rows=\"5\" cols=\"80\"></textarea><br>\n", - " <button onclick=\"saveFRQ('frq2')\">💾 Save Answer</button>\n", - "</div>\n", - "<script>\n", - "function saveFRQ(id) {\n", - " let val = document.getElementById(id).value;\n", - " localStorage.setItem(id, val);\n", - " alert(\"Answer saved!\");\n", - "}\n", - "window.addEventListener(\"load\", () => {\n", - " document.querySelectorAll(\"textarea\").forEach(t => {\n", - " let saved = localStorage.getItem(t.id);\n", - " if (saved) t.value = saved;\n", - " });\n", - "});\n", - "</script>\n", - "<br>" - ] - }, - { - "cell_type": "markdown", - "id": "5602d328", - "metadata": {}, - "source": [ - "## Homework Hack 1\n", - "1. **Predict Output**: What will this print?\n", - "```java\n", - "System.out.print(\"AP \");\n", - "System.out.println(\"CSA\");\n", - "System.out.println(\"Rocks!\");\n", - "```\n", - "\n", - "2. **Fix the Bug**: The following is supposed to print `C:\\Users\\Student`, but it fails. Correct it:\n", - "```java\n", - "System.out.println(\"C:\\Users\\Student\");\n", - "```\n", - "\n", - "3. **Menu Hack**: Add a 4th option (`Settings`) to `Menu.java` and update `optionCount` accordingly.\n", - "\n", - "4. **Challenge**: Use `System.out.printf` to print pi with 2 decimals.\n", - "```java\n", - "System.out.printf(\"Pi = %.2f\\n\", Math.PI);\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "d20bf63d", - "metadata": {}, - "source": [ - "## Homework Hack 2\n", - "- Expand `Menu.java` into a **calculator menu**:\n", - " 1. Print a menu with options: `Add`, `Subtract`, `Multiply`, `Divide`.\n", - " 2. Ask the user for two numbers.\n", - " 3. Use arithmetic expressions to compute and display the result.\n", - " 4. Example run:\n", - "```\n", - "==== Calculator Menu ====\n", - "1. Add\n", - "2. Subtract\n", - "3. Multiply\n", - "4. Divide\n", - "Choose an option: 1\n", - "Enter first number: 10\n", - "Enter second number: 5\n", - "Result: 15\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "c40315e1", - "metadata": {}, - "source": [ - "## Homework Hack 3 Game \n", - "\n", - "Here is the game that you will also be playing, to test your understanding of the lesson. You will screenshot the game score and submit it to the 1.3 google form (this will alos include 1.4 content, submission is for both)\n", - "\n", - "<a href=\"{{site.baseurl}}/csa/1_4/quiz\">1.3 and 1.4 Game</a>" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.3" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2024-11-09-lesson_outline.ipynb b/_notebooks/CSSE/JavaScriptLessons/2024-11-09-lesson_outline.ipynb deleted file mode 100644 index 96104b802f..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2024-11-09-lesson_outline.ipynb +++ /dev/null @@ -1,214 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "yaml" - } - }, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Planning]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Planning\n", - "lesson_part: reference\n", - "lesson_type: planning\n", - "title: Lesson Planning\n", - "description: Review this outline as a guide to assist in planning and teaching JavaScript lessons.\n", - "type: objectives\n", - "permalink: /csse/sprint2/outline\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "<img width=\"300\" height=\"742\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/6b90e734-a53a-4bb7-ba9c-d3623ca4a756\" />" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "## For **Students**\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>Before Class</strong></summary>\n", - "\n", - "- If you **don’t have Slack access on your school computer**:\n", - " - Bookmark lesson & homework links **before class**\n", - " - The Slack announcement with links should be posted by **7:30 AM**\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>Homework Rules</strong></summary>\n", - "\n", - "- Homework is due **48 hours after the Team Teach**\n", - "- You may submit up to **2 days late**\n", - "- Late penalty: **–0.1 points**\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>Extensions & Communication</strong></summary>\n", - "\n", - "- Request an extension by messaging **Anusha on Slack**\n", - " - Must be **1 day before the deadline**\n", - " - Must include a **valid reason**\n", - "- For homework help:\n", - " - Message the **students who taught the lesson**\n", - "- If you will be **absent on your presentation day**:\n", - " - Message **Anusha immediately**\n", - "- Poor communication may cause delays or point deductions\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>The Master Sheet (Official Grades)</strong></summary>\n", - "\n", - "[**Master Sheet Link**](https://docs.google.com/spreadsheets/d/16Z_z18CjgdK9-tCv6kKy4Vcq5fmjOY4OkWFkqBW10MM/edit?usp=sharing)\n", - "\n", - "- This is the **official record** of homework scores\n", - "- Anusha updates it periodically using grading sheets\n", - "\n", - "### Color Key\n", - "- **Red** → Late (past final deadline)\n", - "- **Blue** → Team Teach Teacher (no homework score for that lesson)\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "## For **Teachers**\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>Creating the Lesson</strong></summary>\n", - "\n", - "Lesson links must follow this format: https://pages.opencodingsociety.com/js/lesson_title\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>Before the Lesson</strong></summary>\n", - "\n", - "- Lesson & homework **fully completed and tested** by \n", - " **8:35 AM — the day before Team Teach**\n", - "- Final **pull request submitted** by \n", - " **4:00 PM — the day before Team Teach**\n", - "- Post Slack announcement in **#per1_teamteach** \n", - " **before 7:00 AM on Team Teach day**\n", - "\n", - "### Slack Post Must Include\n", - "- Homework deadline\n", - "- Group member names\n", - "- Lesson link\n", - "- Homework submission link (Google Form)\n", - "- Team Teach date\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>During the Lesson</strong></summary>\n", - "\n", - "- Walk around during work time\n", - "- Answer questions after popcorn hacks\n", - "- Help students who are stuck\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>Homework Grading Window</strong></summary>\n", - "\n", - "*(Final Deadline = when you submit the grading sheet)*\n", - "\n", - "> You do **NOT** submit homework for the lesson you teach.\n", - "\n", - "- Make a copy of the grading template\n", - "- Homework due for students:\n", - " - **48 hrs after lesson**\n", - " - **8:35 AM**\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>Final Deadline (Teachers)</strong></summary>\n", - "\n", - "- **Grading sheet due by 8:35 AM**\n", - "- Deadline is **72 hrs after the homework due date**\n", - "- This is the **absolute cutoff** for homework included\n", - "\n", - "### If a student submits AFTER you turn in the sheet:\n", - "- Student must message **your team directly**\n", - "- You grade the homework individually\n", - "- **Maximum score = 0.7**\n", - "- Report the score to **Anusha separately**\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>How to Grade Homework</strong></summary>\n", - "\n", - "Homework is graded on a **0.9-point scale** \n", - "*(Scores may be scaled later depending on class policy.)*\n", - "\n", - "### Grading Rules\n", - "- On-time & correct → score out of **0.9**\n", - "- Extra or unique effort → **0.91**\n", - "- Late (≤ 2 days) → **–0.1**, note “late”\n", - "- Missing → **0.55**, note “missing”\n", - "\n", - "### Every student must have:\n", - "- A score\n", - "- A written justification/comment\n", - "\n", - "</details>\n", - "\n", - "---\n", - "\n", - "<details markdown=\"1\">\n", - "<summary><strong>Grading Sheet Template</strong></summary>\n", - "\n", - "**Make a copy of the template** \n", - "[Click Here to Make a Copy](https://docs.google.com/spreadsheets/d/1Et2g2h0_pK0cyKN-LVVMqbF_2xjPbamI5ju-fnme7O8/copy)\n", - "\n", - "### You must:\n", - "- Copy the template\n", - "- Fill in **every student’s score**\n", - "- Include comments for late/missing work\n", - "- Submit the completed sheet to **Anusha** by your final deadline\n", - "\n", - "</details>\n" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2025-09-29-functions_tinkerers_js_lesson.ipynb b/_notebooks/CSSE/JavaScriptLessons/2025-09-29-functions_tinkerers_js_lesson.ipynb deleted file mode 100644 index a4253c6409..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2025-09-29-functions_tinkerers_js_lesson.ipynb +++ /dev/null @@ -1,1047 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "1a9e40c0", - "metadata": { - "vscode": { - "languageId": "yaml" - } - }, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Functions]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Functions\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "title: Functions\n", - "description: This lesson explains JavaScript functions.\n", - "author: Tinkerers - Anish G, James B, Vihaan B\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "eba067dc", - "metadata": {}, - "source": [ - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #8a2be2, /* Purple glow */\n", - " 0 0 20px #8a2be2, /* Deeper purple glow */\n", - " 0 0 30px #4169e1, /* Blue glow */\n", - " 0 0 40px #4169e1; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - "}\n", - "\n", - " .hw-btn {\n", - " background-color: #007bff; /* blue */\n", - " color: white; /* white text */\n", - " padding: 12px 20px; /* spacing */\n", - " border: none; /* remove default border */\n", - " border-radius: 12px; /* rounded corners */\n", - " font-size: 16px; /* slightly larger text */\n", - " cursor: pointer; /* pointer on hover */\n", - " transition: background-color 0.3s ease; /* smooth hover transition */\n", - " }\n", - "\n", - " .hw-btn:hover {\n", - " background-color: #0056b3; /* darker blue on hover */\n", - " }\n", - "\n", - "</style>\n", - "\n", - "<table>\n", - "\t<tr>\n", - "\t\t<th>Role</th>\n", - "\t\t<th>Name</th>\n", - "\t</tr>\n", - "\t<tr>\n", - "\t\t<td>📋 Scrum Master</td>\n", - "\t\t<td>Anish Gupta</td>\n", - "\t</tr>\n", - "\t<tr>\n", - "\t\t<td>💻 Scrummer</td>\n", - "\t\t<td>James Blazek</td>\n", - "\t</tr>\n", - "\t<tr>\n", - "\t\t<td>💻 Scummer</td>\n", - "\t\t<td>Vihaan Budhraja</td>\n", - "\t</tr>\n", - "</table>\n", - "\n", - "<br>\n", - "\n", - "<h2 class=\"glowing-text\">Setup</h2>\n", - "Copy the homework file into your personal repository by doing this:\n", - "\n", - "1. Open the `Open-Coding-Society/pages` repo in one VSCode window and your own `portfolio` repo in the other\n", - "2. Drag and drop `2025-09-29-functions_tinkerers_js_hw.ipynb` from pages to your own repo. It is in `_notebooks/CSSE/JavaScriptLessons/Functions`.\n", - "\n", - "Alternatively, you can use wget: \n", - "\n", - "```bash\n", - "# First cd to the base of your repo\n", - "\n", - "mkdir -p _notebooks/CSSE/JavascriptLessons/Functions\n", - "\n", - "wget -O _notebooks/CSSE/JavascriptLessons/Functions/2025-09-29-functions_js_tinkerers_hw \"https://raw.githubusercontent.com/Open-Coding-Society/pages/main/_notebooks/CSSE/JavaScriptLessons/Functions/2025-09-29-functions_js_tinkerers_hw.ipynb\"\n", - "```\n", - "\n", - "\n", - "Your homework is now copied into your personal repo! This notebook also contains popcorn hacks #1 and #2.\n", - "\n", - "\n", - "\n", - "<h2 class=\"glowing-text\">What are functions?</h2>\n", - "\n", - "\n", - "> Functions in programming are modular units of code designed to perform specific tasks. They encapsulate a set of instructions, allowing for code reuse and organization. - GeeksForGeeks\n", - "\n", - "Functions allow you to take a piece of code, and almost put it into a box so you can reuse it a lot of times. It also let you modularize code. For example, let's look at the code below." - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "0de26416", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "<div>\n", - " <h3>Program Output</h3>\n", - " <p id=\"output1\"></p>\n", - "</div>\n", - "\n", - "<script>\n", - "(() => {\n", - "let myname = \"Alice\";\n", - "let myage = 16;\n", - "let message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - "document.getElementById(\"output1\").innerText += message;\n", - "\n", - "\n", - "myname = \"Bob\";\n", - "myage = 999999999;\n", - "message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - "document.getElementById(\"output1\").innerText += \"\\n\" + message;\n", - "\n", - "myname = \"Charlie\";\n", - "myage = 1;\n", - "message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - "document.getElementById(\"output1\").innerText += \"\\n\" + message;\n", - "\n", - "\n", - "myname = \"Daniel\";\n", - "myage = 67;\n", - "message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - "document.getElementById(\"output1\").innerText += \"\\n\" + message;\n", - "})();\n", - "\n", - "</script>\n" - ], - "text/plain": [ - "<IPython.core.display.HTML object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%html\n", - "\n", - "<div>\n", - " <h3>Program Output</h3>\n", - " <p id=\"output1\"></p>\n", - "</div>\n", - "\n", - "<script>\n", - "(() => {\n", - "let myname = \"Alice\";\n", - "let myage = 16;\n", - "let message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - "document.getElementById(\"output1\").innerText += message;\n", - "\n", - "\n", - "myname = \"Bob\";\n", - "myage = 999999999;\n", - "message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - "document.getElementById(\"output1\").innerText += \"\\n\" + message;\n", - "\n", - "myname = \"Charlie\";\n", - "myage = 1;\n", - "message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - "document.getElementById(\"output1\").innerText += \"\\n\" + message;\n", - "\n", - "\n", - "myname = \"Daniel\";\n", - "myage = 67;\n", - "message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - "document.getElementById(\"output1\").innerText += \"\\n\" + message;\n", - "})();\n", - "\n", - "</script>" - ] - }, - { - "cell_type": "markdown", - "id": "ee6afbd9", - "metadata": {}, - "source": [ - "This code, while it works, has a lot of code that is reused. We can modularize this code as shown below." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "14265de6", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "<div>\n", - " <h3>Program Output</h3>\n", - " <p id=\"output2\"></p>\n", - "</div>\n", - "\n", - "<script>\n", - "(() => {\n", - " function greet(myname, myage){\n", - " message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - " document.getElementById(\"output2\").innerText += \"\\n\" + message;\n", - " }\n", - "\n", - " greet(\"Alice\", 16);\n", - " greet(\"Bob\", 999999999);\n", - " greet(\"Charlie\", 1);\n", - " greet(\"Daniel\", 67);\n", - "\n", - "})();\n", - "\n", - "</script>\n" - ], - "text/plain": [ - "<IPython.core.display.HTML object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%html\n", - "\n", - "<div>\n", - " <h3>Program Output</h3>\n", - " <p id=\"output2\"></p>\n", - "</div>\n", - "\n", - "<script>\n", - "(() => {\n", - " function greet(myname, myage){\n", - " message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - " document.getElementById(\"output2\").innerText += \"\\n\" + message;\n", - " }\n", - "\n", - " greet(\"Alice\", 16);\n", - " greet(\"Bob\", 999999999);\n", - " greet(\"Charlie\", 1);\n", - " greet(\"Daniel\", 67);\n", - "\n", - "})();\n", - "\n", - "</script>\n" - ] - }, - { - "cell_type": "markdown", - "id": "30a4b63c", - "metadata": {}, - "source": [ - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #8a2be2, /* Purple glow */\n", - " 0 0 20px #8a2be2, /* Deeper purple glow */\n", - " 0 0 30px #4169e1, /* Blue glow */\n", - " 0 0 40px #4169e1; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - "}\n", - "</style>\n", - "\n", - "<h2 class=\"glowing-text\">Try it out for yourself!</h2>\n", - "\n", - "<br>" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "7bf27bb2", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "<div>\n", - " <h3>Program Output</h3>\n", - " <p id=\"output3\"></p>\n", - "\n", - " <hr>\n", - " <label for=\"nameInput\">Name:</label>\n", - " <input type=\"text\" id=\"nameInput\" placeholder=\"Enter name\">\n", - " <label for=\"ageInput\">Age:</label>\n", - " <input type=\"number\" id=\"ageInput\" placeholder=\"Enter age\">\n", - " <button id=\"greetButton\">Greet</button>\n", - "</div>\n", - "\n", - "<script>\n", - "(() => {\n", - "\n", - " // Define greet() func\n", - "\n", - " function greet(myname, myage){\n", - " let message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - " document.getElementById(\"output3\").innerText += \"\\n\" + message;\n", - " }\n", - "\n", - " // calling it a few times with a few fixed parameters\n", - " greet(\"Alice\", 16);\n", - " greet(\"Bob\", 999999999);\n", - " greet(\"Charlie\", 1);\n", - " greet(\"Daniel\", 67);\n", - "\n", - " // user input\n", - " const nameInput = document.getElementById(\"nameInput\");\n", - " const ageInput = document.getElementById(\"ageInput\");\n", - " const greetButton = document.getElementById(\"greetButton\");\n", - "\n", - " greetButton.addEventListener(\"click\", () => {\n", - " const name = nameInput.value.trim();\n", - " const age = parseInt(ageInput.value, 10);\n", - " if(name && !isNaN(age)){\n", - " greet(name, age);\n", - " nameInput.value = \"\";\n", - " ageInput.value = \"\";\n", - " } else {\n", - " alert(\"Please enter a valid name and age!\");\n", - " }\n", - " });\n", - "\n", - "\n", - "})();\n", - "</script>\n" - ], - "text/plain": [ - "<IPython.core.display.HTML object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%html\n", - "\n", - "<div>\n", - " <h3>Program Output</h3>\n", - " <p id=\"output3\"></p>\n", - "\n", - " <hr>\n", - " <label for=\"nameInput\">Name:</label>\n", - " <input type=\"text\" id=\"nameInput\" placeholder=\"Enter name\">\n", - " <label for=\"ageInput\">Age:</label>\n", - " <input type=\"number\" id=\"ageInput\" placeholder=\"Enter age\">\n", - " <button id=\"greetButton\">Greet</button>\n", - "</div>\n", - "\n", - "<script>\n", - "(() => {\n", - "\n", - " // Define greet() func\n", - "\n", - " function greet(myname, myage){\n", - " let message = \"Hello, \" + myname + \" (\" + myage + \")!\";\n", - " document.getElementById(\"output3\").innerText += \"\\n\" + message;\n", - " }\n", - "\n", - " // calling it a few times with a few fixed parameters\n", - " greet(\"Alice\", 16);\n", - " greet(\"Bob\", 999999999);\n", - " greet(\"Charlie\", 1);\n", - " greet(\"Daniel\", 67);\n", - "\n", - " // user input\n", - " const nameInput = document.getElementById(\"nameInput\");\n", - " const ageInput = document.getElementById(\"ageInput\");\n", - " const greetButton = document.getElementById(\"greetButton\");\n", - "\n", - " greetButton.addEventListener(\"click\", () => {\n", - " const name = nameInput.value.trim();\n", - " const age = parseInt(ageInput.value, 10);\n", - " if(name && !isNaN(age)){\n", - " greet(name, age);\n", - " nameInput.value = \"\";\n", - " ageInput.value = \"\";\n", - " } else {\n", - " alert(\"Please enter a valid name and age!\");\n", - " }\n", - " });\n", - "\n", - "\n", - "})();\n", - "</script>\n" - ] - }, - { - "cell_type": "markdown", - "id": "c7bd3890", - "metadata": {}, - "source": [ - "<script src=\"https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js\"></script>\n", - "<script>\n", - " mermaid.initialize({ startOnLoad: true });\n", - "</script>\n", - "\n", - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #8a2be2, /* Purple glow */\n", - " 0 0 20px #8a2be2, /* Deeper purple glow */\n", - " 0 0 30px #4169e1, /* Blue glow */\n", - " 0 0 40px #4169e1; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - "}\n", - "</style>\n", - "\n", - "<br><br>\n", - "<div class=\"mermaid\">\n", - "flowchart LR\n", - " A[\"Inputs: Alice, 16\"] --> B[\"greet() function\"]\n", - " B --> C[\"Output: Hello, Alice (16)!\"]\n", - " A2[Inputs: Bob, 999999999] --> B\n", - " B --> C2[\"Output: Hello, Bob (999999999)!\"]\n", - " A3[Inputs: Charlie, 1] --> B\n", - " B --> C3[\"Output: Hello, Charlie (1)!\"]\n", - " A4[Inputs: myname, myage] --> B\n", - " B --> C4[\"Output: Hello, [myname] ([myage])!\"]\n", - "\n", - " classDef func fill:#4169e1,stroke:#333,stroke-width:2px,color:#ffffff;\n", - " class B func;\n", - "</div>\n", - "\n", - "<hr>\n", - "\n", - "<h2 class=\"glowing-text\">Defining Functions & Function Syntax</h2>\n", - "\n", - "The code to create a function is as follows:\n", - "\n", - "![](https://lh3.googleusercontent.com/proxy/8HuWupeaffPfTzROp_TE2Y4MlniKWW3BoSvSc3oJ35aCJHQbZR0_lmdvqF_bEVNEXzzG53puMLbuIzD1tcH5tfGfRx7sOMAJL_K07adSUML6FbJYOkxSF1pFGoMgXZEtmlxXC-Lq)\n", - "\n", - "Let's look at the below code.\n", - "\n", - "```\n", - "function add(a, b) {\n", - " return a + b;\n", - "}\n", - "```\n", - "\n", - "`add` is the name of the function. A common JavaScript convention is to use camelCase. Function names are usually verbs- like calculateSum(), drawText(), startGame(), etc. because they do something.\n", - "\n", - "`a` and `b` are parameters. You aren't fixed to 2 parameters: you can have one, three, zero, or five hundred (if you want to for some reason).\n", - "Parameters are like the input to a function: information that the function takes in to be proccessed.\n", - "\n", - "(Side note: Parameters are the variables listed in the function definition. Arguments are the actual values you pass when calling the function.)\n", - "\n", - "Next, we use curly braces { } to represent that \"hey, the code for **this function specifically** starts/ends here!\"\n", - "\n", - "The `return` keyword is the output of a function: Mozilla says that\n", - "> The return statement ends function execution and specifies a value to be returned to the function caller.\n", - "\n", - "Here's an example:\n", - "\n", - "```js\n", - "function add(a, b) {\n", - " return a + b;\n", - "}\n", - "\n", - "let result = add(5, 6);\n", - "console.log(result); // Logs 11\n", - "```\n", - "\n", - "\n", - "\n", - "Let's do a practice: what will the below function output and why?\n", - "\n", - "```js\n", - "function add(a, b){\n", - " console.log(a+b);\n", - "}\n", - "\n", - "let result = add(5, 6);\n", - "console.log(result);\n", - "```\n", - "\n", - "<details>\n", - " <summary>\n", - " View solution\n", - " </summary>\n", - "\n", - " The first log to the console will display 11. The second log will say undefined.\n", - " This is because the function is not returning anything, and result is being set to a value that does not exist.\n", - "\n", - "</details>\n", - "\n", - "\n", - "<h2 class=\"glowing-text\">Example of Returning in Word Game</h2>\n", - "\n", - "\n", - "```\n", - "\n", - "function wrapText(text, maxWidth) {\n", - " const words = text.split(' ');\n", - " const lines = [];\n", - " let currentLine = words[0];\n", - "\n", - " for (let i = 1; i < words.length; i++) {\n", - " const word = words[i];\n", - " const width = wordCtx.measureText(currentLine + ' ' + word).width;\n", - " if (width < maxWidth) {\n", - " currentLine += ' ' + word;\n", - " } else {\n", - " lines.push(currentLine);\n", - " currentLine = word;\n", - " }\n", - " }\n", - " lines.push(currentLine); // Add the last line\n", - " return lines;\n", - "}\n", - "\n", - "```\n", - "\n", - "<hr>\n", - "\n", - "<h2 class=\"glowing-text\">🍿 POPCORN HACK NO. 1 🍿</h2>\n", - "\n", - "Let's start making our own functions :)\n", - "Head over to `2025-09-29-functions_tinkerers_js_hw.ipynb` to do the popcorn hack.\n", - "Didn't download it yet? Check the **setup section** at the top of this lesson.\n", - "\n", - "<hr>\n", - "\n", - "\n", - "<h2 class=\"glowing-text\">More Function Use Cases</h2>\n", - "\n", - "![](https://media.geeksforgeeks.org/wp-content/uploads/20250721183631453591/Why-Use-Functions__.webp)\n", - "\n", - "\n", - "> Functions can be used to reuse code.\n", - "\n", - "Let's say I have a function that I need to call multiple times. For example, in Word Game, there is a function called drawText() with this code:\n", - "\n", - "```js\n", - "function drawText(text) {\n", - " wordCtx.clearRect(0, 0, wordCanvas.width, wordCanvas.height);\n", - " wordCtx.font = '24px \"Times New Roman\", Times, serif';\n", - " wordCtx.fillStyle = '#dededeff';\n", - " wordCtx.textAlign = 'center';\n", - "\n", - " const maxWidth = wordCanvas.width - 20; // Leave some padding\n", - " const lineHeight = 30; // Line height for wrapped text\n", - " const lines = wrapText(text, maxWidth);\n", - "\n", - " const startY = (wordCanvas.height - lines.length * lineHeight) / 2; // Center vertically\n", - " lines.forEach((line, index) => {\n", - " wordCtx.fillText(line, wordCanvas.width / 2, startY + index * lineHeight);\n", - " });\n", - "}\n", - "```\n", - "\n", - "This function is called *twice* in wordgame.md: once when the game starts and once to clear the canvas after done typing.\n", - "\n", - "This keeps us from having to write this code twice. Instead, we can define it ONCE and call it whenever we want: if we wanted to call it 67 times for some reason, instead of copy pasting the code 67 times, we can just call drawText() whenever needed.\n", - "\n", - "<h2 class=\"glowing-text\">Functions for Abstraction & Modularity</h2>\n", - "\n", - "<strong>ABSTRACTION</strong>\n", - "\n", - "> Functions in Programming allow programmers to abstract the details of a particular operation. Instead of dealing with the entire implementation, a programmer can use a function with a clear interface, relying on its functionality without needing to understand the internal complexities. *Functions hide the details of their operation, allowing the programmer to think at a higher level.* - GeeksForGeeks\n", - "\n", - "<strong>MODULARITY</strong>\n", - "\n", - "Using word game as an example, instead of implementing the whole program, we can tackle the steps one by one. These functions are:\n", - "\n", - "- `drawText(text)` – Draws the prompt text centered on the canvas\n", - "- `wrapText(text, maxWidth)` – Splits text into lines that fit within `maxWidth`\n", - "- `drawUserText(prompt, input)` – Draws the prompt and user input, highlighting correct/incorrect chars and showing the caret\n", - "- `updateStats(prompt, input, startTime)` – Updates WPM and accuracy stats\n", - "- `finishGame(prompt, input, startTime)` – Handles game end, calculates mistakes, and shows finish overlay\n", - "- `startGame()` – Starts a new game, picks a prompt, and sets up key input handling\n", - "- `setProgress(percent)` – Updates the progress bar width and text\n", - "- `updateProgress(prompt, input)` – Computes progress from input length and updates the bar\n", - "- `createOptionButton(text, val)` – Creates a modal button to select string length\n", - "- `escHandler(ev)` – Handles Escape key to close the options menu\n", - "\n", - "<hr>" - ] - }, - { - "cell_type": "markdown", - "id": "5378ef96", - "metadata": {}, - "source": [ - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #8a2be2, /* Purple glow */\n", - " 0 0 20px #8a2be2, /* Deeper purple glow */\n", - " 0 0 30px #4169e1, /* Blue glow */\n", - " 0 0 40px #4169e1; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - "}\n", - "</style>\n", - "\n", - "<h2 class=\"glowing-text\">Scope</h2>\n", - "\n", - "Scope is a common pitfall for those learning functions. Press the button below to run the following code snippet." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "27aaaee2", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "<button id=\"runButton\">Click me!</button>\n", - "\n", - "<p id=\"scope_demo1\"></p>\n", - "<p id=\"scope_demo2\"></p>\n", - "\n", - "\n", - "<script>\n", - "\n", - "function onClick() {\n", - "\n", - " // myFunction() taken from W3Schools\n", - " function myFunction() {\n", - " let carName = \"Volvo\";\n", - " let text = \"Inside (\" + typeof carName + \") - \" + carName; \n", - " document.getElementById(\"scope_demo2\").innerHTML = text;\n", - " }\n", - "\n", - " myFunction();\n", - " let text = \"Outside - \" + typeof carName;\n", - " document.getElementById(\"scope_demo1\").innerHTML = text;\n", - "\n", - "}\n", - "\n", - "document.getElementById(\"runButton\").addEventListener(\"click\", onClick);\n", - "</script>\n" - ], - "text/plain": [ - "<IPython.core.display.HTML object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%html\n", - "\n", - "<button id=\"runButton\">Click me!</button>\n", - "\n", - "<p id=\"scope_demo1\"></p>\n", - "<p id=\"scope_demo2\"></p>\n", - "\n", - "\n", - "<script>\n", - "\n", - "function onClick() {\n", - "\n", - " // myFunction() taken from W3Schools\n", - " function myFunction() {\n", - " let carName = \"Volvo\";\n", - " let text = \"Inside (\" + typeof carName + \") - \" + carName; \n", - " document.getElementById(\"scope_demo2\").innerHTML = text;\n", - " }\n", - "\n", - " myFunction();\n", - " let text = \"Outside - \" + typeof carName;\n", - " document.getElementById(\"scope_demo1\").innerHTML = text;\n", - "\n", - "}\n", - "\n", - "document.getElementById(\"runButton\").addEventListener(\"click\", onClick);\n", - "</script>\n" - ] - }, - { - "cell_type": "markdown", - "id": "67014b50", - "metadata": {}, - "source": [ - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #8a2be2, /* Purple glow */\n", - " 0 0 20px #8a2be2, /* Deeper purple glow */\n", - " 0 0 30px #4169e1, /* Blue glow */\n", - " 0 0 40px #4169e1; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - "}\n", - "</style>\n", - "\n", - "<h3 class=\"glowing-text\">This is because of <i>SCOPE</i>!</h3>\n", - "\n", - "Essentially, we have things called\n", - "- **Local** variables, and\n", - "- **Global** variables\n", - "\n", - "Variables defined within a JavaScript function become LOCAL TO THAT FUNCTION.\n", - "\n", - "If I define a variable called `x` inside of a function, it can only be accessed within that function. Even if we use `var`, it will remain stuck inside that function. You should avoid polluting the global scope, but if you absolutely have to (which you don't), you can write something similar to the below code:\n", - "\n", - "```\n", - "function makeGlobal() {\n", - " let localVar = \"I am local\";\n", - " window.globalVar = localVar; // now accessible globally\n", - "}\n", - "\n", - "makeGlobal();\n", - "console.log(globalVar); // Outputs \"I am local\"\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "e9a078cc", - "metadata": {}, - "source": [ - "<hr>\n", - "\n", - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #8a2be2, /* Purple glow */\n", - " 0 0 20px #8a2be2, /* Deeper purple glow */\n", - " 0 0 30px #4169e1, /* Blue glow */\n", - " 0 0 40px #4169e1; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - "}\n", - "</style>\n", - "\n", - "<h2 class=\"glowing-text\">🍿 POPCORN HACK NO. 2 🍿</h2>\n", - "\n", - "Let's practice using functions!\n", - "\n", - "Head over to the homework notebook to do the popcorn hack.\n", - "\n", - "<hr>" - ] - }, - { - "cell_type": "markdown", - "id": "37b783d2", - "metadata": {}, - "source": [ - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #8a2be2, /* Purple glow */\n", - " 0 0 20px #8a2be2, /* Deeper purple glow */\n", - " 0 0 30px #4169e1, /* Blue glow */\n", - " 0 0 40px #4169e1; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - "}\n", - "</style>\n", - "\n", - "<h2 class=\"glowing-text\">Recursion</h2>\n", - "\n", - "We won't spend too much time on this, but we'll just do an overview of what recursion is.\n", - "\n", - "Recursion is where a function continuously calls itself. View the example below for a factorial recursion function:\n", - "\n", - "```js\n", - "function factorial(n) {\n", - " // If n is 0 or 1, the factorial is 1.\n", - " // This condition prevents infinite recursion.\n", - " if (n === 0 || n === 1) {\n", - " return 1;\n", - " } \n", - " // Recursive case: the function calls itself with a smaller value of n.\n", - " else {\n", - " return n * factorial(n - 1);\n", - " }\n", - "}\n", - "```\n", - "\n", - "If we run factorial(5), it will do:\n", - "- factorial(5) = 5 * factorial(4), which calls:\n", - "- factorial(4) = 4 * factorial(3)\n", - "- factorial(3) = 3 * factorial(2)\n", - "- factorial(2) = 2 * factorial (1)\n", - "- factorial(1) = 1\n", - "\n", - "### Demo" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6719f03f", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "<html>\n", - "<body>\n", - "\n", - "<p>Factorial Rescursion Demo</p>\n", - "\n", - "<input type=\"number\" id=\"fInput\" placeholder=\"Enter input (less than 100 please!)\">\n", - "<button id=\"calcFactorial\">Calculate</button>\n", - "\n", - "<div id=\"fDemo\">Your results will appear here.</div>\n", - "\n", - "<script>\n", - " (() => {\n", - " function factorial(n) {\n", - " // If n is 0 or 1, the factorial is 1.\n", - " // This condition prevents infinite recursion.\n", - " if (n === 0 || n === 1) {\n", - " return 1;\n", - " }\n", - " // Recursive case: the function calls itself with a smaller value of n.\n", - " else {\n", - " return n * factorial(n - 1);\n", - " }\n", - " }\n", - "\n", - " const button = document.getElementById(\"calcFactorial\");\n", - " const input = document.getElementById(\"fInput\");\n", - " const output = document.getElementById(\"fDemo\");\n", - "\n", - " button.addEventListener(\"click\", () => {\n", - " let val = Number(input.value);\n", - " if (val > 100){\n", - " output.innerText += \"\\n\" + \"Please enter a value less than or equal to 100. (\" + val + \")\";\n", - " console.log(\"Please enter a value less than or equal to 100. (\" + val + \")\");\n", - " } else {\n", - " let result = BigInt(factorial(val));\n", - " output.innerText += \"\\n\" + val + \"! = \" + result; \n", - " console.log(val + \"! = \" + result);\n", - " }\n", - " });\n", - " })();\n", - "\n", - "</script>\n", - "</body>\n", - "</html>\n" - ], - "text/plain": [ - "<IPython.core.display.HTML object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%html\n", - "\n", - "<p>Factorial Recursion Demo</p>\n", - "\n", - "<input type=\"number\" id=\"fInput\" placeholder=\"Enter input (less than 100 please!)\">\n", - "<button id=\"calcFactorial\">Calculate</button>\n", - "\n", - "<div id=\"fDemo\">Your results will appear here.</div>\n", - "\n", - "<script>\n", - " (() => {\n", - " function factorial(n) {\n", - " // If n is 0 or 1, the factorial is 1.\n", - " // This condition prevents infinite recursion.\n", - " if (n === 0 || n === 1) {\n", - " return 1;\n", - " }\n", - " // Recursive case: the function calls itself with a smaller value of n.\n", - " else {\n", - " return n * factorial(n - 1);\n", - " }\n", - " }\n", - "\n", - " const button = document.getElementById(\"calcFactorial\");\n", - " const input = document.getElementById(\"fInput\");\n", - " const output = document.getElementById(\"fDemo\");\n", - "\n", - " button.addEventListener(\"click\", () => {\n", - " let val = Number(input.value);\n", - " if (val > 100){\n", - " output.innerText += \"\\n\" + \"Please enter a value less than or equal to 100. (\" + val + \")\";\n", - " console.log(\"Please enter a value less than or equal to 100. (\" + val + \")\");\n", - " } else {\n", - " let result = BigInt(factorial(val));\n", - " output.innerText += \"\\n\" + val + \"! = \" + result; \n", - " console.log(val + \"! = \" + result);\n", - " }\n", - " });\n", - " })();\n", - "\n", - "</script>" - ] - }, - { - "cell_type": "markdown", - "id": "43124b5e", - "metadata": {}, - "source": [ - "<hr>\n", - "\n", - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #8a2be2, /* Purple glow */\n", - " 0 0 20px #8a2be2, /* Deeper purple glow */\n", - " 0 0 30px #4169e1, /* Blue glow */\n", - " 0 0 40px #4169e1; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - "}\n", - "</style>\n", - "\n", - "<h2 class=\"glowing-text\">Arrow Functions (if time)</h2>\n", - "\n", - "Arrow functions are a more concise way to write functions. Use case scenario:\n" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "dda8cfc4", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "<h3>Result</h3>\n", - "<button id=\"arrowfuncs_button\">Click Me</button>\n", - "<div id=\"arrowfuncs_result\"></div>\n", - "\n", - "<script>\n", - " document.getElementById(\"arrowfuncs_button\").addEventListener(\"click\", () => {\n", - " document.getElementById(\"arrowfuncs_result\").innerText = \"Button clicked\";\n", - "})\n", - "</script>\n" - ], - "text/plain": [ - "<IPython.core.display.HTML object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%html\n", - "\n", - "<h3>Result</h3>\n", - "<button id=\"arrowfuncs_button\">Click Me</button>\n", - "<div id=\"arrowfuncs_result\"></div>\n", - "\n", - "<script>\n", - " document.getElementById(\"arrowfuncs_button\").addEventListener(\"click\", () => {\n", - " document.getElementById(\"arrowfuncs_result\").innerText = \"Button clicked\";\n", - "})\n", - "</script>" - ] - }, - { - "cell_type": "markdown", - "id": "b724234d", - "metadata": {}, - "source": [ - "\n", - "\n", - "<h2 class=\"glowing-text\">HOMEWORK 😈</h2>\n", - "\n", - "\n", - "The homework for functions is located at `2025-09-29-functions_tinkerers_js_hw.ipynb`.\n", - "Make sure to attempt all the challenges and turn in your notebook URL to the link on that page." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.6" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2025-10-02-conditionals_constellators_lesson.ipynb b/_notebooks/CSSE/JavaScriptLessons/2025-10-02-conditionals_constellators_lesson.ipynb deleted file mode 100644 index 9b5a9226a6..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2025-10-02-conditionals_constellators_lesson.ipynb +++ /dev/null @@ -1,223 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "b12bfe54", - "metadata": { - "vscode": { - "languageId": "yaml" - } - }, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Conditions]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Conditions\n", - "lesson_part: reference\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "title: Conditions\n", - "description: This is the JavaScript Conditionals Lesson, taught by the Constellators.\n", - "permalink: /csse/javascript/constellators/conditionals-lesson\n", - "author: Constellators - Adya S, Niharika B, Salma Z, Anika S, Sophie H\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "8da63b4f", - "metadata": {}, - "source": [ - "<style>\n", - ".glowing-text {\n", - " color: #fff; /* Set the text color to white or a light color for better contrast */\n", - " text-shadow: 0 0 10px #581696ff, /* Purple glow */\n", - " 0 0 20px #4a147cff, /* Deeper purple glow */\n", - " 0 0 30px #2248baff, /* Blue glow */\n", - " 0 0 40px #092780ff; /* Deeper blue glow */\n", - "\n", - " font-weight: bold;\n", - " margin-top: 0;\n", - "}\n", - "</style>\n", - "\n", - "Presented by the\n", - "<h4 class=\"glowing-text\">CONSTELLATORS</h4>\n", - "\n", - "<hr>\n", - "\n", - "## **Conditionals**\n", - "\n", - "In JavaScript, conditionals are essential aspects of programming that are used to control the flow of code based on whether certain conditions are met. They're necessary to make decisions within game code and run different actions based on different conditions.\n", - "\n", - "TO FIND THIS LESSON (pages repository): Search -> \"Constellators - Conditionals Lesson\" -> Select the most recent one (should be 10/02/25)\n", - "\n", - "### <u>What are Conditionals?</u>\n", - "- Allows the execution of different blocks of code based on whether a specified condition evaluates to true or false\n", - "- This enables programs to make decisions and respond dynamically to various situations\n", - "- Analogy: depending on the weather, you either bring outside an umbrella (rain) or a hat (sunny)\n", - "- Types: if, if-else, else if, (+switch)\n", - "\n", - "<br>\n", - "\n", - "### <u>Types of Conditionals</u>\n", - "\n", - "#### 1. If\n", - "\n", - "- Executes code if a given condition is true\n", - "\n", - "Example:\n", - "```js\n", - "if (condition) {\n", - " // Code to execute if condition is true\n", - "}\n", - "```\n", - "\n", - "#### 2. If ... Else\n", - "\n", - "- Basically a true/false --> executes one thing if the condition is true, and a different thing if the condition is false\n", - "\n", - "Else statement:\n", - "- Executes a block of code only if the preceding if (or else if) condition evaluates to false.\n", - "- It must always follow an if or else if statement.\n", - "- No condition\n", - "\n", - "Example:\n", - "```js\n", - "if (condition) {\n", - " // Code to execute if condition is true\n", - "} else {\n", - " // Code to execute if condition is false\n", - "}\n", - "```\n", - "\n", - "#### 3. Else ... If\n", - "\n", - "- JavaScript's equivalent of elif\n", - "- Executes a block of code if the preceding if condition (or any preceding else if conditions) evaluates to false, AND its own specified condition evaluates to true.\n", - "- Only the first true condition's block is executed\n", - "- Must always follow an if or another else if statement\n", - "\n", - "Example:\n", - "```js\n", - "if (condition1) {\n", - " // Code to execute if condition1 is true\n", - " } else if (condition2) {\n", - " // Code to execute if condition2 is true\n", - " } else {\n", - " // Code to execute if none of the above conditions are true\n", - " }\n", - "```\n", - "\n", - "#### 4. Switch\n", - "\n", - "- Compares multiple possible outcomes\n", - "- More complex than just true/false\n", - "\n", - "Example:\n", - "```js\n", - "switch (expression) {\n", - " case value1:\n", - " // Code to execute if expression matches value1\n", - " break;\n", - " case value2:\n", - " // Code to execute if expression matches value2\n", - " break;\n", - " default:\n", - " // Code to execute if no match is found\n", - " }\n", - "```\n", - "\n", - "#### 5. Nested If (Nested Conditionals)\n", - "\n", - "- An if statement within another conditional.\n", - "- Analogy: if-else statement to determine whether it's raining. If it's raining, check if you have an umbrella.\n", - "\n", - "Example:\n", - "```js\n", - "if (condition1) {\n", - " if (extracondition1) {\n", - " // Code to execute if both condition 1 and extra condition are true\n", - " }\n", - " else {\n", - " // Code to execute if condition 1 is true, but extra condition is false\n", - " }\n", - "} else {\n", - " // Code to execute if condition 1 is false\n", - "}\n", - "```\n", - "\n", - "<br>\n", - "\n", - "**Summary**\n", - "\n", - "“if” checks a condition\n", - "<br>“else if\" checks another condition if the previous ones were false\n", - "<br>“else” runs if none of the above conditions were true.\n", - "\n", - "### <u>Popcorn Hack 1</u>\n", - "\n", - "Go to the HW file that you can access [here](https://github.com/AdyaShipekar/code-constellations/blob/main/_notebooks/CSSE/JavaScriptLessons/Conditionals/2025-10-02-conditionals_constellators_js_hw.ipynb). Download to your student/portfolio repository and complete Popcorn Hack 1.\n", - "\n", - "### <u>Examples of Conditionals in OOP Breakout</u>\n", - "\n", - "To Recap: A **conditional** in code is any statement where the program checks a condition (using `if, else, or else if ` statements) to decide what to do next. Throughout the OOP BREAKOUT game, there are many examples of conditionals and conditional expressions that help the game run smoothly. \n", - "\n", - "In our OOP Breakout game, you can consider the conditionals the rules of the game world! They let the code make decisions.\n", - "\n", - "If the ball hits a wall → it bounces back.\n", - "If the ball hits a brick → the brick disappears.\n", - "If the ball hits the bottom → a life is lost.\n", - "Else (if none of those things happen) → the ball just keeps moving.\n", - "\n", - "**Inside the update() method for the ball:**\n", - "\n", - "```js\n", - "update(canvasWidth, canvasHeight) {\n", - "// Wall collision (left/right)\n", - "if (this.x + this.dx > canvasWidth - this.radius || this.x + this.dx < this.radius) {\n", - "this.dx = -this.dx;\n", - "}\n", - "// Top\n", - "if (this.y + this.dy < this.radius) {\n", - " this.dy = -this.dy;\n", - " }\n", - "this.x += this.dx;\n", - "this.y += this.dy;\n", - "}\n", - "```\n", - "\n", - "**Explanation:**\n", - "\n", - "First conditional: ```if (this.x + this.dx > canvasWidth - this.radius || this.x + this.dx < this.radius)```\n", - "- Checks if the ball is about to hit the left or right wall!\n", - "- If true, the ball bounces back by flipping its horizontal direction (```this.dx = -this.dx```).\n", - "\n", - "Second conditional: ```if (this.y + this.dy < this.radius) ```\n", - "- Checks if the ball is about to hit the top wall!\n", - "- If true, it flips the vertical direction (```this.dy = -this.dy```).\n", - "\n", - "Without these if statements, the ball would fly off the screen forever. The conditionals keep the ball bouncing around, making the game actually playable!\n", - "\n", - "### <u>Popcorn Hack 2</u>\n", - "\n", - "Go to the HW file from before and complete Popcorn Hack 2.\n", - "\n", - "### <u>Homework</u>\n", - "\n", - "Complete the homework and submit to [this form](https://docs.google.com/forms/d/e/1FAIpQLSccjujB0DqCnCy5mOE2r4Py8cYuvzmyBk9X-gWSn8XUNQvlDw/viewform?usp=header). \n" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-01-07-arrays.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-01-07-arrays.ipynb deleted file mode 100644 index e720affdda..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-01-07-arrays.ipynb +++ /dev/null @@ -1,399 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "b3d88644", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Arrays]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Arrays\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "title: Arrays\n", - "description: Learn about arrays in JavaScript, including how to create, access, and manipulate them.\n", - "permalink: /js/arrays\n", - "author: Sadaf, Sujay, Arjun, Joshika\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "b2963c88", - "metadata": {}, - "source": [ - "## What are Arrays?\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "070814e2", - "metadata": {}, - "source": [ - "An **array** is a collection of elements (values) stored in a single variable. Each element in an array can be accessed by its **index** (position), starting from 0.\n", - "\n", - "Think of an array like a row of boxes, each containing a value:\n", - "- Box 0 contains the first element\n", - "- Box 1 contains the second element \n", - "- Box 2 contains the third element\n", - "- And so on...\n", - "\n", - "### Why Use Arrays?\n", - "- Store multiple values in one variable\n", - "- Easy to access values by position\n", - "- Useful for loops (process many items at once)\n", - "- Organize related data together" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2bc62850", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Add or remove a new value in the array and see what happens!\n", - "\n", - "let fruits = [\"apple\", \"banana\", \"orange\", \"grape\"];\n", - "\n", - "console.log(\"My array of fruits:\");\n", - "console.log(fruits);\n", - "console.log();\n", - "\n", - "console.log(\"First fruit (index 0):\", fruits[0]);\n", - "console.log(\"Third fruit (index 2):\", fruits[2]);\n", - "console.log();\n", - "\n", - "\n", - "console.log(\"Number of fruits:\", fruits.length);" - ] - }, - { - "cell_type": "markdown", - "id": "8c158a6a", - "metadata": {}, - "source": [ - "## Modifying Arrays\n", - "\n", - "You can change, add, or remove elements from an array:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1c5ade19", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Practice modifying arrays by changing, adding, and removing elements!\n", - "\n", - "// Start with an array\n", - "let colors = [\"red\", \"blue\", \"green\"];\n", - "console.log(colors);\n", - "console.log();\n", - "\n", - "// Change an element\n", - "colors[1] = \"yellow\";\n", - "console.log(colors);\n", - "console.log();\n", - "\n", - "// Add an element\n", - "colors.push(\"purple\");\n", - "console.log(colors);\n", - "console.log();\n", - "\n", - "// Remove an element\n", - "colors.splice(colors.indexOf(\"red\"), 1);\n", - "console.log(colors);" - ] - }, - { - "cell_type": "markdown", - "id": "ea514f14", - "metadata": {}, - "source": [ - "## Looping Through Arrays\n", - "\n", - "Arrays are powerful when combined with loops. You can process each element without writing it by hand:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f5f1723c", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Modify the numbers array to see different outputs\n", - "\n", - "// Using a for loop to go through each element\n", - "let numbers = [10, 20, 30, 40, 50];\n", - "\n", - "console.log(\"Numbers in the array:\");\n", - "for (let num of numbers) {\n", - " console.log(num);\n", - "}\n", - "\n", - "console.log();\n", - "console.log(\"Double each number:\");\n", - "for (let num of numbers) {\n", - " console.log(num * 2);\n", - "}\n", - "\n", - "console.log();\n", - "console.log(\"Using index to access elements:\");\n", - "for (let i = 0; i < numbers.length; i++) {\n", - " // conversion fails with template literals\n", - " console.log(`Index ${i}: ${numbers[i]}`);\n", - " // conversion works with concat\n", - " console.log(\"Index \" + i + \": \" + numbers[i] );\n", - "\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "9c60b1f5", - "metadata": {}, - "source": [ - "## Real-World Example: Student Grades\n", - "\n", - "Let's calculate the average grade of students:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d2abe784", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Change the student grades to yours in the array to see different results\n", - "\n", - "// Array of student grades\n", - "let grades = [85, 92, 78, 95, 88, 91];\n", - "\n", - "// Calculate the sum\n", - "let total = 0;\n", - "for (let grade of grades) {\n", - " total = total + grade;\n", - "}\n", - "\n", - "// Calculate the average\n", - "let average = total / grades.length;\n", - "\n", - "console.log(`Student grades: ${grades}`);\n", - "console.log(`Total points: ${total}`);\n", - "console.log(`Number of students: ${grades.length}`);\n", - "console.log(`Average grade: ${average.toFixed(1)}`);\n", - "console.log();\n", - "\n", - "// Find the highest and lowest grades\n", - "console.log(`Highest grade: ${Math.max(...grades)}`);\n", - "console.log(`Lowest grade: ${Math.min(...grades)}`);" - ] - }, - { - "cell_type": "markdown", - "id": "f8947964", - "metadata": {}, - "source": [ - "## Key Takeaways\n", - "\n", - "✅ **Arrays** store multiple values in a single variable \n", - "✅ **Index** starts at 0 for the first element \n", - "✅ Access elements using `array[index]` \n", - "✅ Use **loops** to process all elements \n", - "✅ Common operations: append, remove, change, loop, sum, average \n", - "\n", - "Arrays are one of the most important data structures in programming. Master them and you'll be able to solve many problems efficiently!" - ] - }, - { - "cell_type": "markdown", - "id": "c8c9d822", - "metadata": {}, - "source": [ - "# Arrays Homework 🎯\n", - "\n", - "Welcome to the Arrays homework! These exercises will help you practice the key array concepts from the lesson: accessing elements, modifying arrays, looping through arrays, and performing calculations.\n", - "\n", - "Complete all exercises below. Good luck! 💪" - ] - }, - { - "cell_type": "markdown", - "id": "91164904", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## Exercise 1: Array Basics - Access Elements\n", - "\n", - "Create an array with 5 different items (could be favorite movies, books, games, etc.). Then:\n", - "1. Print the entire array\n", - "2. Access and print the first element (index 0)\n", - "3. Access and print the last element\n", - "4. Print the total number of items in the array" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "977ff445", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Exercise 1 - Array Basics\n", - "\n", - "// TODO: Write your code here for Exercise 1\n", - "// Create an array with 5 items\n", - "// Print the array\n", - "// Print the first element\n", - "// Print the last element\n", - "// Print the length\n" - ] - }, - { - "cell_type": "markdown", - "id": "53795213", - "metadata": {}, - "source": [ - "## Exercise 2: Modify Arrays\n", - "\n", - "Start with this shopping list: `[\"milk\", \"eggs\", \"bread\", \"cheese\"]`\n", - "Then perform these operations:\n", - "1. Print the original array\n", - "2. Change the second item to \"butter\"\n", - "3. Add \"yogurt\" to the end using push()\n", - "4. Remove \"bread\" from the array\n", - "5. Print the final array" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "170b2aa6", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Exercise 2 - Arrays Manipulation\n", - "\n", - "// TODO: Write your code here for Exercise 2\n", - "// Start with the shopping list\n", - "// Modify it as described above" - ] - }, - { - "cell_type": "markdown", - "id": "56ad19bb", - "metadata": {}, - "source": [ - "## Exercise 3: Loop Through an Array\n", - "\n", - "Create an array with 5 numbers: `[10, 25, 30, 15, 20]`\n", - "\n", - "Write a loop that:\n", - "1. Prints each number with a message (e.g., \"Number: 10\")\n", - "2. Prints each number multiplied by 2\n", - "3. Calculates and prints the sum of all numbers" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "05a179a4", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Exercise 3 - Arrays Manipulation\n", - "\n", - "// TODO: Write your code here for Exercise 3\n", - "// Create the numbers array\n", - "// Loop through and print each number\n", - "// Print each number multiplied by 2\n", - "// Calculate and print the sum\n" - ] - }, - { - "cell_type": "markdown", - "id": "5e01175a", - "metadata": {}, - "source": [ - "Google form link is here: https://forms.gle/X47CB92yKuLVRHq98 " - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.3" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-01-09-data_abstraction.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-01-09-data_abstraction.ipynb deleted file mode 100644 index f728d8dd0c..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-01-09-data_abstraction.ipynb +++ /dev/null @@ -1,408 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "84243aa1", - "metadata": { - "vscode": { - "languageId": "yaml" - } - }, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Data-Abstraction]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Data-Abstraction\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "title: Data Abstraction!\n", - "codemirror: true\n", - "microblog: true\n", - "permalink: /js/data-abstraction\n", - "description: How Data Abstraction is used in Programming\n", - "author: Rashi Gaurav, Rigved Reddy Gaddam, and Jasan Boparai\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "69ff395a", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "## What is Data Abstraction??\n", - "<font color=\"blue\"> IMAGINE </font> \n", - "Simply driving a steering wheel without understanding how the parts inside work. This is exactly what Data Abstraction is. \n", - "\n", - "Data Abstraction simplifies complex systems by showing <font color= \"red\"> only </font> the essential features and hiding complex details, so users can easily understand and interact with systems or apps! \n", - "\n", - "<font color=\"green\"> It focuses on *what* something does rather than *how* it does it. </font>\n", - "\n", - "### Example #1: Rounding numbers\n", - "One example is <font color=\"red\"> built-in functions </font> in JavaScript, because they allow you to use one simple, clear command to run a type of function, but don't show *how* the built-in function was coded." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7496eabd", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "// --- Abstraction in Action: Math.round() ---\n\n// 1. The Complex Data (Input)\nconst messyNumber = 7.84236;\n\n\n// We call the built-in function. We don't care *how* it calculates the rounding,\n// only that it *does* the rounding.\nconst roundedResult = Math.round(messyNumber);\n\n// 3. The Simple Result (Output)\nconsole.log(`The original messy number was: ${messyNumber}`);\nconsole.log(`The simplified, rounded result is: ${roundedResult}`);\n// Expected output: 8\n\n/*\nWhat's hidden (The Implementation):\nThe specific machine code and internal logic the JavaScript engine uses \nto look at the decimal part (.84236), determine it's >= 0.5, and then \nincrement the integer part (7 -> 8). All of that is abstracted away.\n*/\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "// CODE_RUNNER: Try out Data Abstraction with Math.round()\n", - "\n", - "// Abstraction in Action: Math.round()\n", - "\n", - "// The Complex Data (Input)\n", - "const messyNumber = 7.84236;\n", - "\n", - "\n", - "// We call the built-in function. \n", - "// We don't care *how* it calculates the rounding\n", - "\n", - "// only that it *does* the rounding\n", - "const roundedResult = Math.round(messyNumber);\n", - "\n", - "// The Simple Result (Output)\n", - "console.log(`The original messy number was: ${messyNumber}`);\n", - "console.log(`The simplified, rounded result is: ${roundedResult}`);\n", - "// Expected output: 8\n" - ] - }, - { - "cell_type": "markdown", - "id": "8b3d33c4", - "metadata": {}, - "source": [ - "#### What's hidden:\n", - "The internal logic the JavaScript uses to look at the decimal part (.84236), determine it's >= 0.5, and then round the integer part (7 -> 8). All of this is abstracted away!" - ] - }, - { - "cell_type": "markdown", - "id": "5467f0bd", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "### Example #2: Adding two numbers\n", - "The user should be able to call addNumbers(a, b) and trust it works <font color=\"yellow\"> without </font> needing to see the math inside.\n", - "\n", - "<font color=\"red\"> YOUR JOB: </font>\n", - "The code below is \"broken\". Complete the function so that it successfully returns the sum of the two inputs. \n", - "\n", - "<font color=\"yellow\"> hint: </font> use the *return* keyword inside the function" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d747e5ac", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "// CODE_RUNNER: Display two numbers, and add them!\n// 1. The Abstraction (The Function)\n// --- The Abstraction ---\nfunction addNumbers(num1, num2) {\n return num1 + num2; \n}\n\n// --- The Data Abstraction and function Logic ---\n\n// Get the values from the input boxes (Input Variables)\nlet a = 2\nlet b = 3\n\n// Use the abstraction to get the result\n// (We use Number() to make sure JS treats them as math, not text)\nlet result = addNumbers(a, b);\n\n// Display the result (Output)\nconsole.log(result);\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "// CODE_RUNNER: Display two numbers, and add them!\n", - "\n", - "// The Abstraction (The Function)\n", - "function addNumbers(num1, num2) {\n", - " // Add code here\n", - "}\n", - "\n", - "let a = 2\n", - "let b = 3\n", - "\n", - "// Use the abstraction to get the result\n", - "let result = addNumbers(a, b);\n", - "\n", - "console.log(result);" - ] - }, - { - "cell_type": "markdown", - "id": "812bb9ce", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "## Data Abstraction with Classes\n", - "Secondly, Data Abstraction can be seen in Object Oriented Programming, specifically with <font color=\"red\"> Classes and Objects </font>. Classes are essential tools for <font color=\"red\"> simplifying how we handle data. </font>\n", - "\n", - "### Example #3: Checking Account Balance" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3bd9aaf4", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "// CODE_RUNNER: Use the abstraction to deposit $200\n", - "class BankAccount {\n", - " constructor() {\n", - " this.balance = 500;\n", - " }\n", - "\n", - " deposit(amount) {\n", - " this.balance = this.balance + amount;\n", - " console.log(\"💰 Deposited: $\" + amount);\n", - " }\n", - "}\n", - "\n", - "const myAccount = new BankAccount();\n", - "\n", - "// Write code here\n", - "// Hint: myAccount.______();\n", - "\n", - "// 3. Check the result\n", - "console.log(\"Final Balance: $\" + myAccount.balance);" - ] - }, - { - "cell_type": "markdown", - "id": "df5b8860", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "## Inheritance\n", - "In programming, Inheritance allows one class (called a subclass / child class) to <font color=\"red\">\"borrow\" </font> features (properties and methods) from another class (the adult). \n", - "\n", - "<font color=\"yellow\">Real World Example: Smartphone </font>\n", - "\n", - "The Parent Class: A basic phone that can make calls \n", - "\n", - "The Child Class: An iPhone that <b> inherits </b> the ability to make phone calls, but adds its own features" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e50d394f", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "// CODE_RUNNER: Use the inherited methods to make a call and take a photo\n", - "class Phone {\n", - " makeCall() {\n", - " console.log(\"Making a phone call\");\n", - " }\n", - "}\n", - "\n", - "// Child class\n", - "class SmartPhone extends Phone {\n", - " takePhoto() {\n", - " console.log(\"Taking a photo\");\n", - " }\n", - "}\n", - "\n", - "const myNewPhone = new SmartPhone();\n", - "\n", - "// Hint: const_name.method();" - ] - }, - { - "cell_type": "markdown", - "id": "09233129", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "## HOMEWORK\n", - "\n", - "1. This is a code of a calculator. Please read through the code first to try and understand what it does. There are many unnecessary lines within the code. Please identify the unnecessary lines and delete them." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "bb367397", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "// CODE_RUNNER: Homework for data abstraction\nfunction calculator(num1, num2, operator) {\n let nothing = 0;\n let randomText = \"calculator running\";\n let temp = null;\n\n nothing = nothing + 0;\n nothing = nothing * 1;\n\n let result;\n\n if (randomText === \"calculator running\") {\n temp = \"still running\";\n }\n\n if (operator === \"+\") {\n result = num1 + num2;\n } else if (operator === \"-\") {\n result = num1 - num2;\n } else if (operator === \"*\") {\n result = num1 * num2;\n } else if (operator === \"/\") {\n result = num1 / num2;\n } else {\n result = \"Invalid operator\";\n }\n\n for (let i = 0; i < 3; i++) {\n nothing += 0;\n }\n\n result = result;\n\n return result;\n}\n\nconsole.log(calculator(10, 5, \"+\"));\nconsole.log(calculator(10, 5, \"-\"));\nconsole.log(calculator(10, 5, \"*\"));\nconsole.log(calculator(10, 5, \"/\"));\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "// CODE_RUNNER: Homework for data abstraction\n", - "function calculator(num1, num2, operator) {\n", - " let nothing = 0;\n", - " let randomText = \"calculator running\";\n", - " let temp = null;\n", - "\n", - " nothing = nothing + 0;\n", - " nothing = nothing * 1;\n", - "\n", - " let result;\n", - "\n", - " if (randomText === \"calculator running\") {\n", - " temp = \"still running\";\n", - " }\n", - "\n", - " if (operator === \"+\") {\n", - " result = num1 + num2;\n", - " } else if (operator === \"-\") {\n", - " result = num1 - num2;\n", - " } else if (operator === \"*\") {\n", - " result = num1 * num2;\n", - " } else if (operator === \"/\") {\n", - " result = num1 / num2;\n", - " } else {\n", - " result = \"Invalid operator\";\n", - " }\n", - "\n", - " for (let i = 0; i < 3; i++) {\n", - " nothing += 0;\n", - " }\n", - "\n", - " result = result;\n", - "\n", - " return result;\n", - "}\n", - "\n", - "console.log(calculator(10, 5, \"+\"));\n", - "console.log(calculator(10, 5, \"-\"));\n", - "console.log(calculator(10, 5, \"*\"));\n", - "console.log(calculator(10, 5, \"/\"));" - ] - }, - { - "cell_type": "markdown", - "id": "064405a9", - "metadata": {}, - "source": [ - "2. Below a pet class is given.\n", - "Your Job is to add a new subclass,<font color=\"red\"> Dog</font>, that <font color=\"red\">inherits</font> from the Pet Class " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b94a25cb", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Add a Pet Class\nclass Pet {\n eat() {\n console.log(\"Nom nom nom\");\n }\n}\n\n// Create the Dog class that extends Pet\n\n// We would also like you to create a method like eat() but called bark() that prints \"Woof woof!\"\n\n// Refer back to the syntax of the classes examples such as phone and smartphone if you need help!\n\n// Write your code here\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js \n", - "\n", - "// CODE_RUNNER: Add a Dog subclass\n", - "class Pet {\n", - " eat() {\n", - " console.log(\"Nom nom nom\");\n", - " }\n", - "}\n", - "\n", - "// Create the Dog class that extends Pet\n", - "\n", - "// We would also like you to create a method like eat() but called bark() that prints \"Woof woof!\"\n", - "\n", - "// Refer back to the syntax of the classes examples such as phone and smartphone if you need help!\n", - "\n", - "// Write your code here\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.3" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-01-13-iterations_lesson.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-01-13-iterations_lesson.ipynb deleted file mode 100644 index d013585175..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-01-13-iterations_lesson.ipynb +++ /dev/null @@ -1,407 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "40b6c513", - "metadata": { - "vscode": { - "languageId": "yaml" - } - }, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Iteration]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Iteration\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "microblog: true\n", - "codemirror: true\n", - "title: Iterations\n", - "description: An intro to iterations using Code Runner\n", - "permalink: /js/iterations\n", - "author: Rishab Shyamal, Flora Segale, Chetan Tiduwar\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "061dba9e", - "metadata": {}, - "source": [ - "## Intro to iterations\n", - "- The basic gist of iterations are to repeat multiple actions for a desirable result\n", - "- Used to repeat code more efficiently compared to just writing out all the functions line by line" - ] - }, - { - "cell_type": "markdown", - "id": "7bbccf7d", - "metadata": {}, - "source": [ - "\n", - "The syntax of a for loop consists of three main parts:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a6f7e2fa", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "for (initialization; condition; increment) {\n", - " // Code to execute\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "9e727123", - "metadata": {}, - "source": [ - "Initialization: This sets up a counter variable and runs once at the beginning of the loop.\n", - "\n", - "Condition: Before each iteration, the loop checks this condition. If it's true, the loop continues; if false, the loop ends.\n", - "\n", - "Increment: This updates the counter variable after each iteration." - ] - }, - { - "cell_type": "markdown", - "id": "ef3bbe16", - "metadata": {}, - "source": [ - "### For Loop with Syntax Error" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "56430c17", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "for (let i = 1; i <= 5; i++) {\n console.log(i);\n}\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js \n", - "\n", - "// CODE_RUNNER: Run loop, the fix the Syntax Error\n", - "\n", - "for (let i = 1, i <= 5; i++) {\n", - " console.log(i);\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "6363e99f", - "metadata": {}, - "source": [ - "### Usage: Looping Through Arrays\n", - "You can use a for loop to iterate over elements in an array." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f1ee5a50", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Run fruits\n\nlet fruits = [\"Heart Shaped Herb\", \"Yami Yami no Mi\", \"Gomu Gomu no Mi\"];\n\nfor (let i = 0; i < fruits.length; i++) {\n console.log(fruits[i]);\n}\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js \n", - "\n", - "// CODE_RUNNER: Run loop, then add another fruit to the array and print all fruits \n", - "\n", - "let fruits = [\"Heart Shaped Herb\", \"Yami Yami no Mi\", \"Gomu Gomu no Mi\"];\n", - "\n", - "for (let i = 0; i < fruits.length; i++) {\n", - " console.log(fruits[i]);\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "3f83f811", - "metadata": {}, - "source": [ - "Add two of your own fruits and try it out!" - ] - }, - { - "cell_type": "markdown", - "id": "b8a85570", - "metadata": {}, - "source": [ - "### Objects\n", - "\n", - "for loops can also be used to iterate **objects** over each **key** and its **value**" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "cd9972d8", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Run loop, then change to your Personal Info\n\nconst personInfo = { // Define an object\n name: \"Rishab\",\n age: 15,\n city: \"San Diego\",\n occupation: \"High School Student\"\n};\n\nfor (let key in personInfo) { // Notice we are using for... in... instead of for... of...\n console.log(key + \": \" + personInfo[key]);\n}\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js \n", - "\n", - "// CODE_RUNNER: Run loop, then change to your Personal Info\n", - "\n", - "const personInfo = { // Define an object\n", - " name: \"Rishab\",\n", - " age: 15,\n", - " city: \"San Diego\",\n", - " occupation: \"High School Student\"\n", - "};\n", - "\n", - "for (let key in personInfo) { // Notice we are using for... in... instead of for... of...\n", - " console.log(key + \": \" + personInfo[key]);\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "490a0aad", - "metadata": {}, - "source": [ - "# 🌿 **Understanding `while` Loops**\n", - "\n", - "A **`while` loop** repeats a block of code **as long as a condition is true**. \n", - "It’s useful when you don’t know exactly how many times something should run — you just know the rule for when it should stop.\n", - "\n", - "A `while` loop always includes:\n", - "\n", - "- **A starting value** \n", - "- **A condition** checked before each loop \n", - "- **A change** inside the loop that eventually makes the condition false \n", - "\n", - "If the condition never becomes false, the loop runs forever — an **infinite loop**.\n", - "\n", - "# 🌱 **Simple Example**" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "24e7e56e", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Run loop, then change the starting value, condition, and increment\nlet counter = 0;\n\nwhile (counter < 5) {\n console.log(\"The counter is:\", counter);\n counter += 1;\n}\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Run loop, then change the starting value, condition, and increment\n", - "let counter = 0;\n", - "\n", - "while (counter < 5) {\n", - " console.log(\"The counter is:\", counter);\n", - " counter += 1;\n", - "}" - ] - }, - { - "cell_type": "markdown", - "id": "83044a84", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "Try experimenting with:\n", - "\n", - "- Changing the starting value \n", - "- Changing the condition \n", - "- Changing the increment (e.g., `counter += 2`) \n", - "- Making it count down instead of up " - ] - }, - { - "cell_type": "markdown", - "id": "0c0d7817", - "metadata": {}, - "source": [ - "# 🌼 **Playful Example: Growing Vine**\n", - "\n", - "This version is visual, fun, and great for experimenting with iteration.\n", - "\n", - "Try experimenting with:\n", - "\n", - "- Changing the maximum length \n", - "- Make the vine shrink instead of grow \n", - "- Replace the emoji with another symbol \n", - "- Increase the growth rate (e.g., `length += 2`) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "eb7c3a2c", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "// Growing vine using a while loop\n\nlet length = 1;\n\nwhile (length <= 10) {\n console.log(\"🌿\".repeat(length));\n length += 1;\n}\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js \n", - "// Growing vine using a while loop\n", - "\n", - "// CODE_RUNNER: Run loop to see growing vine\n", - "\n", - "let length = 1;\n", - "\n", - "while (length <= 10) {\n", - " console.log(\"🌿\".repeat(length));\n", - " length += 1;\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "d0f0b22d", - "metadata": {}, - "source": [ - "## Challenge Iteration\n", - "Write an iteration to calculate the sum of all numbers from 1 to n \n", - "Test it with an input of 5" - ] - }, - { - "cell_type": "markdown", - "id": "f59c71ed", - "metadata": {}, - "source": [ - "Hint: use 'n' to define your condition, and replace 'n' with the number that you want to be the upper limit you are adding to your sum." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2eb0f563", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\nconst personInfo = { // Define an object\n name: \"Rishab\",\n age: 15,\n city: \"San Diego\",\n occupation: \"High School Student\"\n};\n\nfor (let key in personInfo) { // Notice we are using for... in... instead of for... of...\n console.log(key + \": \" + personInfo[key]);\n}\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js \n", - "\n", - "// CODE_RUNNER: Complete function to Sum Numbers from 1 to n, and call the function with a parameter of your choice\n", - "\n", - "function sumNumbers(n) {\n", - " let sum = 0;" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.3" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-01-16-json_lesson.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-01-16-json_lesson.ipynb deleted file mode 100644 index 3438a228ef..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-01-16-json_lesson.ipynb +++ /dev/null @@ -1,407 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "6a72c690", - "metadata": { - "vscode": { - "languageId": "yaml" - } - }, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, JSON]\n", - "lesson_language: JavaScript\n", - "lesson_topic: JSON\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "title: JSON and JavaScript Objects\n", - "description: JSON Structures using Code Runner\n", - "permalink: /js/json\n", - "author: Finn Dyess, Matteo\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "045b5b04", - "metadata": {}, - "source": [ - "# JSON and JavaScript Objects" - ] - }, - { - "cell_type": "markdown", - "id": "4395c2ab", - "metadata": {}, - "source": [ - "## All About JSON and JavaScript Objects\n", - "\n", - "Let's imagine this. You're in your room, with tons of stuff laid out however you want: clothes on the bed, books stacked on a shelf, maybe a backpack open with notebooks inside. You can walk around, grab things, move them, and even use them right away.\n", - "\n", - "This is what a **JavaScript** object is like. It lives inside your program, and JavaScript can interact with it directly. \n", - "\n", - "Now imagine that you need to ship your stuff to someone else.\n", - "\n", - "You can't just send your entire room as-is. You have to:\n", - "- Put everything to boxes\n", - "- Label everything clearly\n", - "- Follow shipping rules so nothing breaks\n", - "\n", - "That is what JSON is like. JSON is how we *package data* so it can be sent, stored, or shared. It is not meant to be used directly, but instead to travel. \n", - "\n", - "In this lesson, we will go over:\n", - "- What JavaScript objects are\n", - "- What JSON is\n", - "- Why they appear similar but have different functions\n", - "- How to convert between the two" - ] - }, - { - "cell_type": "markdown", - "id": "b9200e95", - "metadata": {}, - "source": [ - "## Section 1: JavaScript Objects\n", - "A **JavaScript object** is a collection of related information stored in one variable. \n", - "\n", - "JavaScript objects:\n", - "- Live inside JavaScript code\n", - "- Can store different types of data\n", - "- Can include functions\n", - "- Are flexible\n", - "\n", - "Here's a basic example of a JavaScript object:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "96dcd705", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "const student = {\n", - " name: \"Alex\",\n", - " age: 16,\n", - " enrolled: true,\n", - " greet: function () {\n", - " return \"Hello!\";\n", - " }\n", - "};" - ] - }, - { - "cell_type": "markdown", - "id": "58917f27", - "metadata": {}, - "source": [ - "Notice a few things:\n", - "- The keys **do not** need quotes\n", - "- The object includes a function\n", - "- JavaScript understands this immediately\n", - "\n", - "This only works because JavaScript is running the code.\n", - "\n", - "## Code Runner 1\n", - "Here's what to do:\n", - "\n", - "Run the code below, then try changing it." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b0d046eb", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Personalize your student record.\n\nconst student = {\n name: \"Bartholomew\",\n age: 15,\n grade: \"9th\"\n};\n\n\nconsole.log(student.name);\nconsole.log(student.age);\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Personalize your student record JSON object\n", - "\n", - "const student = {\n", - " name: \"Bartholomew\",\n", - " age: 15,\n", - " grade: \"9th\"\n", - "};\n", - "\n", - "\n", - "console.log(student.name);\n", - "console.log(student.age);" - ] - }, - { - "cell_type": "markdown", - "id": "2bb947e9", - "metadata": {}, - "source": [ - "Try the following:\n", - "- Change the student's name to your own\n", - "- Log the entire object\n", - "\n", - "Now try this:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7f623b36", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "console.log(student.school);" - ] - }, - { - "cell_type": "markdown", - "id": "434bd2fb", - "metadata": {}, - "source": [ - "This will print `undefined`.\n", - "This isn't because of an error, but instead because `student.school` was never defined. \n", - "JavaScript objects are flexible. They do not break just because a property is undefined. " - ] - }, - { - "cell_type": "markdown", - "id": "b6f40405", - "metadata": {}, - "source": [ - "## Section 2: What is JSON?\n", - "\n", - "JSON stands for JavaScript Object Notation.\n", - "\n", - "Even though it has the word *JavaScript* in the name, JSON is **not JavaScript code.**\n", - "\n", - "JSON is:\n", - "- A text format\n", - "- Used to send and store data\n", - "\n", - "Because JSON is meant to be shared, it has **strict rules**.\n", - "\n", - "### JSON Rules\n", - "JSON:\n", - "- Required double quotes for all keys\n", - "- Does NOT allow functions\n", - "- Does NOT allow comments\n", - "- Does NOT allow trailing commas\n", - "\n", - "If any rule is broken, then JSON will fail.\n", - "\n", - "## Code Runner 2\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "ae5398cc", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Personalize your student record.\n\nconst jsonData = `\n{\n \"name\": \"Finn\",\n \"age\": 15,\n \"isStudent\": true\n}\n`;\n\n\nconst parsedData = JSON.parse(jsonData);\nconsole.log(parsedData);\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Personalize your student record again and parse it from JSON\n", - "\n", - "const jsonData = `\n", - "{\n", - " \"name\": \"Finn\",\n", - " \"age\": 15,\n", - " \"isStudent\": true\n", - "}\n", - "`;\n", - "\n", - "\n", - "const parsedData = JSON.parse(jsonData);\n", - "console.log(parsedData);" - ] - }, - { - "cell_type": "markdown", - "id": "2908433f", - "metadata": {}, - "source": [ - "Now, intentionally break it. Try these examples:\n", - "- Remove quotes from a key\n", - "- Add a trailing comma\n", - "- Change `true` to `True`\n", - "- Add a comment\n", - "\n", - "When JSON breaks, JavaScript returns an error.\n", - "This is because JSON must be readable so computers can read it reliably.\n", - "\n", - "## Section 3: Converting Between JSON and JavaScript Objects" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "7afe1114", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Converting a JavaScript object to JSON and back (with your own data)\n\nconst user = {\n username: \"coder123\",\n score: 42,\n premium: false\n};\n\n\nconst jsonString = JSON.stringify(user);\nconsole.log(jsonString);\n\n\nconst parsedUser = JSON.parse(jsonString);\nconsole.log(parsedUser);\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Converting a JavaScript object to JSON and back (with your own data)\n", - "\n", - "const user = {\n", - " username: \"coder123\",\n", - " score: 42,\n", - " premium: false\n", - "};\n", - "\n", - "\n", - "const jsonString = JSON.stringify(user);\n", - "console.log(jsonString);\n", - "\n", - "\n", - "const parsedUser = JSON.parse(jsonString);\n", - "console.log(parsedUser);" - ] - }, - { - "cell_type": "markdown", - "id": "e8bee2dc", - "metadata": {}, - "source": [ - "Try the following:\n", - "- Add a new property\n", - "- Add an array\n", - "- Add a nested object\n", - "\n", - "\n", - "## JSON Objects Summary\n", - "- Elements are stored in a hash table (key-value)\n", - "- You can edit the hash table \n", - "- Store different data types \n", - "- You can nest objects\n", - "- Purpose: store related data, store/organize more complex data, transfer data in JSON format\n", - "## Homework Assignment: JSON Challenge\n", - "Create a resume containing your personal information, skills, and education and print it as a JSON string." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f8a019f8", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Create a resume as a JavaScript Object and print to the console as JSON\n", - "\n", - "// 1. Create a JavaScript object named `resume` with the following properties:\n", - "const resume = {\n", - " fullName: \"\", // Add your full name\n", - " email: \"\", // Add your email\n", - " education: \"\", // Add your grade\n", - " address: { // Nested object\n", - " city: \"\",\n", - " state: \"\",\n", - " country: \"\"\n", - " },\n", - " skills: [] // Array of strings\n", - "};\n", - "// 2. Access and display properties for full name, email, and city using dot notation. Look at section 1.\n", - "// 3. Convert the `resume` JavaScript object into a JSON string and store it in a variable named `jsonString`, then log the JSON string to the console. Look at Section 3.\n", - "// 4. Parse the JSON string back into a JavaScript object and store it in a variable named `parsedResume`, then log the object to the console. Look at Section 3.\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "53135496", - "metadata": {}, - "source": [ - "Hint: use above code runners as examples, then edit them" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.12" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-01-20-booleans-lessons.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-01-20-booleans-lessons.ipynb deleted file mode 100644 index 71818ad6fe..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-01-20-booleans-lessons.ipynb +++ /dev/null @@ -1,249 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "2d41ee33", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Booleans]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Booleans\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "microblog: true\n", - "codemirror: true\n", - "title: Booleans\n", - "description: An intro to booleans using Code Runner\n", - "permalink: /js/booleans\n", - "author: Ahmad, Matt, Ashi\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "3e1fed1a", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - " Booleans\n", - "\n", - "- Booleans are one of the most fundamental data types in programming\n", - "- A boolean can only have two values: `true` or `false`\n", - "- Used to make decisions in code and control the flow of programs\n", - "\n", - "The basic syntax of a boolean:\n", - "```javascript\n", - "let isStudent = true;\n", - "let isRaining = false;\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "0121147c", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\nlet isActive = true;\nconsole.log(isActive);\nconsole.log(\"Boolean value: \" + isActive);\nconsole.log(\"Boolean value: \" + isActive);\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "let isActive = true;\n", - "console.log(isActive);\n", - "console.log(\"Boolean value: \" + isActive);\n", - "console.log(\"Boolean value: \" + isActive);" - ] - }, - { - "cell_type": "markdown", - "id": "3cefe1c9", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "### Usage: Boolean Comparisons\n", - "You can use comparison operators to create boolean values." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "df3dcfe5", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\nlet age = 15;\nlet isAdult = age >= 18;\nlet isTeenager = age >= 13 && age <= 19;\n\nconsole.log(\"Is adult: \" + isAdult);\nconsole.log(\"Is teenager: \" + isTeenager);\n\n// Test with different ages\nconsole.log(isAdult && isTeenager); // false - can't be both adult and teenager\nconsole.log(isAdult || isTeenager); // true - at least one is true\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "let age = 15;\n", - "let isAdult = age >= 18;\n", - "let isTeenager = age >= 13 && age <= 19;\n", - "\n", - "console.log(\"Is adult: \" + isAdult);\n", - "console.log(\"Is teenager: \" + isTeenager);\n", - "\n", - "// Test with different ages\n", - "console.log(isAdult && isTeenager); // false - can't be both adult and teenager\n", - "console.log(isAdult || isTeenager); // true - at least one is true\n" - ] - }, - { - "cell_type": "markdown", - "id": "410a4fa7", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "### Boolean Operators\n", - "Booleans can be combined using **logical operators** like `&&` (and), `||` (or), and `!` (not)" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "29a8edfd", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Run code, then change to your own conditions\nlet hasLicense = true;\nlet hasCar = false;\nlet canDrive = hasLicense && hasCar;\n\nconsole.log(\"Has license: \" + hasLicense);\nconsole.log(\"Has car: \" + hasCar);\nconsole.log(\"Can drive: \" + canDrive);\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Run code, then change to your own conditions\n", - "let hasLicense = true;\n", - "let hasCar = false;\n", - "let canDrive = hasLicense && hasCar;\n", - "\n", - "console.log(\"Has license: \" + hasLicense);\n", - "console.log(\"Has car: \" + hasCar);\n", - "console.log(\"Can drive: \" + canDrive);\n" - ] - }, - { - "cell_type": "markdown", - "id": "ce8045f6", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "source": [ - "\n", - "## HomeWork Boolean\n", - "Write a function that checks if a number is positive AND even\n", - "\n", - "Test it with an input of 8\n", - "\n", - "Hint: use the modulo operator (%) to check if a number is even, and comparison operators to check if it's positive.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "e20c7fdb", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "//code_runner: Run code, then change to your own conditions\nfunction isPositiveAndEven(num) {\n let isPositive = num > 0;\n let isEven = num % 2 === 0;\n return isPositive && isEven;\n}\n\ndocument.body.innerHTML += isPositiveAndEven(8); // true\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "//code_runner: Run code, then change to your own conditions\n", - "function isPositiveAndEven(num) {\n", - " let isPositive = num > 0;\n", - " let isEven = num % 2 === 0;\n", - " return isPositive && isEven;\n", - "}\n", - "\n", - "document.body.innerHTML += isPositiveAndEven(8); // true\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv (3.14.0)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.14.0" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-01-20-math-exp.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-01-20-math-exp.ipynb deleted file mode 100644 index 5d6735888a..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-01-20-math-exp.ipynb +++ /dev/null @@ -1,345 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "54922941", - "metadata": {}, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Mathematical-Expressions]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Mathematical-Expressions\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "title: Mathematical Expressions\n", - "permalink: /js/math\n", - "author: Samaghna Deshatty, Isha Chaturvedi, Ayden Dudley\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "e555d2ed", - "metadata": {}, - "source": [ - "## JS Lessons\n", - "\n", - "<img src=\"{{site.baseurl}}/images/Penguins-jslessons/steam_locomotive.gif\">\n", - "\n", - "\n", - "\n", - "### **Introduction to Mathematical Expresions**\n", - "\n", - "📌 What are Mathematical Expressions?\n", - "Mathematical expressions in coding are combintations of numbers, varibles, and operators that are used to calculate given values or solve problems in a program.\n", - "\n", - "For Example:\n", - "\n", - "`1 + 2 * 3;`\n", - "\n", - "> **Key Ideas:** Mathematical expressions in programming are almost idnetical to the mathematical expresions done in your math class, it is just a difference of how they are written.\n", - "\n", - "---\n", - "\n", - "### **Key Mathematical Operators**\n", - "\n", - "| Operator | Symbol | Example | Result | Example use case |\n", - "|------------------|--------|-------------|--------|-----------------------------|\n", - "| Addition | `+` | `2 + 3` | `5` | `console.log(2 + 3);` |\n", - "| Subtraction | `-` | `5 - 2` | `3` | `console.log(5 - 2);` |\n", - "| Multiplication | `*` | `4 * 3` | `12` | `console.log(4 * 3);` |\n", - "| Division | `/` | `10 / 2` | `5` | `console.log(10 / 2);` |\n", - "| Modulo | `%` | `7 % 3` | `1` | `console.log(7 % 3);` |\n", - "| Exponentiation | `**` | `2 ** 3` | `8` | `console.log(2 ** 3);` |\n", - "\n", - "You can also use inequality operators in if statements (>, <, ==, <=, =>)\n", - "\n", - "---\n", - "\n", - "### **Variables in Expressions**\n", - "You can use variables to store values and build expressions:\n", - "\n", - "`let x = 5` \n", - "\n", - "---\n", - "\n", - "### **Order of Operations**\n", - "Order of operations is used in programming just as it is used in regular math, any equation given to the cell will be done using PEMDAS\n", - "- Parentheses\n", - "- Exponents\n", - "- Multiplication/Division\n", - "- Addition/Subtraction \n", - "\n", - "In any equation that is inputed to the coding cell all eqaution will use order of operation to correctly solve the information given." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "2bae462b", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Identitfy the error in the following code and fix it. \n\nlet number = 5; \n\nconsole.log(number;);// hint: there's a syntax error here\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Identitfy the error in the following code and fix it. \n", - "\n", - "let number = 5; \n", - "\n", - "console.log(number;);// hint: there's a syntax error here" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "b4c10c33", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: How does changing the value of variables affect the output? Try changing the values of x and y below and see what happens to total1 and total2.\n\nlet x = 10;\nlet y = 3;\nlet total1 = x + y + 2; // total = 10 + 3 + 2 = 15\n\nconsole.log(\"The total is: \" + total1); // final output\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: How does changing the value of variables affect the output? Try changing the values of x and y below and see what happens to total1 and total2.\n", - "\n", - "let x = 10;\n", - "let y = 3;\n", - "let total1 = x + y + 2; // total = 10 + 3 + 2 = 15\n", - "\n", - "console.log(\"The total is: \" + total1); // final output" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "09d1d7f7", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Modulo is used to check the divisibility of certain numbers.It can also be used to see if number are even or odd, using the code below change the values of x to see how modulo works.\n\nlet x = 17;\nlet total = x % 2;\n\nconsole.log(x + \" % 2 = \" + total);\n\nif (x % 2 === 0) {\n console.log(x + \" number is even\");\n} else {\n console.log(x + \" number is odd\");\n}\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Modulo is used to check the divisibility of certain numbers.It can also be used to see if number are even or odd, using the code below change the values of x to see how modulo works.\n", - "\n", - "let x = 17;\n", - "let total = x % 2;\n", - "\n", - "console.log(x + \" % 2 = \" + total);\n", - "\n", - "if (x % 2 === 0) {\n", - " console.log(x + \" number is even\");\n", - "} else {\n", - " console.log(x + \" number is odd\");\n", - "}\n" - ] - }, - { - "cell_type": "markdown", - "id": "33955f71", - "metadata": {}, - "source": [ - "## Advanced Code ( optional )\n", - "The below code cell is built into the page. The cell shows advanced ways of building a custom runner. You must run the cell to ensure code is in page when running make or view in deployed actions. FYI, this uses most common elements you need to understand when building an interactive web page.\n", - "\n", - "\n", - "- Style for text area and buttons\n", - "- HTML Document Object Model (DOM) definitions\n", - "- Event handling\n", - "- Evaluation of the textarea example code" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f2ecbc5c", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [], - "source": [ - "<!-- Penguins custom code runner using an HTML cell -->\n", - "<style>\n", - " /* Basic styling for javascript */\n", - " textarea { width: 100%; height: 200px; }\n", - " button { margin-top: 10px; padding: 8px 16px; font-size: 14px; cursor: pointer; }\n", - "</style>\n", - "\n", - "<!-- Basic HTML structure for the challenge -->\n", - "<h2>JavaScript - Math Challenge user conventional Style, HTML, and JS</h2>\n", - "<p>Set a variable <code>x</code> to any number. Then calculate:</p>\n", - "<ul>\n", - " <li><code>x + 5</code></li>\n", - " <li><code>x * 2</code></li>\n", - " <li><code>x % 3</code> (remainder when x is divided by 3)</li>\n", - "</ul>\n", - "<p>Print all three results in a single line. Try different values of <code>x</code>!</p>\n", - "\n", - "<!-- Code editor for user input -->\n", - "<textarea id=\"code\">\n", - "// Example: change the value of x and run the code\n", - "let x = 4;\n", - "let addResult = x + 5;\n", - "let multiplyResult = x * 2;\n", - "let moduloResult = x % 3;\n", - "\n", - "\n", - "document.getElementById('output').textContent = addResult + ' ' + multiplyResult + ' ' + moduloResult;\n", - "</textarea>\n", - "<br>\n", - "<!--Run code action button-->\n", - "<button id=\"run-button\">Run Code</button>\n", - "<h3>Output:</h3>\n", - "<div id=\"output\"></div>\n", - "\n", - "\n", - "<script>\n", - " // Attach event listener in JS to the run button\n", - " document.getElementById('run-button').addEventListener('click', function() {\n", - " const code = document.getElementById('code').value;\n", - " const outputDiv = document.getElementById('output');\n", - " outputDiv.textContent = '';\n", - " try {\n", - " eval(code); // execute student code\n", - " } catch (err) {\n", - " outputDiv.textContent = 'Error: ' + err.message;\n", - " }\n", - " });\n", - "</script>" - ] - }, - { - "cell_type": "markdown", - "id": "4685c2ae", - "metadata": {}, - "source": [ - "## Homework Problems" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "ed02bd4b", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Homework Problem #1. Create a program that check if a number y is divisible by 5 or not, use modulo in this!\n// hint: use challenge problem #3 code above to help you!\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Homework Problem #1. Create a program that check if a number y is divisible by 5 or not, use modulo in this!\n", - "// hint: use challenge problem #3 code above to help you!\n" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "19cbd88e", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Homework Problem #1. Create a program that has three variables, a,b,and sum, which adds them together, use console.log to print the final output.\n// hint: use challenge problem #2 code above to help you!\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Homework Problem #1. Create a program that has three variables, a,b,and sum, which adds them together, use console.log to print the final output.\n", - "// hint: use challenge problem #2 code above to help you!" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv (3.14.0)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.14.0" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-01-27-Strings.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-01-27-Strings.ipynb deleted file mode 100644 index 3d8e01cdaf..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-01-27-Strings.ipynb +++ /dev/null @@ -1,215 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Strings]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Strings\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "title: Strings\n", - "description: Strings using Code Runner\n", - "permalink: /js/strings\n", - "author: Seonyoo Pak, Adam Ong, Roger Wang\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Introduction\n", - "\n", - "**What Exactly Are Strings?** Strings are essentially sequences of characters used to represent text in programming. They can include letters, numbers, symbols, and spaces.\n", - "\n", - "\n", - "**Example Code:**\n", - "\n", - "~~~js\n", - "// Add two strings together\n", - "\n", - "let fruit1 = \"Apple\";\n", - "let fruit2 = \"Banana\";\n", - "let combinedFruits = fruit1 + \" and \" + fruit2;\n", - "console.log(\"Fruits to eat: \" + combinedFruits);\n", - "~~~\n", - "\n", - "In the example above, there are two variables: fruit1 and fruit2. Notice how apple and banana are in quotation marks? That indicates that they are strings. In JavaScript, strings are enclosed in single quotes (' '), double quotes (\" \"), or backticks (` `). The \"and\" in between the two fruits is also a string. When we add the strings together using the + operator, we get a new string that combines them.\n", - "\n", - "Now you try:" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Identify and correct the error in the code.\n\n let sport1 = \"Soccer\";\n let sport2 = \"Basketball\";\n\n console.log(The sports I play are: + sport1 + \" and \" + sport2);\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Identify and correct the error in the code.\n", - "\n", - " let sport1 = \"Soccer\";\n", - " let sport2 = \"Basketball\";\n", - "\n", - " console.log(The sports I play are: + sport1 + \" and \" + sport2);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## String Length and Indexing\n", - "\n", - "**String Lenth:** You can find out how many characters are in a string using the `.length` property. Spaces also count as a character.\n", - "\n", - "**Example:**\n", - "\n", - "~~~js\n", - "let message = \"Hello World\";\n", - "console.log(message.length); // Will output 11 because there are 11 characters\n", - "~~~\n", - "\n", - "**String Indexing:** Each character in a string has an index, starting from 0 for the first character. You can access individual characters using bracket notation.\n", - "\n", - "**Example:**\n", - "\n", - "~~~js\n", - "let greeting = \"Hello World\";\n", - "console.log(greeting[0]); // Will output \"H\"\n", - "console.log(greeting[6]); // Will output \"W\"\n", - "~~~" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Modify this code so that the password requires at least 8 characters and the first character is equal to 3. Remember, the first character is 0, not 1.\n\nlet password = \"abc\";\nif (password.length < x || password[x] !== \"x\") { // FYI, \"||\" means OR, and \"!==\" means NOT EQUAL TO\n console.log(\"Password must be at least 8 characters and start with '3'\");\n} else {\n console.log(\"Password is valid!\");\n}\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Modify this code so that the password requires at least 8 characters and the first character is equal to 3. Remember, the first character is 0, not 1.\n", - "\n", - "let password = \"abc\";\n", - "if (password.length < 8 || password[0] !== \"3\") { // FYI, \"||\" means OR, and \"!==\" means NOT EQUAL TO\n", - " console.log(\"Password must be at least 8 characters and start with '3'\");\n", - "} else {\n", - " console.log(\"Password is valid!\");\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## String Concatenation\n", - "\n", - "**String Concatenation:** is simply the process of combining two or more strings together. In JavaScript, you can concatenate strings using the `+` operator.\n", - "\n", - "**Example:**\n", - "\n", - "~~~js\n", - "let firstName = \"John\";\n", - "let lastName = \"Smith\";\n", - "let fullName = firstName + \" \" + lastName; // Those quotation marks just add a space between the words\n", - "console.log(fullName); // Will output \"John Smith\"\n", - "~~~\n" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "\n// CODE_RUNNER: Add your own information to the constants below and use concatenation to print a sentence about yourself.\n\nconst name = \"x\";\nconst age = y;\nconst city = \"z\";\n\n// Your code here\n\n", - "text/plain": [ - "<IPython.core.display.Javascript object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Add your own information to the constants below and use concatenation to print a sentence about yourself.\n", - "\n", - "const name = \"x\";\n", - "const age = y;\n", - "const city = \"z\";\n", - "\n", - "// Your code here\n", - "\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.3" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-02-19-variables.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-02-19-variables.ipynb deleted file mode 100644 index 9e95cb215d..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-02-19-variables.ipynb +++ /dev/null @@ -1,344 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "a9e09637", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Variables]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Variables\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "title: Variables\n", - "description: HTML Domain and Variables lesson\n", - "permalink: /js/variables/\n", - "author: Aadi Saini, Daniel Livitz, Kashyap Tubati\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "3db17a4d", - "metadata": {}, - "source": [ - "### What are variables?\n", - "A variable is a container where you store stuff. Think of it like your lunchbox: `let lunchbox = \"sandwich\";`\n", - "\n", - "Meaning: \n", - "let → When creating a new variable you use let\n", - "\n", - "lunchbox → the name of the variable\n", - "\n", - "\"sandwich\" → the value or info that is stored in the variable\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "0ab366da", - "metadata": {}, - "source": [ - "### Why are variables helpful? \n", - "Instead of repeating the same thing again and again, you store it once and reuse it. \n", - "\n", - "### 1. let vs const \n", - "\n", - "When you create variables, you use let or const.\n", - "\n", - "Let is used when the value can change \n", - "**Examples:** your points in a video game, your age \n", - "\n", - "`let points = 0; points = points + 1;`\n", - "\n", - "Const is used when the value should NOT change.\n", - "**Examples:** your student ID, your birthday, your permanent username \n", - "\n", - "`const studentID = \"S12345\";` \n", - "`const birthday = \"2012-08-19\";` \n", - "`const username = \"Daniel_the_Miner\";`\n", - " Now you go ahead and try!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9ca07bd3", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Create 2 variables. One of your birthday and one of a point system that adds by 3. (Look at the reading above for help)\n", - "\n", - "let // Put a variable here\n", - "const // Put another variable here\n", - "\n", - "console.log(Points)\n", - "console.log(Birthday)" - ] - }, - { - "cell_type": "markdown", - "id": "6c8a85c8", - "metadata": {}, - "source": [ - "\n", - "### Data Types \n", - "\n", - "**A data type is what kind of value is stored in the variable. Here are the main ones:** \n", - "\n", - "\n", - "\n", - "`let pencils = 12;` Number → how many(quantitative) \n", - "\n", - "`let teacherName = \"Mr. Lee\";`String → text (You only need double quotes when writing strings) \n", - "\n", - "`let isPresent = true;` Boolean → true or false value\n", - "\n", - "`let homework;` Undefined → declared but not filled yet\n", - "\n", - "`let deskItem = null;` Null → intentionally empty" - ] - }, - { - "cell_type": "markdown", - "id": "32c4f4a8", - "metadata": {}, - "source": [ - "### Reference Data Types (Bigger containers) \n", - "\n", - "**When you need to store multiple varibles together into category.**\n", - "\n", - "Object → a bundle of related info\n", - "Array → a list of the same type of data\n", - "\n", - "**Objects**\n", - "\n", - "Instead of storing everything separately: \n", - "`let name = \"Ava\";` `let grade = 7;` `let hasPencil = true;` \n", - "\n", - "You can group it into one object: \n", - "`const student = { name: \"Ava\", grade: 7, hasPencil: true };` \n", - "\n", - "**Arrays:**\n", - "\n", - "Instead of storing every item separately:\n", - "`let snack1 = \"chips\";` `let snack2 = \"apple\";` `let snack3 = \"cookie\";`\n", - "\n", - "You can group it into one array:\n", - " `let snacks = [\"chips\", \"apple\", \"cookie\"];`" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b9c29573", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Make an an object of your favorite food, color and movie. (Refer above for help)\n", - "\n", - "console.log(FavoriteThings)" - ] - }, - { - "cell_type": "markdown", - "id": "9397a8d5", - "metadata": {}, - "source": [ - "## HTML DOM (Document Object Model)\n", - "\n", - "Now, to go to HTML DOM. Imagine HTML DOM like this: It's essentially the HTML code, but with changes applied to it. Here's a better way to visualize that: You are playing the Pong Game on the `pages.opencodingsociety.com` website, and you are playing against an AI paddle. Now, imagine a score tracker on the top that counts the points that each side has. Javascript would change the HTML DOM in this scenario by changing the amount of points each side has." - ] - }, - { - "cell_type": "markdown", - "id": "710c1092", - "metadata": {}, - "source": [ - "### So how does HTML DOM connect to variables?\n", - "\n", - "It's very simple actually. Taking something like the ping pong game, Javascript would store data like a variable for `player score` and then the DOM would just take the value of that variable and then output it to the rendered site." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c6281166", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [ - { - "data": { - "text/html": [ - "\n", - "<!-- UI_RUNNER: DOM change -->\n", - "\n", - "<!--\n", - "Update the player and AI scores when the buttons are clicked.\n", - "-->\n", - "\n", - "<button onclick=\"playerScores()\">Player Clicker: <span id=\"playerScore\">0</span></button>\n", - "<button onclick=\"aiScores()\">AI Clicker: <span id=\"aiScore\">0</span></button>\n", - "\n", - "<script>\n", - "\n", - "function playerScores() {\n", - " // Get the current player's points from the DOM\n", - " let playerPoints = parseInt(document.getElementById(\"playerScore\").textContent);\n", - " // Increment the player's points and update the DOM\n", - " playerPoints += 1;\n", - " document.getElementById(\"playerScore\").textContent = playerPoints;\n", - "}\n", - "\n", - "function aiScores() {\n", - " // Get the current AI's points from the DOM\n", - " let aiPoints = parseInt(document.getElementById(\"aiScore\").textContent);\n", - " // Increment the AI's points and update the DOM\n", - " aiPoints += 1;\n", - " document.getElementById(\"aiScore\").textContent = aiPoints;\n", - "}\n", - "</script>\n" - ], - "text/plain": [ - "<IPython.core.display.HTML object>" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%html\n", - "\n", - "<!-- UI_RUNNER: DOM change -->\n", - "\n", - "<!--\n", - "Update the player and AI scores when the buttons are clicked.\n", - "-->\n", - "\n", - "<button onclick=\"playerScores()\">Player Clicker: <span id=\"playerScore\">0</span></button>\n", - "<button onclick=\"aiScores()\">AI Clicker: <span id=\"aiScore\">0</span></button>\n", - "\n", - "<script>\n", - "\n", - "function playerScores() {\n", - " let playerPoints = parseInt(document.getElementById(\"playerScore\").textContent);\n", - " playerPoints += 1;\n", - " document.getElementById(\"playerScore\").textContent = playerPoints;\n", - "}\n", - "\n", - "function aiScores() {\n", - " let aiPoints = parseInt(document.getElementById(\"aiScore\").textContent);\n", - " aiPoints += 1;\n", - " document.getElementById(\"aiScore\").textContent = aiPoints;\n", - "}\n", - "</script>" - ] - }, - { - "cell_type": "markdown", - "id": "3490b7d3", - "metadata": {}, - "source": [ - "1. The first part of the code is the HTML button, text and DOM id → `<button>`, `<span id =>` \n", - "\n", - "2. onclick functions → `playerScores()`, `aiScores()`\n", - "\n", - "3. Click happens (button click, respective fuction is colled)\n", - "\n", - " - get value of DOM and assign variable `let playerPoints = parseInt(document.getElementById(\"playerScore\").textContent)`, or `let aiPoints = parseInt(document.getElementById(\"aiScore\").textContent)`\n", - " - increment varaible → `playerPoints += 1`, or `aiPoints += 1`;\n", - "\n", - " - set value of updat to the DOM → `document.getElementById(\"playerScore\").textContent = playerPoints;`, or `parseInt(document.getElementById(\"aiScore\").textContent) = aiPoints`" - ] - }, - { - "cell_type": "markdown", - "id": "88942812", - "metadata": {}, - "source": [ - "## HOMEWORK" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "475c5017", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Create a const object called student with your name, grade, and favorite subject.\n", - "\n", - "console.log(student);\n", - "console.log(scores);" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d0577b65", - "metadata": { - "vscode": { - "languageId": "html" - } - }, - "outputs": [], - "source": [ - "%%html\n", - "\n", - "<!-- UI_RUNNER: Extra credit - Make a Cookie Clicker -->\n", - "\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv (3.14.0)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.14.0" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-1-14-Nested-Conditionals.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-1-14-Nested-Conditionals.ipynb deleted file mode 100644 index 8b3434f9a2..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-1-14-Nested-Conditionals.ipynb +++ /dev/null @@ -1,208 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "yaml" - } - }, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Nested-Conditionals]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Nested-Conditionals\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "title: Nested Conditionals\n", - "description: Nested Conditionals using Code Runner\n", - "permalink: /js/nested-conditionals\n", - "author: Rohan Sharma, Kaden Arp\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Introduction\n", - "\n", - "**Picture this**: You're getting ready for school in the morning. \n", - "\n", - "First, you check the weather forecast.\n", - "\n", - "**IF** it's raining: \n", - "- You grab your umbrella, But then you need to check another thing - how cold is it? \n", - " - **IF** it's also cold, you pack both your umbrella **AND** your jacket. \n", - " - **ELSE** (if it's raining but it's still warm outside), just the umbrella is enough.\n", - "\n", - "**ELSE** (if it's not raining): \n", - "- You skip the umbrella, **BUT** you still need to check the temperature. \n", - " - **IF** it's cold, you'll take a jacket. \n", - " - **ELSE**, you're good to go!\n", - "\n", - "See how you're making decisions **INSIDE** other decisions? That's a **nested conditional**!\n", - "\n", - "\n", - "## Nested Conditional Code\n", - "\n", - "Now let's look at an example of the nested conditional code using the analogy above.\n", - "\n", - "~~~js\n", - "// Check the weather before leaving for school\n", - "if (raining) {\n", - " // First decision: It's raining, so take umbrella\n", - " takeUmbrella();\n", - " \n", - " // Nested decision INSIDE the raining condition\n", - " if (cold) {\n", - " takeJacket();\n", - " console.log(\"Taking umbrella AND jacket\");\n", - " } else {\n", - " console.log(\"Taking just umbrella\");\n", - " }\n", - " \n", - "} else {\n", - " // First decision: Not raining, skip umbrella\n", - " \n", - " // Nested decision INSIDE the not-raining condition\n", - " if (cold) {\n", - " takeJacket();\n", - " console.log(\"Taking just jacket\");\n", - " } else {\n", - " console.log(\"Nothing needed - good to go!\");\n", - " }\n", - "}\n", - "~~~\n", - "\n", - "In the code example above, there are 2 nested conditionals: there's one in the if statement, and one in the else statement. If it's raining, the temperature check inside the if block will run. If it's not raining, we skip the if block entirely and go to the else statement, where a different temperature check will run.\n", - "\n", - "Now you go ahead and try!" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Complete the nested conditional to make it list if the numbers 1-10 are odd or even and if they are divisible by 3.\n", - "\n", - "const NUMBERS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n", - "\n", - "for (let number of NUMBERS) {\n", - " if (number % 2 === 0) {\n", - " console.log(number + \" is even\");\n", - " \n", - " // TODO: Add a nested if statement here to check if divisible by 3\n", - " \n", - " } else {\n", - " console.log(number + \" is odd\");\n", - " \n", - " // TODO: Add a nested if statement here to check if divisible by 3\n", - " \n", - " }\n", - "}\n", - "\n", - "// Expected output:\n", - "// 1 is odd\n", - "// 2 is even\n", - "// 3 is odd\n", - "// 3 is also divisible by 3\n", - "// 4 is even\n", - "// 5 is odd\n", - "// 6 is even\n", - "// 6 is also divisible by 3\n", - "// 7 is odd\n", - "// 8 is even\n", - "// 9 is odd\n", - "// 9 is also divisible by 3\n", - "// 10 is even" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Now, you're a bouncer at a nightclub. You need to make a for loop with a nested conditional that will check if people are of the correct age, and if they aren't, it should check if they wear sunglasses. If they are underage but they still have sunglasses, they should be let in.\n", - "\n", - "// List of people trying to get into the nightclub\n", - "const people = [\n", - " { name: 'jimmy', age: 15, wearsSunglasses: false },\n", - " { name: 'sara', age: 5, wearsSunglasses: true },\n", - " { name: 'alex', age: 22, wearsSunglasses: true },\n", - " { name: 'morgan', age: 18, wearsSunglasses: false },\n", - " { name: 'dakota', age: 21, wearsSunglasses: false },\n", - " { name: 'casey', age: 25, wearsSunglasses: true }\n", - "];\n", - "\n", - "// Check everyone at the door\n", - "for (const person of people) {\n", - " if (person.age >= 21) {\n", - " // TODO: Add nested conditional to check if person wears sunglasses\n", - " // If they do, print: person.name + \" is free to enter because they're over 21 and they have sunglasses\"\n", - " // Otherwise, print: person.name + \" is free to enter\"\n", - "\n", - " } else {\n", - " // TODO: Add nested conditional to check if person wears sunglasses\n", - " // If they do, print: person.name + \" is free to enter because they have sunglasses\"\n", - " // Otherwise, print: person.name + \" is not free to enter because they are underage\"\n", - "\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Homework\n", - "Make a nested conditional that does the following: \n", - "1. contains more than 1 nested conditional\n", - "2. use the numbers 1-50\n", - "3. check if each number is divisible by each factor of 50" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "\n", - "// CODE_RUNNER: Make a nested conditional homework" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/_notebooks/CSSE/JavaScriptLessons/2026-1-27-ClassesAndMethods-Lesson.ipynb b/_notebooks/CSSE/JavaScriptLessons/2026-1-27-ClassesAndMethods-Lesson.ipynb deleted file mode 100644 index c1b6043c88..0000000000 --- a/_notebooks/CSSE/JavaScriptLessons/2026-1-27-ClassesAndMethods-Lesson.ipynb +++ /dev/null @@ -1,217 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "bfec2d01", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [JavaScript, Classes-and-Methods]\n", - "lesson_language: JavaScript\n", - "lesson_topic: Classes-and-Methods\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "microblog: true\n", - "codemirror: true\n", - "title: Classes and Methods\n", - "description: Basics of Classes and Methods\n", - "permalink: /js/classes\n", - "author: Aarnav Jain and Dean\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "6b7b76ef", - "metadata": {}, - "source": [ - "## Classes and Methods\n", - "\n", - "classes and methods are fundamental parts of coding.\n", - "\n", - " - Classes are a template for creating something. It defines what properties and behaviors the object should have. \n", - "\n", - " - For example the class car would define the color, the model, year released, etc.\n", - "\n", - " - Methods are an action that an object executes.\n", - "\n", - " - For example in the car example a method could be drive() or brake()\n", - "\n", - " - here is an example Code Runner using the example above. The code first creates a class which in this case is a car. It then defines the different properties of the car such as the brand, the color, and the speed. Lastly the method accelerate is defined, which increases speed by 10.\n" - ] - }, - { - "cell_type": "markdown", - "id": "1ce4db60", - "metadata": {}, - "source": [ - "## Why do you use Classes and Methods\n", - "\n", - " - Methods are used because they help keep the code simple. Instead of typing out a specific process everytime, you could just define a method once and then execute the method as needed.\n", - " \n", - " - For example if you are making a video game you can make a method called take damage which causes the player to lose health.\n", - "\n", - " - You would use classes to organize the code and when you have a set of data that goes together such as player, monster, ally etc." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9f8341ae", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "//CODE_RUNNER: Car Example: Try and make another method called brake which decreases speed of car by a set amount.\n", - "\n", - "//Hint: look at how accelerate is defined and use the same format for brake.\n", - "\n", - "// 1. Define the Class (The Blueprint)\n", - "class Car {\n", - " constructor(brand, color) {\n", - " this.brand = brand; \n", - " this.color = color; \n", - " this.speed = 0; //(starts at 0)\n", - " }\n", - "\n", - " // 2. Define a Method \n", - " accelerate() {\n", - " this.speed = this.speed + 10;\n", - " console.log(\"The \" + this.brand + \" is now going \" + this.speed + \"mph.\");\n", - " }\n", - "}\n", - "\n", - "// 3. Create an Instance (The actual car)\n", - "let myCar = new Car(\"Toyota\", \"Blue\");\n", - "\n", - "// 4. Use the Method\n", - "myCar.accelerate(); // \"The Toyota is now going 10mph.\"\n", - "myCar.accelerate(); // \"The Toyota is now going 20mph.\"" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2a4a66d8", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js \n", - "\n", - "//CODE_RUNNER: Car Example #2 Finish the code.\n", - "class Car {\n", - " constructor(speed, maxSpeed) {\n", - " this.speed = speed;\n", - " this.maxSpeed = maxSpeed;\n", - " }\n", - "\n", - " accelerate() {\n", - " // TODO:\n", - " // If the current speed is less than maxSpeed,\n", - " // increase speed by 10.\n", - " //\n", - " // If increasing speed would go over maxSpeed,\n", - " // set speed to maxSpeed instead.\n", - " }\n", - "\n", - " brake() {\n", - " this.speed -= 10;\n", - " if (this.speed < 0) {\n", - " this.speed = 0;\n", - " }\n", - " }\n", - "}\n", - "\n", - "// Example usage:\n", - "let myCar = new Car(90, 100);\n", - "myCar.accelerate();\n", - "console.log(myCar.speed); // should be 100, not more\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6d76be52", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js \n", - "\n", - "//CODE_RUNNER: Car example #3 Add stop method using while loop.\n", - "\n", - "class Car {\n", - " constructor(speed) {\n", - " this.speed = speed;\n", - " }\n", - "\n", - " brake() {\n", - " this.speed -= 10;\n", - " if (this.speed < 0) {\n", - " this.speed = 0;\n", - " }\n", - " }\n", - "\n", - " stop() {\n", - " // TODO:\n", - " // Keep calling brake() until the car's speed is 0\n", - " }\n", - "}\n", - "\n", - "// Example usage:\n", - "let myCar = new Car(35);\n", - "myCar.stop();\n", - "console.log(myCar.speed); // should be 0\n" - ] - }, - { - "cell_type": "markdown", - "id": "fbede36a", - "metadata": {}, - "source": [ - "## Homework" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "608cba2a", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js \n", - "\n", - "//CODE_RUNNER: Homework Challenge - Create a class and make 2 different methods.\n", - "\n", - "//Feel free to get creative with the methods. For example a class could be cat and a method could be eat and meow.\n" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-capstone.md b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-capstone.md index de28564213..58f1deea80 100644 --- a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-capstone.md +++ b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-capstone.md @@ -140,6 +140,7 @@ Sept - Nov 2026"] Multi-Camera Tracking & Room Model Nov 2026"] style P1 fill:#3b82f622,stroke:#3b82f6 + style P2 fill:#f59e0b22,stroke:#f59e0b style P3 fill:#a855f722,stroke:#a855f7</pre> </div> <div class="ocs__hub-grid" style="margin-top:1.25rem;"> diff --git a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-1.md b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-1.md index 8696baeb80..334c403075 100644 --- a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-1.md +++ b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-1.md @@ -21,14 +21,14 @@ rp_active: research-1 <!-- Header --> <div class="jv-header"> - <div class="jv-badge">Research Area 1 · Hardware & Acquisition</div> - <h1 class="jv-page-title">Research 1: Camera Setup & Hardware Pipeline</h1> - <p class="jv-description">Investigating multi-viewpoint optical coverage, synchronized frame capture, network transfer across Linux host nodes, and hardware bill of materials.</p> + <div class="ocs__badge">Research Area 1 · Hardware & Acquisition</div> + <h1 class="jv-title">Research 1: Camera Setup & Hardware Pipeline</h1> + <p class="ocs__description">Investigating multi-viewpoint optical coverage, synchronized frame capture, network transfer across Linux host nodes, and hardware bill of materials.</p> </div> <!-- Research Question --> - <div class="jv-section-label">Research Question 1</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Research Question 1</h2> + <div class="ocs__card"> <p class="jv-question">How reliably can timestamped frames from opposing viewpoints across two networked Linux nodes be synchronized and transferred at configurable intervals without frame drops, latency spikes, or timestamp drift?</p> <h3 style="margin-top:1.5rem;">Acceptance & Test Cases</h3> <ul class="ocs__checklist"> @@ -41,8 +41,8 @@ rp_active: research-1 </div> <!-- Hardware / BOM --> - <div class="jv-section-label">Bill of Materials & Hardware Status</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Bill of Materials & Hardware Status</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1rem;">The current testbed uses one Logitech BRIO connected to a primary Linux machine. The target multi-view setup introduces a second camera node.</p> <div class="ocs__table-wrap"> <table class="ocs__table"> @@ -86,14 +86,14 @@ rp_active: research-1 </tbody> </table> </div> - <div class="ocs__callout ocs__callout"> + <div class="ocs__callout"> <span><strong style="color:var(--jv-text);">Camera Placement Rationale:</strong> Mounting two cameras on opposing diagonal corners maximizes surface visibility across desks while providing redundant observations when students or chairs block a single line of sight.</span> </div> </div> <!-- Dependencies & Open Issues --> - <div class="jv-section-label">Open Issues & Next Milestones</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Open Issues & Next Milestones</h2> + <div class="ocs__card"> <ul class="ocs__checklist"> <li class="open"><span class="ocs__checklist-box"></span><span><strong style="color:var(--jv-text);">Mounting & Calibration:</strong> Finalize non-invasive mounting fixtures and measure lens distortion across wide-angle FOV settings.</span></li> <li class="open"><span class="ocs__checklist-box"></span><span><strong style="color:var(--jv-text);">Lighting Variations:</strong> Evaluate sensor auto-exposure adjustments during morning sunlight vs. artificial overhead fluorescent lighting.</span></li> diff --git a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-2.md b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-2.md index 9c92e944fc..d987064bfe 100644 --- a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-2.md +++ b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-2.md @@ -21,29 +21,29 @@ rp_active: research-2 <!-- Header --> <div class="jv-header"> - <div class="jv-badge">Research Area 2 · Object Detection & Instance Segmentation</div> - <h1 class="jv-page-title">Research 2: YOLO Object Detection & SAM 3 Segmentation</h1> - <p class="jv-description">Converting classroom images into structured object detections, then refining each bounding box into a pixel-level segmentation mask for tracking, inventory, and scene comparison.</p> + <div class="ocs__badge">Research Area 2 · Object Detection & Instance Segmentation</div> + <h1 class="jv-title">Research 2: YOLO Object Detection & SAM 3 Segmentation</h1> + <p class="ocs__description">Converting classroom images into structured object detections, then refining each bounding box into a pixel-level segmentation mask for tracking, inventory, and scene comparison.</p> <p style="font-size:0.8rem;color:var(--jv-text-muted);margin-top:0.5rem;">Individual research by <strong style="color:var(--jv-text);">Shriya Paladugu</strong></p> </div> <!-- Problem Statement --> - <div class="jv-section-label">Problem Statement</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Problem Statement</h2> + <div class="ocs__card"> <p style="font-size:0.95rem;line-height:1.75;color:var(--jv-text-muted);margin:0;"> A classroom is a constantly changing environment where people and equipment enter, leave, or move locations. A camera records pixels, but raw images alone do not tell the system what objects are present or where each object appears. The project therefore needs a computer-vision pipeline that identifies classroom objects, records their confidence scores and image locations, and separates them from the surrounding background. </p> </div> <!-- Research Question --> - <div class="jv-section-label">Research Question 2</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Research Question 2</h2> + <div class="ocs__card"> <p class="jv-question">How accurately and efficiently can a locally executed YOLO and SAM 3 pipeline detect, classify, locate, and segment important classroom objects under changing lighting, viewing angles, distance, and partial occlusion while remaining within the target 10-second processing cycle?</p> </div> <!-- Role in the Full System --> - <div class="jv-section-label">Role in the Full System</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Role in the Full System</h2> + <div class="ocs__card"> <div class="ocs__diagram"> <pre class="mermaid" style="margin:0;">flowchart TD CAP["Camera capture\nTimestamped frame"] --> PRE["OpenCV / FFmpeg\nResize + preprocessing"] @@ -52,14 +52,14 @@ rp_active: research-2 SAM --> OUT["Structured observation\nDetection + mask + timestamp"] OUT --> TRACK["Tracking / inventory /\nscene comparison"]</pre> </div> - <div class="ocs__callout ocs__callout"> + <div class="ocs__callout"> <span><strong style="color:var(--jv-text);">Why both models?</strong> YOLO identifies what an object is and provides its bounding box. SAM 3 uses that box as a prompt to trace the object's more precise pixel boundary. The segmentation mask can then support spatial comparison and object-state tracking.</span> </div> </div> <!-- Target Classes --> - <div class="jv-section-label">Initial Target Object Classes</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Initial Target Object Classes</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1rem;">The initial prototype will evaluate six common classroom classes that can support people counting and basic equipment inventory.</p> <div class="jv-decision-grid"> <div class="jv-decision-card"><span class="jv-decision-title">Person</span><p class="jv-decision-why">Supports occupancy counting without facial recognition.</p></div> @@ -72,8 +72,8 @@ rp_active: research-2 </div> <!-- Structured Output --> - <div class="jv-section-label">Detection Output</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Detection Output</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1rem;">Instead of passing only raw images to later components, the pipeline creates a structured observation for every detected object.</p> <pre class="jv-code" style="display:block;white-space:pre-wrap;overflow-x:auto;padding:1rem;margin:0;">{ "timestamp": "2026-09-07T10:15:20.000Z", @@ -83,14 +83,14 @@ rp_active: research-2 "bounding_box": [120, 80, 420, 350], "mask_reference": "camera_1_20260907_101520_laptop_01" }</pre> - <div class="ocs__callout ocs__callout"> + <div class="ocs__callout"> <span><strong style="color:var(--jv-text);">Important limitation:</strong> A detection such as “laptop” identifies an object category, not a specific physical device such as “Laptop #3.” Persistent identity must be added later through temporal tracking, cross-camera matching, visual features, or an external identifier.</span> </div> </div> <!-- Model Decisions --> - <div class="jv-section-label">Model Selection & Technical Rationale</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Model Selection & Technical Rationale</h2> + <div class="ocs__card"> <div class="jv-decision-grid"> <div class="jv-decision-card"> <span class="jv-decision-title">YOLO Object Detection</span> @@ -120,16 +120,16 @@ rp_active: research-2 </div> <!-- Why Object Detection --> -<div class="jv-section-label">Why YOLO Instead of Image Classification?</div> -<div class="jv-card"> - <p style="font-size:0.95rem;line-height:1.75;color:var(--jv-text-muted);margin:0;"> - A standard image-classification model can predict that a classroom image contains a laptop, but it does not identify every separate laptop or show where each one is located. YOLO performs both classification and localization, allowing the system to detect multiple objects in one frame and return an individual class label, confidence score, and bounding box for each object. This makes YOLO more suitable for classroom inventory, people counting, tracking, and scene comparison. - </p> -</div> + <h2 class="ocs__section-title">Why YOLO Instead of Image Classification?</h2> + <div class="ocs__card"> + <p style="font-size:0.95rem;line-height:1.75;color:var(--jv-text-muted);margin:0;"> + A standard image-classification model can predict that a classroom image contains a laptop, but it does not identify every separate laptop or show where each one is located. YOLO performs both classification and localization, allowing the system to detect multiple objects in one frame and return an individual class label, confidence score, and bounding box for each object. This makes YOLO more suitable for classroom inventory, people counting, tracking, and scene comparison. + </p> + </div> <!-- Acceptance Tests --> - <div class="jv-section-label">Acceptance Criteria & Test Cases</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Acceptance Criteria & Test Cases</h2> + <div class="ocs__card"> <ul class="ocs__checklist"> <li class="open"><span class="ocs__checklist-box"></span><span>Capture a timestamped classroom frame and return a class label, confidence score, and bounding box for every accepted YOLO detection</span></li> <li class="open"><span class="ocs__checklist-box"></span><span>Evaluate all six target classes using a separate held-out test set that was not used for training</span></li> @@ -143,9 +143,9 @@ rp_active: research-2 </div> <!-- Compute Plan --> - <div class="jv-section-label">Compute Constraints & Benchmark Plan</div> - <div class="jv-card"> - <div class="ocs__callout ocs__callout" style="margin-top:0;"> + <h2 class="ocs__section-title">Compute Constraints & Benchmark Plan</h2> + <div class="ocs__card"> + <div class="ocs__callout" style="margin-top:0;"> <span><strong style="color:var(--jv-text);">Current constraint:</strong> The primary Linux host does not have a dedicated NVIDIA GPU. All latency values must therefore be measured on the actual project hardware rather than treated as guaranteed model performance.</span> </div> <div class="ocs__table-wrap" style="margin-top:1rem;"> @@ -161,8 +161,8 @@ rp_active: research-2 </div> <!-- Risks and Next Steps --> - <div class="jv-section-label">Open Questions & Next Steps</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Open Questions & Next Steps</h2> + <div class="ocs__card"> <ul class="ocs__checklist"> <li class="open"><span class="ocs__checklist-box"></span><span><strong style="color:var(--jv-text);">Baseline Test:</strong> Determine which target classes are already supported reliably by the pretrained YOLO model.</span></li> <li class="open"><span class="ocs__checklist-box"></span><span><strong style="color:var(--jv-text);">Dataset:</strong> Collect representative classroom images across both camera viewpoints and split them into training, validation, and held-out test sets.</span></li> @@ -173,8 +173,8 @@ rp_active: research-2 </div> <!-- Sources --> - <div class="jv-section-label">Technical Sources</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Technical Sources</h2> + <div class="ocs__card"> <div class="jv-paper-grid"> <div class="jv-paper-card"> <a class="jv-paper-title" href="https://docs.ultralytics.com/tasks/detect/" target="_blank" rel="noopener">Ultralytics Object Detection Documentation</a> diff --git a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-3.md b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-3.md index 646c76678b..ca5bb9e363 100644 --- a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-3.md +++ b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-3.md @@ -21,27 +21,27 @@ rp_active: research-3 <!-- Header --> <div class="jv-header"> - <div class="jv-badge">Research Area 3 · Computer Vision · Spatial Awareness · Classroom Safety</div> - <h1 class="jv-page-title">Multi-Camera Spatial Perception & Distance Estimation</h1> - <p class="jv-description">Two Logitech BRIO 4K cameras, mounted on opposite sides of the room.</p> + <div class="ocs__badge">Research Area 3 · Computer Vision · Spatial Awareness · Classroom Safety</div> + <h1 class="jv-title">Multi-Camera Spatial Perception & Distance Estimation</h1> + <p class="ocs__description">Two Logitech BRIO 4K cameras, mounted on opposite sides of the room.</p> <p style="font-size:0.8rem;color:var(--jv-text-muted);margin-top:0.5rem;">Individual research by <strong style="color:var(--jv-text);">Sonika Dhenuva Konda</strong></p> </div> <!-- Problem Statement --> - <div class="jv-section-label">Problem Statement</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Problem Statement</h2> + <div class="ocs__card"> <p style="font-size:0.9rem;line-height:1.7;color:var(--jv-text-muted);margin:0;">People and equipment constantly move around a busy classroom. A standard camera can see what's in the room, but not how far away it is or where it sits in 3D. Two wide-spaced cameras, fused with depth models and geometry, can fix that.</p> </div> <!-- Research Question --> - <div class="jv-section-label">Research Question</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Research Question</h2> + <div class="ocs__card"> <p class="jv-question">How can a setup of two wide-spaced 4K cameras combine separate 2D video feeds using deep learning models and geometry to accurately measure real-world distances and build a continuous 3D spatial map of a classroom?</p> </div> <!-- Pipeline diagram --> - <div class="jv-section-label">Pipeline</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Pipeline</h2> + <div class="ocs__card"> <div class="ocs__diagram"> <pre class="mermaid" style="margin:0;">flowchart TD C1["Camera 1, BRIO @@ -67,8 +67,8 @@ Object boxes"] </div> <!-- Equipment, Libraries, AI Models --> - <div class="jv-section-label">Equipment, Libraries & AI Models</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Equipment, Libraries & AI Models</h2> + <div class="ocs__card"> <div class="jv-decision-grid"> <div class="jv-decision-card"> <span class="jv-decision-title">2× Logitech BRIO 4K</span> @@ -106,8 +106,8 @@ Object boxes"] </div> <!-- Background Research: depth-sensing approaches --> - <div class="jv-section-label">Background: How Machines Sense Depth</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Background: How Machines Sense Depth</h2> + <div class="ocs__card"> <div class="jv-decision-grid"> <div class="jv-decision-card"> <span class="jv-decision-title">Stereo Vision (chosen)</span> @@ -129,8 +129,8 @@ Object boxes"] </div> <!-- Academic Research Papers --> - <div class="jv-section-label">Academic Research Papers</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Academic Research Papers</h2> + <div class="ocs__card"> <div class="jv-paper-grid"> <div class="jv-paper-card"> <a class="jv-paper-title" href="https://arxiv.org/abs/2406.09414" target="_blank" rel="noopener">Depth Anything V2</a> @@ -186,8 +186,8 @@ Object boxes"] </div> <!-- Patent Reference --> - <div class="jv-section-label">Patent Reference</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Patent Reference</h2> + <div class="ocs__card"> <div class="jv-paper-grid"> <div class="jv-paper-card"> <a class="jv-paper-title" href="https://patents.google.com/patent/US11321876B2" target="_blank" rel="noopener">Non-rigid Stereo Vision Camera System</a> @@ -203,8 +203,8 @@ Object boxes"] </div> <!-- Online Sources --> - <div class="jv-section-label">Online Sources</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Online Sources</h2> + <div class="ocs__card"> <div class="jv-paper-grid"> <div class="jv-paper-card"> <a class="jv-paper-title" href="https://www.e-consystems.com/blog/camera/technology/the-ultimate-guide-to-depth-perception-and-3d-imaging-technologies/" target="_blank" rel="noopener">e-con Systems: Depth Perception & 3D Imaging</a> diff --git a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-4.md b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-4.md index fcde20682d..9f26785d70 100644 --- a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-4.md +++ b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-research-4.md @@ -21,14 +21,14 @@ rp_active: research-4 <!-- Header --> <div class="jv-header"> - <div class="jv-badge">Research Area 4 · Visual Memory & Scene Comparison</div> - <h1 class="jv-page-title">Research 4: Visual Memory & Scene Comparison</h1> - <p class="jv-description">Investigating interval-based change detection, structural gradient matching for illumination/shadow invariance, and lightweight edge-AI vs. cloud-dependent architectures.</p> + <div class="ocs__badge">Research Area 4 · Visual Memory & Scene Comparison</div> + <h1 class="jv-title">Research 4: Visual Memory & Scene Comparison</h1> + <p class="ocs__description">Investigating interval-based change detection, structural gradient matching for illumination/shadow invariance, and lightweight edge-AI vs. cloud-dependent architectures.</p> </div> <!-- Research Question --> - <div class="jv-section-label">Research Question 4</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Research Question 4</h2> + <div class="ocs__card"> <p class="jv-question">How can an AI camera system spot real changes in a room (like a moved or missing object) every 10 seconds without being fooled by shadows or light changes?</p> <div style="margin-top:1.25rem;text-align:center;"> <img src="https://github.com/user-attachments/assets/d326d254-c8b8-48c3-976f-8248f82aba0a" alt="Visual Memory Scene Comparison" style="max-width:100%;border-radius:0.75rem;border:1px solid var(--jv-card-border);display:block;margin:0 auto;"> @@ -36,8 +36,8 @@ rp_active: research-4 </div> <!-- Problem Statement & Architecture --> - <div class="jv-section-label">Specific Problem Statement & Strategy</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Specific Problem Statement & Strategy</h2> + <div class="ocs__card"> <p style="font-size:0.95rem;line-height:1.75;color:var(--jv-text-muted);margin:0 0 1.25rem;"> Conventional security cameras often produce false alarms from shifting sunlight, moving shadows, and transient ambient motion, while struggling to reliably detect permanent, meaningful changes in physical room state (such as moved, missing, or newly introduced equipment). </p> @@ -71,8 +71,8 @@ rp_active: research-4 </div> <!-- Academic Literature --> - <div class="jv-section-label">Scholarly Research & Academic Baseline</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Scholarly Research & Academic Baseline</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1rem;">Analysis of recent peer-reviewed change-detection architectures and visual memory frameworks:</p> <div class="ocs__table-wrap"> @@ -109,7 +109,7 @@ rp_active: research-4 </table> </div> - <div class="ocs__callout ocs__callout" style="margin-top:1rem;"> + <div class="ocs__callout" style="margin-top:1rem;"> <strong style="color:var(--jv-text);">Consolidated Synthesis:</strong> Academic research confirms that feature-aggregation models coupled with persistent visual memory reliably isolate genuine structural changes from lighting noise. Jarvis fills the gap by packaging these principles into a standalone, edge-based framework operating at discrete 10-second intervals. </div> @@ -119,8 +119,8 @@ rp_active: research-4 </div> <!-- Patent Research --> - <div class="jv-section-label">Patent Research & Prior IP</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Patent Research & Prior IP</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1rem;">Patented machine vision techniques addressing illumination invariance and background subtraction:</p> <div class="ocs__table-wrap"> @@ -163,8 +163,8 @@ rp_active: research-4 </div> <!-- Commercial Product Research --> - <div class="jv-section-label">Commercial Products & Competitive Analysis</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Commercial Products & Competitive Analysis</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1.25rem;">Evaluation of existing consumer and enterprise camera systems:</p> <div class="ocs__table-wrap"> diff --git a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-technical.md b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-technical.md index 02f0d9b443..1458caae69 100644 --- a/_posts/capstone/Jarvis3000/2026-09-01-jarvis-technical.md +++ b/_posts/capstone/Jarvis3000/2026-09-01-jarvis-technical.md @@ -21,14 +21,14 @@ rp_active: technical <!-- Header --> <div class="jv-header"> - <div class="jv-badge">Technical Specification · Architecture & Lifecycle</div> - <h1 class="jv-page-title">Technical Detail & System Flow</h1> - <p class="jv-description">In-depth state machines, capture loops, data schemas, and privacy governance models underpinning the Jarvis classroom perception pipeline.</p> + <div class="ocs__badge">Technical Specification · Architecture & Lifecycle</div> + <h1 class="jv-title">Technical Detail & System Flow</h1> + <p class="ocs__description">In-depth state machines, capture loops, data schemas, and privacy governance models underpinning the Jarvis classroom perception pipeline.</p> </div> <!-- Capture and processing loop --> - <div class="jv-section-label">Capture & Processing Logic</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Capture & Processing Logic</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 0.25rem;">Each capture cycle creates a timestamped observation. Jarvis preserves the original frame, processes it through YOLO and SAM 3, and compares the result with recent observations before changing the room model.</p> <div class="ocs__diagram"> <pre class="mermaid" style="margin:0;">sequenceDiagram @@ -51,8 +51,8 @@ rp_active: technical </div> <!-- Detection and tracking lifecycle --> - <div class="jv-section-label">Detection & Tracking Lifecycle</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Detection & Tracking Lifecycle</h2> + <div class="ocs__card"> <div class="ocs__diagram"> <pre class="mermaid" style="margin:0;">flowchart LR A[YOLO detection] --> B["SAM 3 mask @@ -83,8 +83,8 @@ and observation record"] </div> <!-- Design decisions --> - <div class="jv-section-label">Design Decisions & Rationale</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Design Decisions & Rationale</h2> + <div class="ocs__card"> <div class="jv-decision-grid"> <div class="jv-decision-card"> <span class="jv-decision-title">Two cameras, opposite sides</span> @@ -138,8 +138,8 @@ and observation record"] </div> <!-- Privacy / governance --> - <div class="jv-section-label">Privacy, Scope & Governance</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Privacy, Scope & Governance</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1rem;">Jarvis is designed to understand classroom objects, not identify or monitor individual people:</p> <div class="ocs__table-wrap"> <table class="ocs__table"> @@ -154,14 +154,14 @@ and observation record"] </tbody> </table> </div> - <div class="ocs__callout ocs__callout"> + <div class="ocs__callout"> <span>A generic person mask may explain why a previously confirmed object is temporarily invisible. In that case, Jarvis should prefer <span class="jv-code">OCCLUDED</span> over immediately changing the object to <span class="jv-code">MISSING</span>.</span> </div> </div> <!-- People Occupancy Tracking --> - <div class="jv-section-label">People Occupancy Tracking</div> - <div class="jv-card"> + <h2 class="ocs__section-title">People Occupancy Tracking</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1rem;">Generic <span class="jv-code">person</span> detections are counted, not identified, to produce a room occupancy number and flag presence at unexpected hours.</p> <div class="ocs__diagram"> <pre class="mermaid" style="margin:0;">flowchart LR @@ -190,14 +190,14 @@ occupancy"]</pre> <div class="jv-occupancy-bar"><span class="jv-occupancy-bar-value">0</span><div class="jv-occupancy-bar-fill" style="height:1%;background:var(--jv-red);"></div><span class="jv-occupancy-bar-label">9p+</span></div> </div> </div> - <div class="ocs__callout ocs__callout"> + <div class="ocs__callout"> <span>Counts only, no identity — consistent with the privacy design above.</span> </div> </div> <!-- Hardware / Bill of Materials --> - <div class="jv-section-label">Hardware / Bill of Materials</div> - <div class="jv-card"> + <h2 class="ocs__section-title">Hardware / Bill of Materials</h2> + <div class="ocs__card"> <div class="jv-bom-grid"> <div class="jv-bom-card"> <div class="jv-bom-thumb"><img src="/images/capstone/jarvis-bom/brio-webcam.png" alt="Logitech BRIO webcam"></div> @@ -242,17 +242,17 @@ occupancy"]</pre> <p class="jv-bom-note">Cross-network SSH + transfer.</p> </div> </div> - <div class="ocs__callout ocs__callout"> + <div class="ocs__callout"> <span>Costs are rough estimates; camera mount and Linux computer photos are representative, not the exact model.</span> </div> - <div class="ocs__callout ocs__callout"> + <div class="ocs__callout"> <span><strong style="color:var(--jv-text);">Open problem:</strong> camera height, angle, overlap, and cable routing still need on-site testing.</span> </div> </div> <!-- In-Depth Timeline --> - <div class="jv-section-label">In-Depth Timeline</div> - <div class="jv-card"> + <h2 class="ocs__section-title">In-Depth Timeline</h2> + <div class="ocs__card"> <p style="font-size:0.875rem;color:var(--jv-text-muted);margin:0 0 1rem;">Build schedule through end of November. First two weeks are camera research only, no recognition work.</p> <div class="jv-timeline-bar"> <div class="jv-timeline-seg" style="flex:14 1 0%;background:var(--jv-accent);">Phase 1</div> @@ -267,7 +267,7 @@ occupancy"]</pre> <div class="jv-timeline-legend-item"><span class="jv-timeline-legend-dot" style="background:var(--jv-amber);"></span>Phase 2 · Recognition & segmentation</div> <div class="jv-timeline-legend-item"><span class="jv-timeline-legend-dot" style="background:var(--jv-purple);"></span>Phase 3 · Tracking & room model</div> </div> - <div class="ocs__callout ocs__callout"> + <div class="ocs__callout"> <span>Dates track the <a href="/capstone/jarvis/" style="color:var(--jv-accent);">Project Phases</a> on the Overview tab and may shift with CPU benchmarking results.</span> </div> </div> diff --git a/_sass/capstone/jarvis.scss b/_sass/capstone/jarvis.scss index 6115fa82cd..6c3ecb5553 100644 --- a/_sass/capstone/jarvis.scss +++ b/_sass/capstone/jarvis.scss @@ -10,14 +10,15 @@ --jv-text-muted: var(--text-muted); --jv-accent: var(--pref-accent-color); --jv-accent-soft: color-mix(in srgb, var(--pref-accent-color) 15%, transparent); - --jv-success: var(--pref-accent-color); - --jv-success-soft: color-mix(in srgb, var(--pref-accent-color) 12%, transparent); + --jv-success: #22c55e; + --jv-success-soft: color-mix(in srgb, #22c55e 12%, transparent); --jv-tag: var(--ui-bg); - --jv-purple: var(--pref-accent-color); - --jv-amber: var(--pref-accent-color); - --jv-amber-soft: color-mix(in srgb, var(--pref-accent-color) 12%, transparent); - --jv-red: var(--pref-accent-color); - --jv-red-soft: color-mix(in srgb, var(--pref-accent-color) 12%, transparent); + --jv-purple: #a855f7; + --jv-purple-soft: color-mix(in srgb, #a855f7 12%, transparent); + --jv-amber: #f59e0b; + --jv-amber-soft: color-mix(in srgb, #f59e0b 12%, transparent); + --jv-red: #ef4444; + --jv-red-soft: color-mix(in srgb, #ef4444 12%, transparent); --jv-surface: color-mix(in srgb, var(--pref-text-color) 6%, var(--pref-bg-color)); --jv-surface-strong: color-mix(in srgb, var(--pref-text-color) 12%, var(--pref-bg-color)); --jv-overlay: color-mix(in srgb, var(--pref-bg-color) 50%, transparent); From f0013ec8e95ba15f31badeca084c0f31bbe62294 Mon Sep 17 00:00:00 2001 From: Aashihegu <aashihegu1@gmail.com> Date: Mon, 14 Sep 2026 14:13:22 -0700 Subject: [PATCH 02/43] Removed random buttons/texts --- _posts/capstone/2026-09-08-oak-cancer-capstone.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/_posts/capstone/2026-09-08-oak-cancer-capstone.md b/_posts/capstone/2026-09-08-oak-cancer-capstone.md index 08310145a5..756688c4ab 100644 --- a/_posts/capstone/2026-09-08-oak-cancer-capstone.md +++ b/_posts/capstone/2026-09-08-oak-cancer-capstone.md @@ -87,9 +87,3 @@ permalink: /capstone/oak/ </div> </div> - -**Powered by OCS grids and buttons** - -[Open project]({{ site.baseurl }}/capstone/oak/) - -[Buttons]({{ '/navigation/sass/buttons/' | relative_url }}) | [Grids]({{ '/navigation/sass/grids/' | relative_url }}) \ No newline at end of file From e578c3eb245f3470b1aa4032752c21ab9de4763d Mon Sep 17 00:00:00 2001 From: Aashihegu <aashihegu1@gmail.com> Date: Mon, 14 Sep 2026 15:13:29 -0700 Subject: [PATCH 03/43] Added different headers --- .../2026-09-08-oak-cancer-capstone.md | 88 +++++++++---------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/_posts/capstone/2026-09-08-oak-cancer-capstone.md b/_posts/capstone/2026-09-08-oak-cancer-capstone.md index 756688c4ab..d2c9936e7a 100644 --- a/_posts/capstone/2026-09-08-oak-cancer-capstone.md +++ b/_posts/capstone/2026-09-08-oak-cancer-capstone.md @@ -8,82 +8,80 @@ permalink: /capstone/oak/ --- -> This capstone project aims to connect and educate both cancer families and cancer patients. We aim to create a platform where people can learn more about cancer on a biological level through interactive learning modules, as well as connect cancer patients through interactive multiplayer games. Rather than cancer websites having long strings of text, people of all ages will be able to easily navigate, learn, and play through these new and advanced modules. +## The Basics and What It Aims to Do -<div class="ocs__grid ocs__grid--standard cols-3" style="margin-bottom: 1.5rem;"> +This capstone project is designed to connect and educate cancer patients and their families through a more engaging, accessible digital experience. Our goal is to create a platform that helps users understand cancer at a biological level through interactive educational modules while also creating opportunities for connection and community through multiplayer games and collaborative experiences. Rather than relying on long text-heavy pages, the project aims to make information easier to navigate, more visually engaging, and more approachable for users of all ages. - <div class="ocs__grid-cell ocs__grid-cell--header">Why We Chose This Project</div> +## Why We Chose This Project - <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Why We Chose This Project</strong> - <p>We chose this project because we wanted to help kids with cancer feel more included in society. Many kids with cancer spend a lot of time in hospitals or away from school and their friends. We wanted to create a website where they can learn, have fun, and connect with other people who understand what they are going through. We also wanted to make something more interactive than a regular cancer website.</p> - <a class="ocs__btn alert-green fill small" href="https://oncologyandkids.org/"> - Official Website - </a> - </div> +We chose this project because we wanted to help children with cancer feel more included, informed, and supported. Many young patients spend significant time in hospitals, at home, or away from school and their peers, which can make them feel isolated. We wanted to build a website that provides both education and connection, giving children a place to learn, play, and engage with others who understand their experiences. We also wanted to create something more interactive and welcoming than a standard informational cancer website. - <div class="ocs__grid-cell"> - <strong>Our Team and Roles</strong> - <p>Our team consists of Salma, Isha, Aashi, and Emily. Salma is our Scrum Master because she is a good leader and has experience helping organize projects and working with a team. Isha, Aashi, and Emily are our developers and coders. We will work together on building the website, creating interactive learning modules, and developing games and other features.</p> - <a class="ocs__btn alert-yellow fill small" href="https://oncologyandkids.org/"> - Official Website - </a> - </div> +## Our Team + +Our team consists of Salma, Isha, Aashi, and Emily. Salma serves as our Scrum Master, helping guide project organization, communication, and team coordination. Isha, Aashi, and Emily are our developers and programmers, and together we are responsible for building the website, designing educational content, and creating interactive features that support the project’s goals. + +<div class="ocs__grid ocs__grid--standard cols-3" style="margin-bottom: 1.5rem;"> + + <div class="ocs__grid-cell ocs__grid-cell--header">Project Goals and Core Features</div> <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Making Kids Feel Included</strong> - <p>Our goal is to make kids with cancer feel like they are part of a community. We want them to have a place where they can learn new things, play games, and interact with others. We hope our website can help them feel less left out and show that they can still do fun and interesting things while going through cancer treatment.</p> - <a class="ocs__btn alert-green fill small" href="https://oncologyandkids.org/"> - Official Website + <strong>Community Support and Inclusion</strong> + <p>Our goal is to create a space where young patients feel seen, supported, and part of a broader community. By combining learning, play, and interaction, we hope to reduce feelings of isolation and help users feel more connected to others navigating similar experiences.</p> + <a class="ocs__btn alert-green fill small" href="#community-support"> + Implementation Goal </a> </div> <div class="ocs__grid-cell"> - <strong>How are we feeling today check in/poll</strong> - <p>A daily poll where users can share how they are feeling and interact with others in the cancer community. The poll can reset every day. The question can either stay the same or change each day.</p> - <a class="ocs__btn alert-yellow fill small" href="https://oncologyandkids.org/"> - View Example + <strong>Daily Check-In and Emotional Support</strong> + <p>A daily check-in feature where users can share how they are feeling and interact with members of the cancer community. The prompt can remain consistent or rotate daily, creating a simple way for users to reflect on their emotional wellbeing and connect with others.</p> + <a class="ocs__btn alert-yellow fill small" href="#daily-check-in"> + Planned Feature </a> </div> <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Implement online games for them to play</strong> - <p>Different types of games to engage and entertain kids while scrolling the website. It would make the experience more enjoyable. Games could include puzzles, memory games, or other interactive games. Gives kids something fun to do while using the website. Online games, where they can connect.</p> - <a class="ocs__btn alert-green fill small" href="https://oncologyandkids.org/"> - Official Website + <strong>Interactive Educational Games</strong> + <p>We aim to include engaging games that make the website more enjoyable and interactive. These could include puzzles, memory exercises, and other activities designed to entertain users while supporting learning and encouraging healthy engagement.</p> + <a class="ocs__btn alert-green fill small" href="#interactive-games"> + Feature Concept </a> </div> <div class="ocs__grid-cell"> - <strong>Have informational files be able to be filtered by reading level</strong> - <p>Information can be filtered by reading level so kids, teens, and parents can find information that is easier for them to understand. There could be a kids, teens, and parents reading level. This would make the information less confusing and overwhelming. Statistics page (Updated from old website).</p> - <a class="ocs__btn alert-yellow fill small" href="https://oncologyandkids.org/"> - Official Website + <strong>Accessible Information by Reading Level</strong> + <p>Content can be organized by reading level so that children, teens, and parents can access information that is clear and appropriately tailored to their needs. This approach makes medical and scientific information easier to understand and less overwhelming.</p> + <a class="ocs__btn alert-yellow fill small" href="#reading-levels"> + Planned Feature </a> </div> <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Risk Calculator</strong> - <p>Conduct research and produce a risk calculator, where symptoms can be input. Not only will the type of cancer be identified, but your risk of mortality as well as the type of cancer you have/ link you to a doc for you to learn more about your type of cancer.</p> - <a class="ocs__btn alert-green fill small" href="https://oncologyandkids.org/"> - Official Website + <strong>Risk Calculator and Educational Guidance</strong> + <p>We also hope to include a research-based risk calculator that allows users to input symptoms and receive information about possible concerns. This feature would help connect patients with relevant information and support them in learning more about their health in a guided, informative way.</p> + <a class="ocs__btn alert-green fill small" href="#risk-calculator"> + Implementation Goal </a> </div> <div class="ocs__grid-cell"> - <strong>Cell lab incorporation</strong> - <p>Incorporate the old cell lab UI. Make the UI more accessible and easier to understand. Mentors could answer questions or talk with users about their experiences. The chat would need to be monitored to keep users safe.</p> - <a class="ocs__btn alert-yellow fill small" href="https://oncologyandkids.org/"> - Official Website + <strong>Cell Lab and Interactive Learning</strong> + <p>Incorporating a more accessible and engaging version of the previous cell lab interface would create a stronger educational experience. This feature would support learning by allowing users to explore scientific concepts in a way that is clearer and easier to understand.</p> + <a class="ocs__btn alert-yellow fill small" href="#cell-lab"> + Feature Concept </a> </div> <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Body Map</strong> - <p>A body map taking heavy inspiration from the old cancer project, potentially made cleaner, easier to navigate, and 'kid-efied'.</p> - <a class="ocs__btn alert-green fill small" href="https://oncologyandkids.org/"> - Official Website + <strong>Body Map Learning Tool</strong> + <p>A body map feature inspired by previous cancer education work could provide a cleaner, more intuitive, and child-friendly way for users to learn about the body and different aspects of cancer care.</p> + <a class="ocs__btn alert-green fill small" href="#body-map"> + Planned Feature </a> </div> </div> + +## Future Directions + +As the project continues to develop, we plan to expand the platform with additional educational resources, more inclusive community features, and stronger interactive tools that support both learning and emotional wellbeing. Our aim is to create a site that is informative, supportive, and engaging for the families and patients it serves. From f18697eef0b68443505a9edb6b2fd7aef16f517c Mon Sep 17 00:00:00 2001 From: Aashihegu <aashihegu1@gmail.com> Date: Mon, 14 Sep 2026 15:24:19 -0700 Subject: [PATCH 04/43] Changed header locations and information areas --- .../2026-09-08-oak-cancer-capstone.md | 62 +++++++++---------- 1 file changed, 29 insertions(+), 33 deletions(-) diff --git a/_posts/capstone/2026-09-08-oak-cancer-capstone.md b/_posts/capstone/2026-09-08-oak-cancer-capstone.md index d2c9936e7a..01de77fa1f 100644 --- a/_posts/capstone/2026-09-08-oak-cancer-capstone.md +++ b/_posts/capstone/2026-09-08-oak-cancer-capstone.md @@ -22,66 +22,62 @@ Our team consists of Salma, Isha, Aashi, and Emily. Salma serves as our Scrum Ma <div class="ocs__grid ocs__grid--standard cols-3" style="margin-bottom: 1.5rem;"> - <div class="ocs__grid-cell ocs__grid-cell--header">Project Goals and Core Features</div> + <div class="ocs__grid-cell ocs__grid-cell--header">Core Features</div> - <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Community Support and Inclusion</strong> - <p>Our goal is to create a space where young patients feel seen, supported, and part of a broader community. By combining learning, play, and interaction, we hope to reduce feelings of isolation and help users feel more connected to others navigating similar experiences.</p> + <div class="ocs__grid-cell ocs__grid-cell--accent" id="community-support"> + <strong>Community Support</strong> + <p>Create a welcoming space for kids and families to feel connected, supported, and less isolated while navigating cancer treatment and recovery.</p> <a class="ocs__btn alert-green fill small" href="#community-support"> - Implementation Goal + Community Support </a> </div> - <div class="ocs__grid-cell"> - <strong>Daily Check-In and Emotional Support</strong> - <p>A daily check-in feature where users can share how they are feeling and interact with members of the cancer community. The prompt can remain consistent or rotate daily, creating a simple way for users to reflect on their emotional wellbeing and connect with others.</p> + <div class="ocs__grid-cell" id="daily-check-in"> + <strong>Daily Check-In</strong> + <p>Offer a simple daily mood check-in so users can share how they are feeling and connect with others in a supportive, low-pressure way.</p> <a class="ocs__btn alert-yellow fill small" href="#daily-check-in"> - Planned Feature + Daily Check-In </a> </div> - <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Interactive Educational Games</strong> - <p>We aim to include engaging games that make the website more enjoyable and interactive. These could include puzzles, memory exercises, and other activities designed to entertain users while supporting learning and encouraging healthy engagement.</p> + <div class="ocs__grid-cell ocs__grid-cell--accent" id="interactive-games"> + <strong>Interactive Games</strong> + <p>Include fun learning-based games such as puzzles and memory activities to keep the experience engaging, uplifting, and interactive.</p> <a class="ocs__btn alert-green fill small" href="#interactive-games"> - Feature Concept + Interactive Games </a> </div> - <div class="ocs__grid-cell"> - <strong>Accessible Information by Reading Level</strong> - <p>Content can be organized by reading level so that children, teens, and parents can access information that is clear and appropriately tailored to their needs. This approach makes medical and scientific information easier to understand and less overwhelming.</p> + <div class="ocs__grid-cell" id="reading-levels"> + <strong>Reading Level Filters</strong> + <p>Sort educational content by reading level so children, teens, and parents can access information that feels understandable and age-appropriate.</p> <a class="ocs__btn alert-yellow fill small" href="#reading-levels"> - Planned Feature + Reading Level Filters </a> </div> - <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Risk Calculator and Educational Guidance</strong> - <p>We also hope to include a research-based risk calculator that allows users to input symptoms and receive information about possible concerns. This feature would help connect patients with relevant information and support them in learning more about their health in a guided, informative way.</p> + <div class="ocs__grid-cell ocs__grid-cell--accent" id="risk-calculator"> + <strong>Risk Calculator</strong> + <p>Build an educational risk tool that helps users explore health information in a guided and accessible way while encouraging learning.</p> <a class="ocs__btn alert-green fill small" href="#risk-calculator"> - Implementation Goal + Risk Calculator </a> </div> - <div class="ocs__grid-cell"> - <strong>Cell Lab and Interactive Learning</strong> - <p>Incorporating a more accessible and engaging version of the previous cell lab interface would create a stronger educational experience. This feature would support learning by allowing users to explore scientific concepts in a way that is clearer and easier to understand.</p> + <div class="ocs__grid-cell" id="cell-lab"> + <strong>Cell Lab</strong> + <p>Refresh the old cell lab into a clearer, more engaging learning experience that helps users understand cancer-related science in a simpler way.</p> <a class="ocs__btn alert-yellow fill small" href="#cell-lab"> - Feature Concept + Cell Lab </a> </div> - <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Body Map Learning Tool</strong> - <p>A body map feature inspired by previous cancer education work could provide a cleaner, more intuitive, and child-friendly way for users to learn about the body and different aspects of cancer care.</p> + <div class="ocs__grid-cell ocs__grid-cell--accent" id="body-map"> + <strong>Body Map</strong> + <p>Create a kid-friendly body map tool that makes complex health concepts easier to explore and understand through interaction.</p> <a class="ocs__btn alert-green fill small" href="#body-map"> - Planned Feature + Body Map </a> </div> </div> - -## Future Directions - -As the project continues to develop, we plan to expand the platform with additional educational resources, more inclusive community features, and stronger interactive tools that support both learning and emotional wellbeing. Our aim is to create a site that is informative, supportive, and engaging for the families and patients it serves. From 59542db15e32173310069fbe1a0f397d9b6ed8d2 Mon Sep 17 00:00:00 2001 From: Aashihegu <aashihegu1@gmail.com> Date: Mon, 14 Sep 2026 15:33:15 -0700 Subject: [PATCH 05/43] Made everything a grid --- .../2026-09-08-oak-cancer-capstone.md | 30 +++++++++++++++---- 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/_posts/capstone/2026-09-08-oak-cancer-capstone.md b/_posts/capstone/2026-09-08-oak-cancer-capstone.md index 01de77fa1f..d52b2dadb0 100644 --- a/_posts/capstone/2026-09-08-oak-cancer-capstone.md +++ b/_posts/capstone/2026-09-08-oak-cancer-capstone.md @@ -8,17 +8,35 @@ permalink: /capstone/oak/ --- -## The Basics and What It Aims to Do +<div class="ocs__grid ocs__grid--standard cols-3" style="margin-bottom: 1.5rem;"> -This capstone project is designed to connect and educate cancer patients and their families through a more engaging, accessible digital experience. Our goal is to create a platform that helps users understand cancer at a biological level through interactive educational modules while also creating opportunities for connection and community through multiplayer games and collaborative experiences. Rather than relying on long text-heavy pages, the project aims to make information easier to navigate, more visually engaging, and more approachable for users of all ages. + <div class="ocs__grid-cell ocs__grid-cell--header">About the Project</div> -## Why We Chose This Project + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>The Basics and What It Aims to Do</strong> + <p>This capstone project is designed to connect and educate cancer patients and their families through a more engaging, accessible digital experience. Our goal is to create a platform that helps users understand cancer at a biological level through interactive educational modules while also creating opportunities for connection and community through multiplayer games and collaborative experiences. Rather than relying on long text-heavy pages, the project aims to make information easier to navigate, more visually engaging, and more approachable for users of all ages.</p> + <a class="ocs__btn alert-green fill small" href="#about-the-project"> + Project Overview + </a> + </div> -We chose this project because we wanted to help children with cancer feel more included, informed, and supported. Many young patients spend significant time in hospitals, at home, or away from school and their peers, which can make them feel isolated. We wanted to build a website that provides both education and connection, giving children a place to learn, play, and engage with others who understand their experiences. We also wanted to create something more interactive and welcoming than a standard informational cancer website. + <div class="ocs__grid-cell"> + <strong>Why We Chose This Project</strong> + <p>We chose this project because we wanted to help children with cancer feel more included, informed, and supported. Many young patients spend significant time in hospitals, at home, or away from school and their peers, which can make them feel isolated. We wanted to build a website that provides both education and connection, giving children a place to learn, play, and engage with others who understand their experiences. We also wanted to create something more interactive and welcoming than a standard informational cancer website.</p> + <a class="ocs__btn alert-yellow fill small" href="#why-we-chose-this-project"> + Why This Project + </a> + </div> -## Our Team + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>Our Team</strong> + <p>Our team consists of Salma, Isha, Aashi, and Emily. Salma serves as our Scrum Master, helping guide project organization, communication, and team coordination. Isha, Aashi, and Emily are our developers and programmers, and together we are responsible for building the website, designing educational content, and creating interactive features that support the project’s goals.</p> + <a class="ocs__btn alert-green fill small" href="#our-team"> + Meet the Team + </a> + </div> -Our team consists of Salma, Isha, Aashi, and Emily. Salma serves as our Scrum Master, helping guide project organization, communication, and team coordination. Isha, Aashi, and Emily are our developers and programmers, and together we are responsible for building the website, designing educational content, and creating interactive features that support the project’s goals. +</div> <div class="ocs__grid ocs__grid--standard cols-3" style="margin-bottom: 1.5rem;"> From beace57cc12d2801112488091361e7d225b055a2 Mon Sep 17 00:00:00 2001 From: Aashihegu <aashihegu1@gmail.com> Date: Mon, 14 Sep 2026 15:49:55 -0700 Subject: [PATCH 06/43] Added more information --- .../2026-09-08-oak-cancer-capstone.md | 249 +++++++++++++----- 1 file changed, 190 insertions(+), 59 deletions(-) diff --git a/_posts/capstone/2026-09-08-oak-cancer-capstone.md b/_posts/capstone/2026-09-08-oak-cancer-capstone.md index d52b2dadb0..53e31f4b93 100644 --- a/_posts/capstone/2026-09-08-oak-cancer-capstone.md +++ b/_posts/capstone/2026-09-08-oak-cancer-capstone.md @@ -4,98 +4,229 @@ microblog: true toc: false layout: post title: Oncology and Kids +description: > + Capstone project creating an interactive and educational website for cancer patients + and families, with community support, learning modules, and games. +categories: [Capstone] permalink: /capstone/oak/ --- -<div class="ocs__grid ocs__grid--standard cols-3" style="margin-bottom: 1.5rem;"> +> **Student capstone · In development.** This project aims to create a more engaging, supportive, and educational digital experience for cancer patients and their families. It is a student-built concept and is not a medical platform or official cancer-care service. - <div class="ocs__grid-cell ocs__grid-cell--header">About the Project</div> +<div class="ocs__grid ocs__grid--standard cols-2"> + <div class="ocs__grid-cell ocs__grid-cell--header">Oncology and Kids · Capstone</div> <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>The Basics and What It Aims to Do</strong> - <p>This capstone project is designed to connect and educate cancer patients and their families through a more engaging, accessible digital experience. Our goal is to create a platform that helps users understand cancer at a biological level through interactive educational modules while also creating opportunities for connection and community through multiplayer games and collaborative experiences. Rather than relying on long text-heavy pages, the project aims to make information easier to navigate, more visually engaging, and more approachable for users of all ages.</p> - <a class="ocs__btn alert-green fill small" href="#about-the-project"> - Project Overview - </a> + <strong>Connecting learning, care, and community</strong> + <p>This capstone project is designed to make cancer education and support more accessible, interactive, and welcoming. The goal is to help patients and families learn about cancer in an easier way while also creating a space for connection, play, and encouragement.</p> + <p><strong>Experience:</strong> learn → connect → explore → play → feel supported</p> </div> <div class="ocs__grid-cell"> - <strong>Why We Chose This Project</strong> - <p>We chose this project because we wanted to help children with cancer feel more included, informed, and supported. Many young patients spend significant time in hospitals, at home, or away from school and their peers, which can make them feel isolated. We wanted to build a website that provides both education and connection, giving children a place to learn, play, and engage with others who understand their experiences. We also wanted to create something more interactive and welcoming than a standard informational cancer website.</p> - <a class="ocs__btn alert-yellow fill small" href="#why-we-chose-this-project"> - Why This Project - </a> + <img src="{{ '/images/capstone/oak.png' | relative_url }}" alt="Oncology and Kids capstone project" loading="lazy"> + <p><strong>Project focus:</strong> educational modules, community support, mood check-ins, interactive games, reading level filters, risk education, and a kid-friendly learning experience.</p> </div> +</div> + +<br> + +<div class="ocs__links ocs__links--wide"> + <a class="ocs__btn ocs__btn--icon alert-green iridescent" href="https://oncologyandkids.org/" target="_blank" rel="noreferrer noopener"> + <span>Official Website</span> + </a> + <a class="ocs__btn ocs__btn--icon alert-yellow iridescent" href="#core-experience"> + <span>Core Experience</span> + </a> +</div> + +<br> + +--- + +## Core experience + +> Four connected parts of the user journey, from learning about cancer to feeling supported and included in a community. + +<div class="ocs__grid ocs__grid--card"> + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>01 · Learn in a simpler way</strong> + <p>Provide accessible learning modules that explain cancer in a more understandable and age-appropriate way through interactive content.</p> + </div> + + <div class="ocs__grid-cell"> + <strong>02 · Connect with others</strong> + <p>Create a supportive space where children, families, and patients can engage with a community and find encouragement through shared experiences.</p> + </div> + + <div class="ocs__grid-cell"> + <strong>03 · Play and explore</strong> + <p>Include games and interactive activities that make the experience more engaging, uplifting, and enjoyable for users of all ages.</p> + </div> + + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>04 · Feel informed and supported</strong> + <p>Use tools like reading level filters, check-ins, and educational activities to help users understand what they are experiencing with less stress and more confidence.</p> + </div> +</div> + +<br> + +--- + +## From problem to product direction + +<div class="ocs__grid ocs__grid--standard cols-2"> + <div class="ocs__grid-cell ocs__grid-cell--header">Why we are building it</div> <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>Our Team</strong> - <p>Our team consists of Salma, Isha, Aashi, and Emily. Salma serves as our Scrum Master, helping guide project organization, communication, and team coordination. Isha, Aashi, and Emily are our developers and programmers, and together we are responsible for building the website, designing educational content, and creating interactive features that support the project’s goals.</p> - <a class="ocs__btn alert-green fill small" href="#our-team"> - Meet the Team - </a> + <strong>Current challenge</strong> + <p>Many cancer resources are difficult to navigate, overly text-heavy, or not designed to feel welcoming for younger patients. Kids with cancer often need a space that is both informative and emotionally supportive.</p> </div> + <div class="ocs__grid-cell"> + <strong>Project direction</strong> + <p>Build a more engaging and inclusive website that combines education, community support, and interactive play in a way that feels friendly, understandable, and empowering.</p> + </div> </div> -<div class="ocs__grid ocs__grid--standard cols-3" style="margin-bottom: 1.5rem;"> +<br> + +--- - <div class="ocs__grid-cell ocs__grid-cell--header">Core Features</div> +## Core features - <div class="ocs__grid-cell ocs__grid-cell--accent" id="community-support"> - <strong>Community Support</strong> +<div class="ocs__grid ocs__grid--card"> + <div class="ocs__grid-cell"> + <strong>Community support</strong> <p>Create a welcoming space for kids and families to feel connected, supported, and less isolated while navigating cancer treatment and recovery.</p> - <a class="ocs__btn alert-green fill small" href="#community-support"> - Community Support - </a> </div> - <div class="ocs__grid-cell" id="daily-check-in"> - <strong>Daily Check-In</strong> + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>Daily check-in</strong> <p>Offer a simple daily mood check-in so users can share how they are feeling and connect with others in a supportive, low-pressure way.</p> - <a class="ocs__btn alert-yellow fill small" href="#daily-check-in"> - Daily Check-In - </a> </div> - <div class="ocs__grid-cell ocs__grid-cell--accent" id="interactive-games"> - <strong>Interactive Games</strong> - <p>Include fun learning-based games such as puzzles and memory activities to keep the experience engaging, uplifting, and interactive.</p> - <a class="ocs__btn alert-green fill small" href="#interactive-games"> - Interactive Games - </a> + <div class="ocs__grid-cell"> + <strong>Interactive games</strong> + <p>Include puzzles, memory activities, and playful educational tools that make the experience more enjoyable and interactive.</p> + </div> + + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>Reading level filters</strong> + <p>Organize information by age or reading level so kids, teens, and parents can access content that is easier to understand.</p> </div> - <div class="ocs__grid-cell" id="reading-levels"> - <strong>Reading Level Filters</strong> - <p>Sort educational content by reading level so children, teens, and parents can access information that feels understandable and age-appropriate.</p> - <a class="ocs__btn alert-yellow fill small" href="#reading-levels"> - Reading Level Filters - </a> + <div class="ocs__grid-cell"> + <strong>Risk calculator</strong> + <p>Provide educational guidance through a risk-informed feature that helps users explore relevant health information in a clearer way.</p> </div> - <div class="ocs__grid-cell ocs__grid-cell--accent" id="risk-calculator"> - <strong>Risk Calculator</strong> - <p>Build an educational risk tool that helps users explore health information in a guided and accessible way while encouraging learning.</p> - <a class="ocs__btn alert-green fill small" href="#risk-calculator"> - Risk Calculator - </a> + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>Cell lab</strong> + <p>Refresh the past cell lab concept into a more accessible, interactive learning experience that explains cancer science in a simpler format.</p> </div> - <div class="ocs__grid-cell" id="cell-lab"> - <strong>Cell Lab</strong> - <p>Refresh the old cell lab into a clearer, more engaging learning experience that helps users understand cancer-related science in a simpler way.</p> - <a class="ocs__btn alert-yellow fill small" href="#cell-lab"> - Cell Lab - </a> + <div class="ocs__grid-cell"> + <strong>Body map</strong> + <p>Create a kid-friendly body map tool that helps users better understand cancer-related health information through interaction and visual learning.</p> </div> +</div> + +<br> - <div class="ocs__grid-cell ocs__grid-cell--accent" id="body-map"> - <strong>Body Map</strong> - <p>Create a kid-friendly body map tool that makes complex health concepts easier to explore and understand through interaction.</p> - <a class="ocs__btn alert-green fill small" href="#body-map"> - Body Map - </a> +--- + +## System flow + +> The project is designed as a connected experience where educational content, community features, and interactive tools work together. + +<div class="ocs__grid ocs__grid--standard cols-4"> + <div class="ocs__grid-cell ocs__grid-cell--header">One connected support and learning workflow</div> + + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>1 · User interface</strong> + <p>Visitors access educational modules, games, check-ins, and support features through a welcoming and easy-to-navigate website.</p> </div> + <div class="ocs__grid-cell"> + <strong>2 · User actions</strong> + <p>Users explore information, interact with content, participate in activities, and connect with a community designed around support and understanding.</p> + </div> + + <div class="ocs__grid-cell"> + <strong>3 · Content and tools</strong> + <p>Educational content, risk-related guidance, and interactive features help make cancer information more helpful and approachable.</p> + </div> + + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>4 · Community value</strong> + <p>Users leave with more knowledge, stronger support, and a more engaging experience that encourages learning and connection.</p> + </div> +</div> + +<br> + +--- + +## Technical foundation + +<div class="ocs__grid ocs__grid--card"> + <div class="ocs__grid-cell"> + <strong>Frontend</strong> + <p>Jekyll, HTML, JavaScript, and accessible web design for a child-friendly learning and support platform.</p> + </div> + + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>Backend</strong> + <p>Python Flask services can support data-backed information, user interactions, and future community or educational workflows.</p> + </div> + + <div class="ocs__grid-cell"> + <strong>Content</strong> + <p>Educational modules, reading-level filters, and interactive learning features are designed to make complex information easier to understand.</p> + </div> + + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>Project goal</strong> + <p>Turn the strongest ideas from earlier work into a clear, maintainable product direction focused on inclusion, education, and support.</p> + </div> +</div> + +<br> + +--- + +## Our team + +> The project brings together a small team focused on building a supportive and engaging educational platform. + +<div class="ocs__grid ocs__grid--standard cols-2"> + <div class="ocs__grid-cell ocs__grid-cell--header">Current project team</div> + + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>Salma</strong> + <p>Scrum Master</p> + </div> + + <div class="ocs__grid-cell"> + <strong>Isha</strong> + <p>Developer</p> + </div> + + <div class="ocs__grid-cell"> + <strong>Aashi</strong> + <p>Developer</p> + </div> + + <div class="ocs__grid-cell ocs__grid-cell--accent"> + <strong>Emily</strong> + <p>Developer</p> + </div> +</div> + +<br> + +<div class="ocs__links ocs__links--wide"> + <a class="ocs__btn large alert-green iridescent" href="https://oncologyandkids.org/" target="_blank" rel="noreferrer noopener">Official Website</a> </div> From 3c1c4f4ef40a31beea826d77302a350b2214fe90 Mon Sep 17 00:00:00 2001 From: Aashihegu <aashihegu1@gmail.com> Date: Mon, 14 Sep 2026 16:04:01 -0700 Subject: [PATCH 07/43] Changed frontend/backend buttons and image size --- .../2026-09-08-oak-cancer-capstone.md | 44 +++---------------- 1 file changed, 5 insertions(+), 39 deletions(-) diff --git a/_posts/capstone/2026-09-08-oak-cancer-capstone.md b/_posts/capstone/2026-09-08-oak-cancer-capstone.md index 53e31f4b93..5fc9069b66 100644 --- a/_posts/capstone/2026-09-08-oak-cancer-capstone.md +++ b/_posts/capstone/2026-09-08-oak-cancer-capstone.md @@ -24,7 +24,7 @@ permalink: /capstone/oak/ </div> <div class="ocs__grid-cell"> - <img src="{{ '/images/capstone/oak.png' | relative_url }}" alt="Oncology and Kids capstone project" loading="lazy"> + <img src="{{ '/images/capstone/oak.png' | relative_url }}" alt="Oncology and Kids capstone project" loading="lazy" style="max-width: 220px; width: 100%; height: auto; display: block; margin: 0 auto;"> <p><strong>Project focus:</strong> educational modules, community support, mood check-ins, interactive games, reading level filters, risk education, and a kid-friendly learning experience.</p> </div> </div> @@ -32,11 +32,11 @@ permalink: /capstone/oak/ <br> <div class="ocs__links ocs__links--wide"> - <a class="ocs__btn ocs__btn--icon alert-green iridescent" href="https://oncologyandkids.org/" target="_blank" rel="noreferrer noopener"> - <span>Official Website</span> + <a class="ocs__btn ocs__btn--icon alert-green iridescent" href="https://github.com/undergroundrapclub/oak_spring" target="_blank" rel="noreferrer noopener"> + <span>Backend Repository</span> </a> - <a class="ocs__btn ocs__btn--icon alert-yellow iridescent" href="#core-experience"> - <span>Core Experience</span> + <a class="ocs__btn ocs__btn--icon alert-yellow iridescent" href="https://oncologyandkids.org/" target="_blank" rel="noreferrer noopener"> + <span>Frontend</span> </a> </div> @@ -44,36 +44,6 @@ permalink: /capstone/oak/ --- -## Core experience - -> Four connected parts of the user journey, from learning about cancer to feeling supported and included in a community. - -<div class="ocs__grid ocs__grid--card"> - <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>01 · Learn in a simpler way</strong> - <p>Provide accessible learning modules that explain cancer in a more understandable and age-appropriate way through interactive content.</p> - </div> - - <div class="ocs__grid-cell"> - <strong>02 · Connect with others</strong> - <p>Create a supportive space where children, families, and patients can engage with a community and find encouragement through shared experiences.</p> - </div> - - <div class="ocs__grid-cell"> - <strong>03 · Play and explore</strong> - <p>Include games and interactive activities that make the experience more engaging, uplifting, and enjoyable for users of all ages.</p> - </div> - - <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>04 · Feel informed and supported</strong> - <p>Use tools like reading level filters, check-ins, and educational activities to help users understand what they are experiencing with less stress and more confidence.</p> - </div> -</div> - -<br> - ---- - ## From problem to product direction <div class="ocs__grid ocs__grid--standard cols-2"> @@ -226,7 +196,3 @@ permalink: /capstone/oak/ </div> <br> - -<div class="ocs__links ocs__links--wide"> - <a class="ocs__btn large alert-green iridescent" href="https://oncologyandkids.org/" target="_blank" rel="noreferrer noopener">Official Website</a> -</div> From fe4cc0833433b4abbfecb6e6ed52314765b09e4e Mon Sep 17 00:00:00 2001 From: AVG11235 <mateodurand11235@gmail.com> Date: Tue, 15 Sep 2026 14:11:16 -0700 Subject: [PATCH 08/43] typography lesson --- .../lessons/sass/navigation/typography.md | 117 +++++++----------- 1 file changed, 45 insertions(+), 72 deletions(-) diff --git a/_projects/lessons/sass/navigation/typography.md b/_projects/lessons/sass/navigation/typography.md index eddf570789..7ceea2cce7 100644 --- a/_projects/lessons/sass/navigation/typography.md +++ b/_projects/lessons/sass/navigation/typography.md @@ -2,15 +2,13 @@ layout: post title: SASS Typpography Aesthetihawk categories: [SASS] -lesson_topic: Typpography -lesson_part: interactive -lesson_type: lesson -microblog: true +permalink: /aesthetihawk-guide-typography author: Aashray Reddy -permalink: /sass/typography +menu: nav/aesthetihawk-guide.html +toc: false --- -## Typography (refactor for opencoding) +## Typography ### How to Use @@ -19,85 +17,60 @@ Our site uses **semantic HTML tags** to control text styling. Instead of applyin **✅ Correct usage:** ```html -<h1>Main Heading</h1> -<h2>Section Title</h2> -<p>This is a paragraph of text explaining something.</p> +<!-- Don't use bold or italics classes. Use semantic meaning. --> +<p>You <strong>must</strong> commit your code daily.</p> +<p>It is <em>highly recommended</em> to leave comments.</p> ``` -**❌ Avoid:** - +**3. Complex: Full Section Structure** ```html -<p class="big bold">Main Heading</p> <!-- Don't do this --> +<!-- Grouping content properly using hierarchy --> +<h2>Setup Instructions</h2> +<h3>Prerequisites</h3> +<ul> + <li>Python 3.9+</li> + <li>VS Code</li> +</ul> +<h3>Installation Steps</h3> +<ol> + <li>Clone the repo.</li> + <li>Run the setup script.</li> +</ol> ``` --- -### Supported Tags & Visual Hierarchy +## 3. Hacks & Practice Tasks -| Tag | Purpose | Usage Example | -|---------|------------------------------------|--------------------------------------| -| `<h1>` | Page title | Used once per page (top-level heading) | -| `<h2>` | Section titles | Major sections within a page | -| `<h3>` | Sub-sections or card headers | Grouping inside `<h2>` sections | -| `<h4>` | Minor headings | Optional for smaller sub-sections | -| `<p>` | Paragraphs and body content | Default for most content text | -| `<strong>` | Emphasis or importance | Highlights key words/phrases | -| `<em>` | Subtle emphasis or tone shift | Used for soft emphasis (like italics)| -| `<ul>`, `<ol>`, `<li>` | Lists | Use for bullets or ordered items | - ---- +### Popcorn Hack (In-Class) +**Task:** Look at the bad code below. Drop the corrected, semantic version of this code in the chat within 2 minutes. +```html +<div class="huge-text">Welcome!</div> +<span class="sub-title">Read this</span> +<div class="normal">This is a sentence.</div> +``` -### When to Use What +### Homework Hack +**Task:** Refactor the following code block. Remove all the inline styles and custom classes, and replace them with the correct semantic HTML tags (`h1`-`h4`, `p`, `ul`/`ol`/`li`, `strong`, `em`) so it uses our Aesthetihawk SASS theme. Submit the clean HTML code to our issue tracker. -- Use **`<h1>`** for the main page heading. There should only be **one** per page. -- Use **`<h2>`** for top-level sections like "Features", "Pricing", or "FAQ". -- Use **`<p>`** for all standard body text. -- Use **`<h3>` and below** when you need to break down content within a section. -- Use **`<strong>`** instead of manually bolding words. -- Use **semantic HTML** so assistive tech and search engines understand your content structure. +```html +<p class="title-font">Project Features</p> +<p class="section-font">User Accounts</p> +<p class="body-text">Users can make an account and log in. This is a <span class="very-important">crucial</span> feature.</p> +<p class="body-text">Steps to register:</p> +<p class="list-item">1. Click register</p> +<p class="list-item">2. Enter email</p> +<p class="list-item">3. Set password</p> +``` --- -### Accessibility & SEO Benefits - -- Semantic tags improve screen reader experiences. -- Headings create a logical outline of the page for users and search engines. -- Default styles ensure your typography scales responsively across devices. +## 4. Grading Plan (1 Point Total) +* **0.2 points:** Participated in the Popcorn Hack with a reasonable attempt. +* **0.8 points:** Homework Hack is submitted and correctly uses semantic tags instead of classes (0.4 for correct heading hierarchy, 0.4 for converting the fake list into a real `<ol>`). --- -### Recap - -✅ Use semantic tags -❌ Don’t style text manually -🎯 Let the system handle the look — you just focus on structure. - -## Examples - -<h1>Top-level heading</h1> - -<h2>Section title or sub-Level heading. Use for major sections.</h2> - -<h3>Third-level heading. Use for sub-sections within a section.</h3> - -<h4>Minor heading. Use for small headings.</h4> - -<p>Normal text. Use for all body text, explanations, or descriptions.</p> - -<p>This is <strong>important</strong> text. Use it to emphasize key words or actions.</p> - -<p>This is <em>somewhat important</em> text. Use for soft emphasis, tone shifts, or alternate voice.</p> - - -<ul> - <li>Unorder lists don't have numbers</li> - <li>Good for bullet notes</li> - <li>Good if order isn't important</li> -</ul> - - -<ol> - <li>Ordered lists have numbers</li> - <li>Good for steps</li> - <li>Good if order is important (chronological)</li> -</ol> \ No newline at end of file +## 5. Lesson Revisions & Feedback Evidence +* **Feedback Received:** During my peer practice run, my teammate pointed out that my original Popcorn Hack asked them to write a whole HTML page from scratch, which took longer than 5 minutes and killed the lesson's momentum. +* **Revision Made:** I changed the Popcorn Hack to a simple 3-line refactor that they can do directly in the chat window. This keeps engagement high and takes under 2 minutes. From 5d493f53dbf8b399156415c8c6254bb007e97476 Mon Sep 17 00:00:00 2001 From: AVG11235 <mateodurand11235@gmail.com> Date: Tue, 15 Sep 2026 14:16:57 -0700 Subject: [PATCH 09/43] Typography lesson update for work --- .../sass/navigation/9-15-2026-typography.md | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 _projects/lessons/sass/navigation/9-15-2026-typography.md diff --git a/_projects/lessons/sass/navigation/9-15-2026-typography.md b/_projects/lessons/sass/navigation/9-15-2026-typography.md new file mode 100644 index 0000000000..78425d29a3 --- /dev/null +++ b/_projects/lessons/sass/navigation/9-15-2026-typography.md @@ -0,0 +1,126 @@ +--- +layout: post +title: Aesthetihawk Guide - Typography +categories: [SASS] +permalink: /aesthetihawk-guide-typography +author: Tristan Chiu, Mateo Durand Amador, Barbara Zhao +menu: nav/aesthetihawk-guide.html +toc: false +--- + +# Sprint Lesson: SASS Typography & Semantic HTML + +## 1. LxD Cycle Process + +**Empathize:** I noticed a lot of students try to manually style text using custom classes (like `<p class="big-bold">Main Heading</p>`) instead of letting the global SASS theme handle it through proper HTML structure. This breaks our site's visual consistency and messes up accessibility. + +**Define:** +* **POV:** CSP students need a way to build web pages using semantic HTML because relying on manual CSS classes creates messy code and inaccessible design. +* **Learning Goal:** Students will understand how to use global SASS typography styling by applying the correct semantic HTML tags (`<h1>`, `<h2>`, `<p>`, `<strong>`, etc.) instead of custom classes. + +**Ideate:** +* **HMW Question:** How might we teach students to trust global SASS styles and stop hardcoding text appearance? +* **Activity:** Refactoring a poorly written HTML snippet into clean, semantic HTML that automatically inherits our SASS theme. + +**Prototype & Test:** I taught a trial run to my project team. They felt the original homework was too long, so I revised it to be a single, focused refactoring task (documented below). + +--- + +## 2. Lesson Plan + +**Learning Objective:** By the end of this lesson, you will be able to structure text using semantic HTML tags so it automatically inherits our global SASS typography styles without using custom classes. + +**Success Criteria:** You can take an unformatted block of text, apply the correct headings, paragraphs, and list tags, and have it match our site's design system perfectly. + +### Tech Talk (3 minutes) +We are using a global SASS typography system. This means **you don't need to write CSS for your text**. Instead of styling text to look a certain way, you just need to tell the browser *what* the text is. There’s already a global system to take care of the styling. + +* **The Rule:** Use semantic HTML tags. Let the system handle the look. +* ✅ **Do this:** `<h1>Main Heading</h1>` or `<strong>Important</strong>` +* ❌ **Don't do this:** `<div class="title-text">Main Heading</div>` or `<p class="bold">Important</p>` + +Why do we do this? It ensures our whole project looks consistent, makes our code cleaner, and is essential for screen readers and SEO. + +### Supported Tags Reference Guide + +Before we jump into the examples, here is a quick cheat sheet of the tags we use to build our visual hierarchy. + +| Tag | Purpose | Usage Example | +| :--- | :--- | :--- | +| `<h1>` | Page title | Used once per page (top-level heading) | +| `<h2>` | Section titles | Major sections within a page | +| `<h3>` | Sub-sections or card headers | Grouping inside `<h2>` sections | +| `<h4>` | Minor headings | Optional for smaller sub-sections | +| `<p>` | Paragraphs and body content | Default for most content text | +| `<strong>` | Emphasis or importance | Highlights key words/phrases | +| `<em>` | Subtle emphasis or tone shift | Used for soft emphasis (like italics) | +| `<ul>`, `<ol>`, `<li>` | Lists | Use for bullets or ordered items | + +### Code Examples + +**1. Simple: Basic Headings and Paragraphs** +```html +<!-- We use h1 for the single page title, h2 for major sections, and p for body text. --> +<h1>About Our Project</h1> +<h2>The Team</h2> +<p>We are a group of CSP students building a cool web app.</p> + +**2. Intermediate: Adding Emphasis** +```html +<!-- Don't use bold or italics classes. Use semantic meaning. --> +<p>You <strong>must</strong> commit your code daily.</p> +<p>It is <em>highly recommended</em> to leave comments.</p> +``` + +**3. Complex: Full Section Structure** +```html +<!-- Grouping content properly using hierarchy --> +<h2>Setup Instructions</h2> +<h3>Prerequisites</h3> +<ul> + <li>Python 3.9+</li> + <li>VS Code</li> +</ul> +<h3>Installation Steps</h3> +<ol> + <li>Clone the repo.</li> + <li>Run the setup script.</li> +</ol> +``` + +--- + +## 3. Hacks & Practice Tasks + +### Popcorn Hack (In-Class) +**Task:** Look at the bad code below. Drop the corrected, semantic version of this code in the chat within 2 minutes. +```html +<div class="huge-text">Welcome!</div> +<span class="sub-title">Read this</span> +<div class="normal">This is a sentence.</div> +``` + +### Homework Hack +**Task:** Refactor the following code block. Remove all the inline styles and custom classes, and replace them with the correct semantic HTML tags (`h1`-`h4`, `p`, `ul`/`ol`/`li`, `strong`, `em`) so it uses our Aesthetihawk SASS theme. Submit the clean HTML code to our issue tracker. + +```html +<p class="title-font">Project Features</p> +<p class="section-font">User Accounts</p> +<p class="body-text">Users can make an account and log in. This is a <span class="very-important">crucial</span> feature.</p> +<p class="body-text">Steps to register:</p> +<p class="list-item">1. Click register</p> +<p class="list-item">2. Enter email</p> +<p class="list-item">3. Set password</p> +``` + +--- + +## 4. Grading Plan (1 Point Total) +* **0.2 points:** Participated in the Popcorn Hack with a reasonable attempt. +* **0.8 points:** Homework Hack is submitted and correctly uses semantic tags instead of classes (0.4 for correct heading hierarchy, 0.4 for converting the fake list into a real `<ol>`). + +--- + +## 5. Lesson Revisions & Feedback Evidence +* **Feedback Received:** During my peer practice run, my teammate pointed out that my original Popcorn Hack asked them to write a whole HTML page from scratch, which took longer than 5 minutes and killed the lesson's momentum. +* **Revision Made:** I changed the Popcorn Hack to a simple 3-line refactor that they can do directly in the chat window. This keeps engagement high and takes under 2 minutes. From 3e456ed777070c25fe4f694daac599d0266d47fa Mon Sep 17 00:00:00 2001 From: AVG11235 <mateodurand11235@gmail.com> Date: Tue, 15 Sep 2026 14:17:27 -0700 Subject: [PATCH 10/43] deltion of old typography lesson work update --- .../lessons/sass/navigation/typography.md | 76 ------------------- 1 file changed, 76 deletions(-) delete mode 100644 _projects/lessons/sass/navigation/typography.md diff --git a/_projects/lessons/sass/navigation/typography.md b/_projects/lessons/sass/navigation/typography.md deleted file mode 100644 index 7ceea2cce7..0000000000 --- a/_projects/lessons/sass/navigation/typography.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -layout: post -title: SASS Typpography Aesthetihawk -categories: [SASS] -permalink: /aesthetihawk-guide-typography -author: Aashray Reddy -menu: nav/aesthetihawk-guide.html -toc: false ---- - -## Typography - -### How to Use - -Our site uses **semantic HTML tags** to control text styling. Instead of applying custom classes, developers should use the appropriate tags like `<h1>`, `<h2>`, and `<p>`. These tags are automatically styled through our global styles to ensure visual consistency, accessibility, and responsive behavior. - -**✅ Correct usage:** - -```html -<!-- Don't use bold or italics classes. Use semantic meaning. --> -<p>You <strong>must</strong> commit your code daily.</p> -<p>It is <em>highly recommended</em> to leave comments.</p> -``` - -**3. Complex: Full Section Structure** -```html -<!-- Grouping content properly using hierarchy --> -<h2>Setup Instructions</h2> -<h3>Prerequisites</h3> -<ul> - <li>Python 3.9+</li> - <li>VS Code</li> -</ul> -<h3>Installation Steps</h3> -<ol> - <li>Clone the repo.</li> - <li>Run the setup script.</li> -</ol> -``` - ---- - -## 3. Hacks & Practice Tasks - -### Popcorn Hack (In-Class) -**Task:** Look at the bad code below. Drop the corrected, semantic version of this code in the chat within 2 minutes. -```html -<div class="huge-text">Welcome!</div> -<span class="sub-title">Read this</span> -<div class="normal">This is a sentence.</div> -``` - -### Homework Hack -**Task:** Refactor the following code block. Remove all the inline styles and custom classes, and replace them with the correct semantic HTML tags (`h1`-`h4`, `p`, `ul`/`ol`/`li`, `strong`, `em`) so it uses our Aesthetihawk SASS theme. Submit the clean HTML code to our issue tracker. - -```html -<p class="title-font">Project Features</p> -<p class="section-font">User Accounts</p> -<p class="body-text">Users can make an account and log in. This is a <span class="very-important">crucial</span> feature.</p> -<p class="body-text">Steps to register:</p> -<p class="list-item">1. Click register</p> -<p class="list-item">2. Enter email</p> -<p class="list-item">3. Set password</p> -``` - ---- - -## 4. Grading Plan (1 Point Total) -* **0.2 points:** Participated in the Popcorn Hack with a reasonable attempt. -* **0.8 points:** Homework Hack is submitted and correctly uses semantic tags instead of classes (0.4 for correct heading hierarchy, 0.4 for converting the fake list into a real `<ol>`). - ---- - -## 5. Lesson Revisions & Feedback Evidence -* **Feedback Received:** During my peer practice run, my teammate pointed out that my original Popcorn Hack asked them to write a whole HTML page from scratch, which took longer than 5 minutes and killed the lesson's momentum. -* **Revision Made:** I changed the Popcorn Hack to a simple 3-line refactor that they can do directly in the chat window. This keeps engagement high and takes under 2 minutes. From ad641fa2f48cb98de86cad7c12517ef5cf59e490 Mon Sep 17 00:00:00 2001 From: jm1021 <jmort1021@gmail.com> Date: Tue, 15 Sep 2026 21:22:28 -0700 Subject: [PATCH 11/43] Update some topgraph files. --- .../elements/typography/_main.scss | 7 +++-- .../elements/typography/colors.scss | 18 +++++-------- _sass/open-coding/materials/glow.scss | 27 +++++++------------ 3 files changed, 22 insertions(+), 30 deletions(-) diff --git a/_sass/open-coding/elements/typography/_main.scss b/_sass/open-coding/elements/typography/_main.scss index 5a6fec2e5d..375be80e00 100644 --- a/_sass/open-coding/elements/typography/_main.scss +++ b/_sass/open-coding/elements/typography/_main.scss @@ -3,6 +3,9 @@ @import "sizes.scss"; body { - font-family: Verdana, sans-serif !important; + font-family: var( + --pref-font-family, + Verdana, + sans-serif + ); } - diff --git a/_sass/open-coding/elements/typography/colors.scss b/_sass/open-coding/elements/typography/colors.scss index 75afab837b..a59cfb287f 100644 --- a/_sass/open-coding/elements/typography/colors.scss +++ b/_sass/open-coding/elements/typography/colors.scss @@ -1,21 +1,17 @@ @import "../../materials/main.scss"; h1, h2, h3, h4 { - color: $white1 !important; + color: var(--pref-text-color, $white1); } -p { - color: $white3 !important; +p, li, ul, ol { + color: var(--text-muted, var(--pref-text-color, $white3)); } a { - color: $lightBlue1 !important; + color: var(--pref-accent-color, $lightBlue1); - &:hover { - color: $white2 !important; - } -} - -li, ul, ol { - color: $white3 !important; + &:hover { + color: var(--pref-text-color, $white2); + } } \ No newline at end of file diff --git a/_sass/open-coding/materials/glow.scss b/_sass/open-coding/materials/glow.scss index 7e465744e7..662455b9a4 100644 --- a/_sass/open-coding/materials/glow.scss +++ b/_sass/open-coding/materials/glow.scss @@ -16,16 +16,12 @@ } &:before { - background: linear-gradient(45deg, #ff0000, #ff7300, #fffb00, #48ff00, #00ffd5, #002bff, #7a00ff, #ff00c8, #ff0000); - background-size: 400%; - filter: blur(5px); - width: calc(100% + 4px); - height: calc(100% + 4px); - top: -2px; - left: -2px; - opacity: 0; - transition: opacity .3s ease-in-out; - animation: glowing 20s linear infinite; + background: linear-gradient( + 45deg, + color-mix(in srgb, var(--pref-accent-color, $lightBlue1) 65%, #ff4d6d), + var(--pref-accent-color, $lightBlue1), + color-mix(in srgb, var(--pref-accent-color, $lightBlue1) 65%, #7c3aed) + ); } &:hover:before { @@ -33,17 +29,14 @@ } &:after { - background: #1e1e1e; + background: var(--panel, $gray6); } } .glowOnHover { - @extend .glow; - border: none; - outline: none; - color: #fff; - background: #1e1e1e; - border-radius: $border-size; + @extend .glow; + color: var(--pref-text-color, $white1); + background: var(--panel, $gray6); } // animation key frames From 4ab489a6b0554ce2ffb8a5b3b3a8800c668e478a Mon Sep 17 00:00:00 2001 From: jm1021 <jmort1021@gmail.com> Date: Tue, 15 Sep 2026 21:38:00 -0700 Subject: [PATCH 12/43] rename code formatter --- _sass/open-coding/_main.scss | 2 +- _sass/open-coding/base/{_typography.scss => _code.scss} | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) rename _sass/open-coding/base/{_typography.scss => _code.scss} (95%) diff --git a/_sass/open-coding/_main.scss b/_sass/open-coding/_main.scss index 4943b1939d..73d8e86c34 100644 --- a/_sass/open-coding/_main.scss +++ b/_sass/open-coding/_main.scss @@ -1,6 +1,6 @@ @import "theme/legacy/root-color-map"; @import "mixins/variables"; -@import "base/typography"; +@import "base/code"; @import "bathroom"; @import "blogs"; @import "projects/all"; // Auto-generated project imports diff --git a/_sass/open-coding/base/_typography.scss b/_sass/open-coding/base/_code.scss similarity index 95% rename from _sass/open-coding/base/_typography.scss rename to _sass/open-coding/base/_code.scss index 6ecd23ec62..956abf26da 100644 --- a/_sass/open-coding/base/_typography.scss +++ b/_sass/open-coding/base/_code.scss @@ -1,5 +1,5 @@ /** - * Base Typography Styles + * Base code formatting * Override default code and text formatting with user preferences */ @@ -16,7 +16,7 @@ pre { padding: 1rem; border: 1px solid var(--ui-border); overflow-x: auto; - + code { background-color: transparent !important; padding: 0; @@ -29,4 +29,4 @@ li code, td code { background-color: var(--panel) !important; color: var(--pref-text-color) !important; -} +} \ No newline at end of file From 127fee68e123c911140feec025d16ba0a5a7091c Mon Sep 17 00:00:00 2001 From: jm1021 <jmort1021@gmail.com> Date: Tue, 15 Sep 2026 22:41:34 -0700 Subject: [PATCH 13/43] edit student lesson --- ...{9-15-2026-typography.md => typography.md} | 106 +++++++++++++----- 1 file changed, 76 insertions(+), 30 deletions(-) rename _projects/lessons/sass/navigation/{9-15-2026-typography.md => typography.md} (66%) diff --git a/_projects/lessons/sass/navigation/9-15-2026-typography.md b/_projects/lessons/sass/navigation/typography.md similarity index 66% rename from _projects/lessons/sass/navigation/9-15-2026-typography.md rename to _projects/lessons/sass/navigation/typography.md index 78425d29a3..641017e0b4 100644 --- a/_projects/lessons/sass/navigation/9-15-2026-typography.md +++ b/_projects/lessons/sass/navigation/typography.md @@ -1,25 +1,74 @@ --- layout: post -title: Aesthetihawk Guide - Typography -categories: [SASS] -permalink: /aesthetihawk-guide-typography +title: OCS Semantic HTML & Typography Grammar +categories: [SASS, Typography] +lesson_language: SASS +lesson_topic: Typography +lesson_part: interactive +lesson_type: lesson +permalink: /sass/typography author: Tristan Chiu, Mateo Durand Amador, Barbara Zhao -menu: nav/aesthetihawk-guide.html -toc: false --- -# Sprint Lesson: SASS Typography & Semantic HTML +## The Core Rule + +Use HTML for meaning and OCS classes for reusable layout or component roles. This example shows how an OCS class gives a paragraph a defined role. + +```html +<h1>OCS Typography Reference</h1> +<p class="ocs__lead">Use semantic HTML and OCS classes to structure your page.</p> + +<ol> + <li>Choose HTML elements for meaning.</li> + <li>Use OCS classes for reusable visual roles.</li> +</ol> +``` + +### Semantic HTML + +Use meaningful HTML elements to structure content clearly and accessibly. + +| Element | Meaning | OCS usage | +| --- | --- | --- | +| `<h1>` | Page-level heading | Use for the page's primary title. The frontmatter title is the only h1 in Markdown or notebook content. | +| `<h2>` | Major section heading | Use for main sections | +| `<h3>` | Subsection heading | Use inside an `<h2>` section or card | +| `<p>` | Paragraph | Use for normal body text | +| `<strong>` | Important content | Use when the meaning is important, not just when text should look bold | +| `<em>` | Stressed content | Use when emphasis changes the meaning or tone | +| `<ul>` | Unordered list | Use when item order does not matter | +| `<ol>` | Ordered list | Use for steps, rankings, or sequences | +| `<li>` | List item | Must be inside `<ul>` or `<ol>` | + +### OCS Typography Grammar + +Use OCS classes to express roles without hardcoded visual styling. + +| Rule | Use | +| --- | --- | +| `ocs__description` | Introductory or supporting description text | +| `ocs__text` | Standard body text inside an OCS component | +| `ocs__lead` | Larger introductory paragraph | +| `ocs__section-title` | Section or card heading | +| `ocs__badge` | Small contextual label | +| `ocs__status` | State or status indicator | +| `ocs__card` | Framed content panel | +| `ocs__visual` | Supporting visual or fact panel | + +--- ## 1. LxD Cycle Process **Empathize:** I noticed a lot of students try to manually style text using custom classes (like `<p class="big-bold">Main Heading</p>`) instead of letting the global SASS theme handle it through proper HTML structure. This breaks our site's visual consistency and messes up accessibility. -**Define:** +**Define:** + * **POV:** CSP students need a way to build web pages using semantic HTML because relying on manual CSS classes creates messy code and inaccessible design. * **Learning Goal:** Students will understand how to use global SASS typography styling by applying the correct semantic HTML tags (`<h1>`, `<h2>`, `<p>`, `<strong>`, etc.) instead of custom classes. -**Ideate:** -* **HMW Question:** How might we teach students to trust global SASS styles and stop hardcoding text appearance? +**Ideate:** + +* **HMW Question:** How might we teach students to trust global SASS styles and stop hardcoding text appearance? * **Activity:** Refactoring a poorly written HTML snippet into clean, semantic HTML that automatically inherits our SASS theme. **Prototype & Test:** I taught a trial run to my project team. They felt the original homework was too long, so I revised it to be a single, focused refactoring task (documented below). @@ -28,11 +77,12 @@ toc: false ## 2. Lesson Plan -**Learning Objective:** By the end of this lesson, you will be able to structure text using semantic HTML tags so it automatically inherits our global SASS typography styles without using custom classes. +**Learning Objective:** By the end of this lesson, you will be able to structure text using semantic HTML tags so it automatically inherits our global SASS typography styles without using custom classes. **Success Criteria:** You can take an unformatted block of text, apply the correct headings, paragraphs, and list tags, and have it match our site's design system perfectly. ### Tech Talk (3 minutes) + We are using a global SASS typography system. This means **you don't need to write CSS for your text**. Instead of styling text to look a certain way, you just need to tell the browser *what* the text is. There’s already a global system to take care of the styling. * **The Rule:** Use semantic HTML tags. Let the system handle the look. @@ -41,38 +91,27 @@ We are using a global SASS typography system. This means **you don't need to wri Why do we do this? It ensures our whole project looks consistent, makes our code cleaner, and is essential for screen readers and SEO. -### Supported Tags Reference Guide - -Before we jump into the examples, here is a quick cheat sheet of the tags we use to build our visual hierarchy. - -| Tag | Purpose | Usage Example | -| :--- | :--- | :--- | -| `<h1>` | Page title | Used once per page (top-level heading) | -| `<h2>` | Section titles | Major sections within a page | -| `<h3>` | Sub-sections or card headers | Grouping inside `<h2>` sections | -| `<h4>` | Minor headings | Optional for smaller sub-sections | -| `<p>` | Paragraphs and body content | Default for most content text | -| `<strong>` | Emphasis or importance | Highlights key words/phrases | -| `<em>` | Subtle emphasis or tone shift | Used for soft emphasis (like italics) | -| `<ul>`, `<ol>`, `<li>` | Lists | Use for bullets or ordered items | - ### Code Examples -**1. Simple: Basic Headings and Paragraphs** +#### A. Simple: Basic Headings and Paragraphs + ```html <!-- We use h1 for the single page title, h2 for major sections, and p for body text. --> <h1>About Our Project</h1> <h2>The Team</h2> <p>We are a group of CSP students building a cool web app.</p> +``` + +#### B. Intermediate: Adding Emphasis -**2. Intermediate: Adding Emphasis** ```html <!-- Don't use bold or italics classes. Use semantic meaning. --> <p>You <strong>must</strong> commit your code daily.</p> <p>It is <em>highly recommended</em> to leave comments.</p> ``` -**3. Complex: Full Section Structure** +#### C. Complex: Full Section Structure + ```html <!-- Grouping content properly using hierarchy --> <h2>Setup Instructions</h2> @@ -93,7 +132,9 @@ Before we jump into the examples, here is a quick cheat sheet of the tags we use ## 3. Hacks & Practice Tasks ### Popcorn Hack (In-Class) -**Task:** Look at the bad code below. Drop the corrected, semantic version of this code in the chat within 2 minutes. + +**Task:** Look at the bad code below. Drop the corrected, semantic version of this code in the chat within 2 minutes. + ```html <div class="huge-text">Welcome!</div> <span class="sub-title">Read this</span> @@ -101,6 +142,7 @@ Before we jump into the examples, here is a quick cheat sheet of the tags we use ``` ### Homework Hack + **Task:** Refactor the following code block. Remove all the inline styles and custom classes, and replace them with the correct semantic HTML tags (`h1`-`h4`, `p`, `ul`/`ol`/`li`, `strong`, `em`) so it uses our Aesthetihawk SASS theme. Submit the clean HTML code to our issue tracker. ```html @@ -116,11 +158,15 @@ Before we jump into the examples, here is a quick cheat sheet of the tags we use --- ## 4. Grading Plan (1 Point Total) + * **0.2 points:** Participated in the Popcorn Hack with a reasonable attempt. -* **0.8 points:** Homework Hack is submitted and correctly uses semantic tags instead of classes (0.4 for correct heading hierarchy, 0.4 for converting the fake list into a real `<ol>`). +* **0.7 points:** Homework Hack is submitted and correctly uses semantic tags instead of classes (0.4 for correct heading hierarchy, 0.4 for converting the fake list into a real `<ol>`). --- ## 5. Lesson Revisions & Feedback Evidence + * **Feedback Received:** During my peer practice run, my teammate pointed out that my original Popcorn Hack asked them to write a whole HTML page from scratch, which took longer than 5 minutes and killed the lesson's momentum. * **Revision Made:** I changed the Popcorn Hack to a simple 3-line refactor that they can do directly in the chat window. This keeps engagement high and takes under 2 minutes. + +--- From 131c9aec627b4a3cec95c8b0f8bbce9c7d387a23 Mon Sep 17 00:00:00 2001 From: jm1021 <jmort1021@gmail.com> Date: Wed, 16 Sep 2026 05:30:24 -0700 Subject: [PATCH 14/43] change h1 to h2 as we don't use h1 in most documents in OCS --- _projects/lessons/sass/navigation/typography.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_projects/lessons/sass/navigation/typography.md b/_projects/lessons/sass/navigation/typography.md index 641017e0b4..4a4d321b22 100644 --- a/_projects/lessons/sass/navigation/typography.md +++ b/_projects/lessons/sass/navigation/typography.md @@ -15,7 +15,7 @@ author: Tristan Chiu, Mateo Durand Amador, Barbara Zhao Use HTML for meaning and OCS classes for reusable layout or component roles. This example shows how an OCS class gives a paragraph a defined role. ```html -<h1>OCS Typography Reference</h1> +<h2>OCS Typography</h2> <p class="ocs__lead">Use semantic HTML and OCS classes to structure your page.</p> <ol> From 8feb3778579120e0e7d8b617e9bbc294ba4ed337 Mon Sep 17 00:00:00 2001 From: jm1021 <jmort1021@gmail.com> Date: Wed, 16 Sep 2026 07:21:00 -0700 Subject: [PATCH 15/43] grading considerations --- _projects/lessons/aigrading.md | 30 ++++++++ .../lessons/sass/navigation/typography.md | 70 +++++++++++++++++-- 2 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 _projects/lessons/aigrading.md diff --git a/_projects/lessons/aigrading.md b/_projects/lessons/aigrading.md new file mode 100644 index 0000000000..596670a1ec --- /dev/null +++ b/_projects/lessons/aigrading.md @@ -0,0 +1,30 @@ +# AI Grading Calibration for Homework + +This file contains first-pass AI grading calibration rules used by the system prompt. + +## Score Bands (Max 1.0, Practical Cap 0.92) + +- 0.92: Exceeds requirements independently; adds thoughtful structure or polish without being prompted. +- 0.90: Valiant attempt that meets core requirements correctly. +- 0.88: Minimalist completion that meets requirements. +- 0.80: Honest effort with noticeable requirement gaps. +- 0.70: Partial submission with key missing pieces. +- 0.55: Very weak submission with major structural errors. + +## AI Scoring Policy + +1. Start from rubric evidence. +2. If requirements are met, score in the 0.88 to 0.90 band. +3. Reserve 0.92 for clear unprompted quality beyond requirements. +4. If key semantic structures are missing, score 0.80 or below. +5. Do not award above 0.92 for this assignment. + +## Required Grading Output Format + +Return all fields: + +1. score: numeric out of 1.0 +2. checks_passed: list +3. checks_failed: list +4. feedback: one short paragraph with one fix-first priority +5. calibration_reason: one sentence mapping score to 0.92, 0.90, 0.88, 0.80, 0.70, or 0.55 diff --git a/_projects/lessons/sass/navigation/typography.md b/_projects/lessons/sass/navigation/typography.md index 4a4d321b22..e5bef597ea 100644 --- a/_projects/lessons/sass/navigation/typography.md +++ b/_projects/lessons/sass/navigation/typography.md @@ -1,5 +1,6 @@ --- layout: post +assignment: true title: OCS Semantic HTML & Typography Grammar categories: [SASS, Typography] lesson_language: SASS @@ -131,21 +132,67 @@ Why do we do this? It ensures our whole project looks consistent, makes our code ## 3. Hacks & Practice Tasks +### Prepare your submission IPYNB + +Complete this quick-start flow so you can begin in about 2 minutes. + +1. Create a new notebook in your portfolio homework area: `_notebooks/homework`. +2. Add one markdown cell at the top with the frontmatter below. +3. Add code cells for Popcorn and Homework. Keep the `%%html` and `UI_RUNNER` comment in each code cell. +4. Run each cell and verify the rendered output before submitting. + +```raw +--- +layout: post +title: OCS Semantic HTML & Typography Grammar HW +categories: [SASS] +lesson_language: SASS +lesson_topic: Typography HW +lesson_part: interactive +lesson_type: lesson +permalink: /sass/typography-hw +author: githubID +--- +``` + +### Submission Safety Rules (Read First) + +> [!IMPORTANT] +> To avoid grading errors, follow these rules exactly: +> +> * Submit only your final semantic HTML for each hack. +> * Do not add custom CSS, inline styles, or extra classes. +> * Keep `%%html` and the `UI_RUNNER` comment line in each submission cell. +> * Use only allowed semantic tags for this lesson: `h1`-`h4`, `p`, `ul`/`ol`/`li`, `strong`, `em`. +> * For this notebook assignment, treat your notebook content as the student artifact, while site pages still reserve the single top-level h1 for frontmatter title. + ### Popcorn Hack (In-Class) -**Task:** Look at the bad code below. Drop the corrected, semantic version of this code in the chat within 2 minutes. +> [!TIP] +> 2-minute challenge: refactor and run, then paste only your corrected code in chat. + +**Task:** Look at the bad code below. Replace non-semantic elements with semantic tags and run it with UI_RUNNER. ```html +%%html + +<!-- UI_RUNNER: Typography Popcorn Base--> + <div class="huge-text">Welcome!</div> <span class="sub-title">Read this</span> <div class="normal">This is a sentence.</div> ``` +**Expected direction:** one heading, one supporting heading/subheading, and one paragraph. + ### Homework Hack -**Task:** Refactor the following code block. Remove all the inline styles and custom classes, and replace them with the correct semantic HTML tags (`h1`-`h4`, `p`, `ul`/`ol`/`li`, `strong`, `em`) so it uses our Aesthetihawk SASS theme. Submit the clean HTML code to our issue tracker. +**Task:** Refactor the following code block. Remove all custom classes and replace them with the correct semantic HTML tags (`h1`-`h4`, `p`, `ul`/`ol`/`li`, `strong`, `em`) so it uses our Aesthetihawk SASS theme. Run with UI_RUNNER, then submit the clean HTML in your notebook. ```html +%%html + +<!-- UI_RUNNER: Typography Homework Base --> <p class="title-font">Project Features</p> <p class="section-font">User Accounts</p> <p class="body-text">Users can make an account and log in. This is a <span class="very-important">crucial</span> feature.</p> @@ -159,8 +206,23 @@ Why do we do this? It ensures our whole project looks consistent, makes our code ## 4. Grading Plan (1 Point Total) -* **0.2 points:** Participated in the Popcorn Hack with a reasonable attempt. -* **0.7 points:** Homework Hack is submitted and correctly uses semantic tags instead of classes (0.4 for correct heading hierarchy, 0.4 for converting the fake list into a real `<ol>`). +### Classroom Rubric + +* **0.2 points: Popcorn completion** + Student submitted a semantic refactor attempt and kept the code runnable with `%%html`. +* **0.8 points: Homework completion** + * **0.4 heading and paragraph semantics:** Uses heading hierarchy correctly and keeps descriptive text in paragraphs. + * **0.3 list semantics:** Converts fake numbered paragraph lines into one real ordered list (`<ol>` with three `<li>` items). + * **0.1 emphasis semantics:** Converts purely visual emphasis to semantic emphasis (`<strong>` or `<em>`). + +### Quick Validation Checklist + + +* Present: `%%html` and `UI_RUNNER` comment line. +* Absent: class attributes, inline style attributes, and span-based fake emphasis. +* Present: at least one heading tag, paragraph tags, ordered list tags, and list item tags. +* Present: semantic emphasis tag for the word that was previously marked as visually important. + --- From 3ee77c876a48281208a18fda67e74d2d055e21a4 Mon Sep 17 00:00:00 2001 From: nkasse12 <nitya.hamsini@gmail.com> Date: Wed, 16 Sep 2026 12:21:04 -0700 Subject: [PATCH 16/43] add Shoreline capstone card to navigation/capstone.md Adds the Shoreline Community Services card (missing after the page moved from _posts/capstone/2026-02-09-capstone_home.md to navigation/capstone.md), pointing at the current post file and logo asset. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --- images/capstone/shoreline.jpeg | Bin 0 -> 24127 bytes navigation/capstone.md | 12 ++++++++++++ 2 files changed, 12 insertions(+) create mode 100644 images/capstone/shoreline.jpeg diff --git a/images/capstone/shoreline.jpeg b/images/capstone/shoreline.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..9008a3b3a2aa70ea97907a0ee67c4dc27a126066 GIT binary patch literal 24127 zcmbSy1yo#3wr&$3<R?HN1lNS19o(%6!QI^gjW=$MlR$6_?(QDkA-KCk<IuRfKQeRg z+?gly-hI1QpLI&Q>#RDvcJ2M`ubyU~Rsfiiq7tG21Oxy8;rRo2S^)e2{Phy$70S!M zUZK1~Mg8kFI_?{EG&FRgcQ}~1<Rl+Hkdu&+eWYRg^pT30nv9H|pPreWlZS_g0w^FX zz$L`S&BKX+ii(PkhEDkA4Iw8b871d`Tb_OcuwEgwBD5kRU;$oWAs}KQJaqzyo*(c9 z;-5$ThakU1Ktg$e_}nOr2|z$ZL_kJDL4Jw+0_C~KpUz0gSZ`mxXBJez{-AIBj^&Hu z_lOJ%R)g{}6d@(MwpAQTd+*4PU|cqKVdc!@KSMnK`~Nfq0`l|UyhM3!WXF1Le1U+3 zfcWC&^H|7##(05<g@pX}c?4`0g%A4ga41;6*na=07$H>N_L9vY<M?SFfQI<|Gb}_b zfB@i-=GFg6_%=}@FKdIpozWJEuAlbW>_!lBz7c%e|Kk5y&`4kLK?u)HnnPCQx@QOX zI%ehjqLH43kdrrtzb1J|`GJ0eJ8Gpehw3cfbR;z%*eDrnKR<ulgFC@BA(GP8Qcg;# zzP>izYCn9+lL~ogdH)x^@M-dZ0&rx_MJtPhVv@@;>f>GIj+{+Nu8jkZeN}k3_zg|6 zLz+#0a>(rcw5l7&93TI$MZ#CqM+pOi4B9a9E0tQjBG*!pVQwu7!s}jpZI)LnYG~bg zip?dBnN(z-Got=X33D{528AJkelN<afcP{y(+GrrFDP+bY(|{`OvK7CqDkR>!(&BY zOw40=_2f_P9^qfO?y@I03_<IM9V{h%X|*YukNRM1<lzb<1caBE?(l?P-8-b8!Ga9b zKb5dpdHgu4RGY^)p^eEinp?xC!a@!fBZWBK#Ev~Wd|s?ke8D&8qgupw5%>X7TgUP# zkE+dqO+0jd3nsSAeNkATzU{gj^-ORB9zQU~d|}5h?Ysq9_xw{jIXU_D<lyYrNVP)< zp#&WSn<GF!c1%;cp9owiqf#&))oqfN(7)JQW_iB0Ge=FuuydbRQGfaCYZF_@PZpb` z`*2CYe>({%aaCNHHiB#Est+J7`rqS|yB<WtV3#Fz9v8Z~5i5}H!fk9p)3hV-on4Lk z!bd~yQUW9(;XFMS)7<ga9R!#@k8iBskrh}*_M*hOIv5=9Qd;7YM@O&MegY{raztat zO7^c6AT@8eNSxQ-W-<z?TN{O`*S>niB(GMpl-*_+5$Z$&^x<@XH#k=>iK{wlN689= z$8oDhZEkixYaQuo%&5$}K`sYt3^HVFEcS^{PKmmo_9i1QCr|p0s(9fA^n@w=)%1(% zwVPM+gP#SxGey8wMGvI&v|#A`B=J|btf0NMiG~FgN9~9BMhaNvFTGpdC&09wJ?Jc3 z>_OnZ-+bN1dl@0tKHM=YIL681qKhadr35pqf+uqwc!)!dwloVS2JFG>ucvFwZe!1b zWbgCDkYPhH<lp{{_`G`0Q5Zf>4_6JZ`msx@J%b{EX4q4A4e8VA9!=thI==J%YcUa; zvg~umfI-Fp;jcNLl1?<Y++()SizfCL>M2FNxCaVPw1*e>To`zn%;;OS6Qo$BJoI7Y z2X461Y_7qeLZGO=gM<!isRh|h-E%qd=Q&mJGNq@QdR@<9n--ztE^tW4)BX6vt4=;9 zYAE1&g)kkg_!3EXlr9iz2})1&Q-x>dv@SB5c~jAn?bPAYx4(E3J<h_FLIFc0WRci- z*J<5BqzNRl8`$ic(F%#WBQ5@VSGa&qK|(4Nmue5MZh3Dtrx~!#VX7=^Gs8VhN}XA} zO8_Rx9dF)IU|Sa*tyaO-DQbh_HA)fnWw>Z<v{HN&gX?gl?lD%`a3m&jsWah^PHo#N z(ux-qQYhptT8jUh8GUZ@*<v$LPb2#Fz5^NTdZnuW7Cwa)ZxZ>IUkp<%wvVKqUj5p3 z&@-3ef+}}Lc22f{b~#T0KHkhIv<dZ+U7BiE<t@Owf1kL;JmhXQe)&_#|3mY;PHCt7 zHA@{Cj|SDjr8%c8gbmdAEAgckx*`x+o@Gy7@yZ#nH#ZMPji5=gpWY@&P{k&&hFh>R z&%0ri3U*!adx#6PJ7W^H;K+*kDJt|Gi5Sxb$M&uXI{X6(2^pIPCgj>Dycar-YBR2> zQ?QjKdf}&a364|4dow-q?%L50@bcvfC$da!dBCLE&Rg<R*^Ms|HE~N59P?tESx3ol z$l4pP>)3CLGj@{?M#i%XNzqSrDnT4s*9Yq6)Kp=yVJvR=6a*wXgJoEgH%dwTnbaMV zCwpuil8-|Nv3b}!LIJ(LIm@K4<q*l7tk1W*NY%dKr8}}@WBz;jnx0{a<`J`&{sw|U zhO@<8J?&z*5vqZE`4=HPqVp5i&7+@s9~nA<ZMUS1$>zJ&oUW$s&2v=4;Pv3C%>#`b zc*UK9%7~C+e~?LRZ^to3hK3fgZbS6ikUPg=R`#s5@|C#_9CI$ILHx$MkYz2|?jl)M zha2Yvr1-l;wl-S|Ur>C0G5Kfj?wz~QeC-gC^NsIf&qsJdjWx{Q|zT6Yw<XGns z^e&3<dNkl2sh*@WRYAh93DF%&=*udas_B-w@z|!_>V+(euF#r9gB{)}7LWA?XJoZB zwvF2T3t|jn+k!1v-j~r|MktXRUvjE>rDq9udEMILH$b9kN_VBh0;DDv8ZslhD%no! zX>=SCAEP2=Rep&1rv}0f^~}ZZBt%8wM|72ir&-}$@!<`_Ex3$DQ6ueA1O6gwsbQ+2 z!2z#!jo{iuF_7`SHH&3mQ`J!z?Xyk$-wHkrlkQko2fX|+;ELueA1RXiM1ugWYk%*b z{RS0Pb~;4o`xBrB=Z#|c9(ScjuaVvzI~y<|5b-z6xePpdL#7sb4tH-4E&wMQ9tIpw z)9qRP<w2X57;8KrN0AlLL_D536)c*=b;NbBs0SGehv*led#?$zrnD^$w2ElO1)JX# zjoI?#un3FFy{%$y>mc`j^8$}Crb_m{Ia7U{IfUG|et)WA<@8Dv{4-6Lf0?}{Ie4lq zEpK&TOEa3d5p_ScyAir>d@*)!4ad3ME<Z7uPSel8c$r&rL_Gf+WeRL%crV1`VD1%N z?6e?5(!l@jS9P;CH0ngVwhwZrslN{HAj>40Rp&uVpD8Nxi=?0zE(!Gsv~BONPLj<i zqml%N&O2o5UDjxpC||;Q{(|jz<heNLTst?M8NFdF)O-SDy?In|oVlZ|tv}mWBJ(zS zFFeHL6N1M`GJS&;6@e3Yr?x17XAIi0pfiP*@{+=|bY1&ZmSrAi?i*}w<&eSX#RW)6 z_|#ouccgBjVGLyKBx5(6X#R-5z4L4ZsQtdU5GX#|(0>sS4m;MwmmOm_&F(Xxu5?U~ z?vC)_mpr?9$pn~|L;!g207ot@Uvr|6`ydv&ivIDe*Z$);*LA(ku+~Vu{^Ca!Y|;Im zPoWf9kt|Cfg+<z6r*Y-aEAy?@!Am{P3`+v?)zoU|3)&4@W^@Kcffc`x;iN%Zq>>w9 zyR}`J9-ut~VSE}|Ud{c*^22T%6#2Bjt490ud`6a0PfZqYwu5UXR1Dd2>}>ec8QI&3 zv~YrxLCMySa^7MhKq=A=f3{QLTxVzZ?iok+_+sqkX~@?N<v=N&$5jh1KizT0)xIWo z9(ryj#mB{X?zvyLDJ2d>Mj~8jMUaB!FlskXNYK4j&wO3mRJmT)y`*PqLu|G&YCtxL z=CK;z_}C#X+lE2wf^qkk4!eaqqql8}$iLAy-UPV_4~o_J>cG9j`J0txDCVZ3PPHg- z4t9xexSh=o`xgf+zaiIbvy;A%aCVPV;Yz!ryCE^4=w?@KXenH!YUoROzrn@kj%Q>$ zU0zsFvDKFdb%A_Jto;!29$W+3(Vq1amOhd^^vUZoABts~HrC+-@z)culV;S*!&{*B zq3Fh0*%*TER~)kU6V{yr<L1Cy$nj0_+q!+XN-O7`_i8#EUU>{5pr|&Dnu>4UJbO;w zi)8a8ideDTTroqv8xv?Q`Ve6{mD+~g3eVZjB^l#QnYe^!pVl;KFl(@aOj9gsvaZyu z`3Z2SzsOjHbD=zp;pc+#o%=P<R-c?=d{ujo*}Ndd50%woTi8e9H;Gm2_IFPJS<zji z`(jIOc<~cp!hZbc=YJMKZ<|aJBGXc<(xOkHokCdSC`wcE_AVTKp0nrhKC@`a)qn~4 zZ{PB~B51$X^Z1n%y9Ig+`6KpT=p@UElrI5K=;IFx#?L2yHX|17h_?xTp8v~Dt4ql5 zc$^S~;L>8$SUC{+Xj$b7H(36~S8*ck+KB9Myrr=_991BB;53rhow&>K&`7lW^|EKT z*^5ZP;&Q;hz{WG%L(<LnO#%|8=z6MTw*VtIGwU%e67tJT0&sFi?AwWJS?n5W7!|$w zZR`f8TL>bS>LALO{bFid?rZBZR(`L(UyIpI2;tJut_<)!NT9>y3`6c=P{6eGXkGK< zJ{>6x#Mn-q)|cjF{v0i&9Tnz!x;7QBlTfVY&YdnS<`mn>O7ssuzu7|fhjyZw3<S(O zg>e}j`F>YpJpLzu;AF9-X||P?twD{J)67D)yw-<`Ik<(#)}_&i7bh{Dtg1$nrqLc3 z%z1rn(oIneeXmb$(;qH^Nl%1F?UeZe>P_NnJ-&55$ip<^o1s<vik*SoA}c2nx?abL zkz+m-$vkcmtff#ZP?#TCm@y%}w$<3<?|r6WCo3Jr5l5M49oZJ}?OWDNhQ*vzR4zCl z?xcf1@YkA{2=w>H(0a{qveU9}INeb7-{Px(><WaO2@j-;3N&2r{a=ewE!O2Km`!r8 z5XHqW-4BFDe|~m@P`u+$h<r9j_oEV%bojD2Vgc^$=S>i(L7<Z=6n%5F?=(MJ<n;#h zrMG1J<w0>T{IqF+Vgs}g+)^~4xj3D~mABB|X{FJ6VXp0k$q>ePwcFonpB|Bhv!g#l zS2Mof2zgz&4KNbJ<BWO&H0-zaCSJz~@aBn19OYHxsxPCJ2B~sKat4bp;e?ojZO*2P z$K5OsHaR-~!#tuQqGU$NG#WJ&ZYj-<|4Mcp;Uj`qZ}j1>4>)0fWJMYwWT)GgM3nrQ zY0@4yI(xm&F=}z_6>@O}YbUflWry<(;ivsS1%4d$+1UxyTA%OM#@lE7W@IG85SWX8 zyTB-*?+Dhpn~uF#vqq%0vgBA#kvv5`XZV?3e30BJf`sUkl7Ek*rqt9a0^ZDH+fh}% z_2>GQj>#9@Q(kSJFnLAjLUi=a-LB^3==@Z;gHASQ?8W(EPY(IBhxrfjW;DasGbun! z2gW6Bq5bN+%!dqh{8^HUs34A*BjZFZ<Ghiozi!LK+C%mIRRyYP)RZd)Ep@*7Ezh!D z!MRR}XHet^7Q$=z2UMlZ*>VeML!Iq|kitfoT2ADyC7@%D$LlVIBV^Ur=mTR7-Y;G? z4n+p-;ZhqXpcGL!`__^|lqTz4i1}RBl~DO-j2UpR@R(a7-ZbMc@wNZz=_`3?I-<@q z>VUWC|22XV&g|R5e!LPtQ!f4iNjzXS5ECX=o1Yo!A}r55&UXwERhG%5u-KDY@)D-U z4Gl{)n6r{)uH@cNYD#0NJ3W1*t66tQT5_vosEW2xXrDF9!s_Nm?tsYT*|qe9)vc@e z{Z_95sT3d38h?eigMxL{7b&rKhMcXoo2r}ZevoFmWyVBuPJ?~C6Xy+1Oyvf$<dr!J zW4Y(r4p7#bMTsLKBTSza^G&_h+k%56@zjL-syYu9PNncE4b#C=x|;6@pUKH@$Jts+ zaWSYw*Wr~tWTgaZ3)!{a7YaMG=l|-ex|?TWPxN8e@n_RR^E{~X<6+!g!i>2o#}f5p zjYy2lQN-(2)7nvlalSrS2nZ;3?>&SE{g|XuZEzj3m&P<Jime>B&wtjWrgCWl&`eEx zyf5%~=G2QyDdaD&UV6&`SYu-H6sqz$8_x7}KKk${xfP%8Hf=F-PW82RM14GT8r3dF z!d`ff(Xd0sM`4W8rQtAdO||f=C#DnFBSiCx>C3D6JIa<;4-sCeW_So$;)3){UV+`_ zn*PAmmsYi3C&`JDwX9jXu+pG2>iZ0>sH~ZLBLa?Y*sSN!XfKcVmqp?RsmMhNK97nS zUZ4xvozoLw@KbAW_tbr56dC6EVpJ1v2%2@$q!(T&^8`2R33?p|UGs+16lN#)in;m- zODpE0ZbahJer(okA-;{dQ6$vi;>(zo&elXDo_LR5gVV3E(TTB25w=euo|yF|F16KR zd|W5pMd&|qnPB}d(0K8e+l0ICF|2j|$}3K#*l#LhPHe7?x1DD<X)`w<uh<XmK%Qje z8rB|s_)@(ycYi7633R8ITx@<_&1PH()9r?f%Vum2+1melkai3AYpRCP3VENM5QPpT ziqO1!0Z<}UI*yx5WL2`Y_+j+(DzFD6Rrx)5*YGe+elDyrr3}FpMT+iUFpHO{ujn%> z632Glt^7658Sd^`*qG3H8?h*7=|Z~*f45aVRzKt>r9I*ON;yhP(UA!rKjZiA#SfP5 zxaQ)o47MvT`pY@aQzVxwYm`L!sj?AS{T*9Y9#m#t2cEAtc<SKq<jdKp(ig%f7kRlJ zFj5w;9#&DlZ5MIFT4oQ5t2SDizT|V!={OB1f{<yxrZ-sR(E2UTb3t=$p&gMeJJ*fO zhdSze`SXrYp|5{b75obS6+SAazN9pgXvhbRXOki5(}v6nDR85^lpSl(Zyls#$O*4G zfr8X$q6y2)uoxA3ud@v!8l~p#P*o?e>#jdI0xwe627D<DiL!}Omwa7iIX|!}Qjs`T zNpmJ6CV3+uJD5{<Rwyw}YtR~bh_Ff(!0bL>3RGlm9yd~1k|xj5GV}f*Ut-~+yPoM# z|337x3+LU`L_onp)DX;jAsB75rclIqV5-oY*MrHAe=9g;vP`I_4c}}5qhY3oXu$3L zzamC2nKHkcsm&Jv{Y*me+&XME?M_ZMuh5JmK%?XPNv|u>l@gc2tklpOETpd?w@e}x z7AObi$zr0lsKAL2{C($Mv_Y>`C@}|_L*194k&U*t<?9#dF~w>VPyq6HAC^ZGhc_#+ zx}%Wa>fv=vSO2Cc&7>Qod5!N&<Q4ak+Xm%`?LZ)01-XPHWgyK>ADoRUe>bX_*xy^Q zaFDW<4zJPgxv-w^FRynn1!IX$v+0-MBe=S%0@aIo-yax0qk=J{VsZQ>Yb&_81DYP= z@quxDQ}VUJJ#DrdyV@3>`~A%GdaQbwtC97VGh8P-$@-OKYgl)snt5gV&mOJscRhkj z?T9D9B(YaKHF9c_&R_5^+hrPS3!5RUmAmr+DQ&Bc>sw!2i<lBML1do=SL_-f<_nYM zhB$E%&k&I}qbW@@$I>Mmy2TOGb*Zc|V^NU4pE!)hos$$eJkreVDU2j!zMw<jl2a+t z<Yqa%h1~ektjjdsL~F>%Exp9AA))f~ebos{00=m`Hl$r0SX4-D8Oc&JoY$Fyty4M4 z{;|1)neXJ&;<>hqGuP2h>13d2qv6#RUGJH}=A*{luUp1uQ2zuI+$D{AmB@QeHc9+0 z3O^G&dh*wVSmvww?sEj_1P(1>F-NB`Xu#l)zW!YVe;^V3?M^U+oV<-|IR<-u_IuL- zl0)05BGyOP>w0#z)B34wrw*M8VLBH6@m|B2t`VoxHE4_kL}tqletDYyj{Hpgl7R?l z$#(u2!*!=2=0Hks-n?RaN4p5xoCr${?f;Dv3_%ti_Iq7*^bwG0i4)rISW|p)!fNlf z)uw#fFhYiQ*?Fi1^qV%5&;wp$j*Ze0KbU~@Dm!@~-X&1UE!Sb{A=PD&)Wc=keXYm` z{He9-BZ;wms*SOtOp6JgC@&w;^dz?K94xBTIo?^fGLTdr9xDg!1BX6W5q*3q18E%w zDe6r445P-hIE+mzoD6;2d@UZT<1<<&*t5&U`Vh65IeVbC3~aPCKp=|x5>-{RE~aV{ z;_)LpWoaPh4KK<>tGjC)horfapEmlJ7nIf3WvR<tu`g^7*pBTMefWQk_^Gs7S5MD4 z<<<3ET1}8>!b`?@hf?{VWWePZ}c2Sk7`nEZEG0AJx(KY&}2<=G4I(XHU73>@+k zB91?7vIC+;u#)m;dN>O!>2)d*LXyx}nN}L-K)|r3*^)*U=h(WwEmavIK6@q*wSR4q z<bJ8-Jm=dv?AlS{;_*M={~O9S;o%=19`K;Rys9{*8}_7r_&|S8IP6#T8cuM^V{R4x z8Wq0FH)tA5p$qZe#tCVnb)?Dodt1x=FG$FLohQsKNEI1d3J-PhVu*TF-U2c32<@~Q zmXd5IJdGSpe<K2%k=?M$Ft<%;*y;ANe4HEw7EvpcrkHIr!LV9z2PD&^DAvxA7k%T! zX>w{-S_E&xq$f#Ln`R5QHve*^Q%L>~(|$`Hmh`b0s*v0v!f1=J=(#M#ltlKAi7Z*m zm7ksNw@?cE>DkXT#;MBb8z3POP`$X?U7Qi@663C0YdG-@*BD5jQBHyQV2Y@6b;z|v z07&Y3rKqizQ@|59<?stKJuaptdre6I@gL}d^o6mg)hL+4Xz);JP3cn5I&O6OIttHR zju+nTYS$EZR!`>}d_YE=w0oY<?k)C%6?n?3k(4a=qEhoGj>SBCL~xmz%_C3@j+2U! z!85hmQ11mKp|s@JLM(to?t`jw&2{;t95g8_Q0HUipErfCF^H-aEs3EyQ*WzV2$ocf z6HeAc=hf%OUNt~cM3#ywGa;F|`gam?*eiG(Ad$+2b5}5KlB;ahSAD1u_)jb-=<Q8) zXBxJSo2y@qenB$xyOcrgEvs0#1!H)_yOrHWcR0VD5K#6QHT!VDdwwC6w=g1aUi13f zTPM44Ebj)hNtS88%8*#UdpGsvrSY`OdWV^U890H5$*iRgHJ8!trzb$d+CBAd$G~O9 z8-qk4_-Bb-=g0SCnuJjY%7-IhM1uPspvZ0X$O4)P+x>@KtEmgEoO~PWhT&~(=%!I? z4Yr$<)Yb`5dT^v3%<@T|oK`%d`C4@RQtDI8;oCvtdD}CuZ#pnt%8C)kW=_SVm}z_s zB+D=kzw#^qhU8^*kZ48=g`BJn;>SZ`$%Oa-Sk4<A`#$F1P<y-62cZ&|{f;L<oD(VI zP()(ilB}Ex+|n#zam(%?sFN_7ko|p@;=j32-?3f18wtE!cY39De9HPYzJ`~%g=d~G zcbfq%|FE@@dbA8Yaa#(Kb{c_|4)r8^>bLf39So1xFX-2`&Go~$T+4_xRYPWhi7o2$ zjS8jjSmk96QtGbs`UXZeJGe^n*o&CyjS9Y{zw<^bKMZXfYaX<LPxvys6h9_NJ4-0( z9b)R|3Q~9-qLmifv&?K(ut<N*obNeKj3&dacT_5P)K50D;56SUU-DMi^sV7Z6^I8F zvm6xXAT}apU#|*0zZf!A!U;?82yFcO+7`X)uG^hHnFf)PXPq({!4H{x#MhDcu-fBp zJLwkHJr9xTJg17bz5exNFNY5An*+G}hw7xVcWl4LCTj4ta<br(Ej>YXdkdI5LAyln zEv0B)y<*?pMP@S=A`VB4w(Ps14Z4zz*Ig`cCa2@*4ocZ9%PmAX>DIa_4LT_S#nkT3 z793KZ5?O!oFgN>ss__Is_8L%jOlCd4o?f<4Q$L?fF!<?O_Gt-^j3QT7eY&YeOlf`N zYV|cM1*8(~WVoYkUm#xBD{A8GWNXIHaVThFO^>~EaYO#QIE{EV){7TEnnm74iBtG- zil6P*x(-)0-zx_sXdDo65DHgc+Y)sOeLGWavO;rf;sFMMR7Kg?)7jGjT*zivScHDF z#{)1#32MYbO@s1!{_7ve-7ChnK@<W0%m<8QQ#>UVgKJ$pzTsq{3q)zA7eec+Fe9ui z8q@xd{V(NNzDJ{_8zIsVeExfZ%}Drw5HVQ$)kmyB`k1QmG4tUZ++t~SrPxM)D<mai zaW2xL8Hds$0`ShpWyyvuymFB=GFjy;;<z}=y8;_WSpR@um4I38qxqn5IcSO~cSKnc zPeK}P^ki|5^Fq1)8ZR%=)wG4*^~+fgdmD&aab|Be<Hbi|RKd@*;#u>^(Jl|nM3KfH zIO!7=KEH}w)$C@48DH_9t2XIIC4IUw3}u%CB75%0^i;<NiFYdh8knoH8t?K5{>~OE z^xDyi-(868dM!AGZN(8*^8`R~s^8-RuQrNQolljb`^Em+ivO_=uU<x)=4<$MwikEs zV~?aDW0rz1XbajCzcBw%(3{0aw=gKNpuzmTVJPTW39s6uvw9hw@#;&p!)zTX@ts4M z@8f!HRcVv^fLNf49ghq>JZe+6PF_U|zF)ZNV71{w_Mx#Lwl@52=70|s5b}}T?+}Gl zindq_#y&mKiXKq7VTI_IaiM(Q66(X5cwJeGCqTu0P-*qo9BT(redmfvVfM&aJ=gu6 zhQSuNk0%YifOaeR=tD&70hdZ_S7c?8Py>ah{^{)}Dk>1-d%nk)nmtXcA@<>)$5j=i z<l1r%_)}LEy!)YSq}DLpTU(apN!Ad1+93LvmEAtC`H?9ngPqF5(>ZOu7{5rr)X+q; zH3;A5C6!n{ww}K^L>z#2SS-d$)^G2|naePyFNZ4^0dTd*J$|W%3BS}9RX$x%t4f51 zt~~^i_E*0JOA=ac$G^Y%fzZjtMU3^kc+YJ;zS^Ums+>6|XiAq3JbKEjY6Su=oR?-1 zC%e|xDWBTNa>HE3eQn^cWM1vwvEx|jd{p;p8R~itCc(Y!lYwe`9J+-pGOP<g7ZfYH zT58!Qk5Hvx-3X<HJ=$T)+-T?TKkMmz=t0~1?6Kv~X(_RI&1wNZDlrwT$8Rs3U&wi< z$gOzD@C^m@U&DGAx`y$|R2uP!IP`Fe(4yXj?MaDTM0|%K#aQ-ib2DBI$J{i80(pv5 zH3L7wWKlksT`vltkP6Vjnwk>4Oa_LWj%?spSCp0<sCx+*p()V<T~W}1!ilH|Nmr+n zYl6y~Vskv8RlimN(~hP&C4B4nh5>k5<_O0~^2cj6>&-N@L=O!$B?jPYpRt0bu_R|E zLGgbl9^n5LEYlD}HpKAD<>+na!mKFCt*nFe1tkEBXo!R=m9!k?WD?BmAK@-V#C!ow z<{nMUoOugqS89X6dr>vD_KFtaYwE!RPVhWWFyx25v8%-qBuvU(Y`fmxwkVQMEXE%% ze;H}_(Y$4>#cxw~ZUsw%;Fu^psIZl^Iz^K-4p-WxXi<)_(R3#fs?_xa!2ET~wZ2-b zaP5&qM6g?))%$5JCfrB<;#<YIM*BBK=4h<ipd+#1ijaq*YiEqYxMKVD@bHSt+nlNH zwhL<e9c^9GB`@Xsk~MZhTwZeFfPcv+JQq-%{OhPZ_(~#Kn_E@Jx;FG)sy7??Ns6p1 zR*x%l<l^=YgPpfqe7ZK&BElFo6b-Z2YjUo1qzPouzLI~Xi4P<tL6W`5(mylrHq*Ek z%{XOKu73gy{CV*5Tef?`A3BFeLdGEoL?rU7vBIOQa989p|G;HX6PJtjpfkmlJcAlf zWAtK<(iH|8X_0$O3!h34Sq{9?uEHc`F1IobG*1B0zN#)p9(ICPXSv99x#xbE;4eRL znmdTH&@{KQoIYilb>SQ-EF0=SJW+W9yvcQXEN+>Gv$1ECn3@uMug6RZiv_qMeEH8% zLvV8+Lm%>uJai>5{yZ=sezN{@+TtpmZ(5=1mN(qP=gOokvV7g-@PWgnCFA$4JvZ&H zO3rM-@%yrV(E(`cnBvDDal&%*VtpMKniXpyKX=#dN_uM6Cvrzsg>+>5b`}f5$S9Ru zWvCS|>MCaF4W=wVX+49jWZWBAqFaqVqN+{x6eLt<$B8`-I|_yQj?#w_u;C-hvlcxn zSV*OtSNjo$K%TgNpY6R_-QPnaIr3)@{l6r8COR}Szk@4qDcgTT<w^+d@u^kPLn=5S zxPdqJb8|LbYP9zYw71@G%*sNllvcm-<O*I|KIT|;_}NMMqzs1f^SRjv!XtA{WO$Qr zbecP3AevoZ`O}#`w}pn0#J(`N$2UAHh*UBZz#W}NI`+&qDXSHnvrI8UGAJx)C`{$V zPzdwsQnh2flFit0^?Jc9=J8NG5M%LAte-d0$2F#l#Gx1vzgK+i@d<%2=4yiz_B2^= zl~bIi)k}_z4r*75)rpmoUq-hv4@*)hUAF{|Cp0<rJs$*5ljpPsN*pt}b%Hd)NYV^1 zv|%CqC#<B?B)oB4^b6LCJ2E!pSijFztW`+$pL5u4FmEDLx~lT3gSCUhQ(b7;X`^lT zt2C=aT>24*bhU^{_Yx68q*1ExY=5Q8yfDT7oQO2qZ>s-KrN1|!?UH*>cyoO!V3jxw zx9JAk7HH8|f5?r9wC^T?xA^|v@bKif${La#800u@)ck=&s3y5xGO0K@2xYP&kt46j z;XTL=xyeGO8sBuBic*`BP?DF3*m|V+iMsa3-CRF2s&TuT*F#Ry4npsA)8_avkRKc) zWPgwQ9PZEA+EsdmF!JbO2-F+RBL8l6{g1Ht^XEU)`YJT1hGWMvmK-#drEJnkKWjZ_ zYI{~UmiBIDb0C2H=ZYW-k^|kcTWHgd&dx!(-`}7icC?jBp!cIS47(6henK^j=`_U7 z+Q{NfgZ-M-om&&&9(X^^rjkJ=-De<-tJv5P?uiU)@e(hJl-2lsswc3ub$fH*c!=gv zw?=rQZ3)kLUx29iG8<i-@FzRD`RB>+1&DOd75|%R+A2vs6LYq~>%U;D`7UK5qxP3e zw$ep6v-cty`md*eq|qU7eNru}N2g%?7}N%Io?Mq{4>56gWR`9@aMwIKJHuPYYt<Re zY~fmqbBubJey%Bx&XUVL-*i(wC<V%p%1LT(6y&uzRj_8k%tA9y*o{t(A*eKX=ydrm zTd`c-Lz(5-v-*2_gH#e-qEy)?lCmJsziWUdCnpmYqH^^~#6B~ot$a#&edRbRtcx4} z=yI-MA|fW(L3U2KDdsJA?(8Tkup@Qs(moVS;*107?pq9(qn<o|`1A;J&%hIlLkd!$ z<xei<xNCYF6|m&Sd4rS3&wKI&$TNA(w>m=BSoorlv~__dHfGwY+fOZw>$kS{{g{6^ zr1oo`lejM*@v-h}rPG$_CIW>lQ6<rk+)x4;LY71}BR121)3NBWEZYB0b>5PnRd)p~ z3bpmAjy7?cScDeaR-O~L?^rfw%Xd=ueBJ2K*F#`a`WT##M_`OJkd!eUbm{#_-@y6t z{IKj*gBV_~-PT*V#JYeP|Iq42xaEz$Bof7P%-&ZTB;`oeCMcXoU9JHK%1U)Gf6h;Y zG()^mTd(z58<H#UzDz-3l~>2!ECI{?V1&(#wVAuu+?<C|`~!S~91X5r&2&)*->12{ z_Pd7HB}6*2|ISYwbhF5ne8$phRO!86yg+|l(w#adZBD1-7y286f&ayDbkcA}Rzz<p zDpX^nbU{qV&h499x_`6<*GK0VqwsJ|(M`Au@%>!h`SlM@lEXd_&>gbcv9*Cn)HC*m z79#W5Fn_rdGv3M7^M0ha<T;gmI4mH*fcK?x(d@9Q-PPWwZIDk>#aP-t%#l&5dt)L( zXJ-C0aY!+VWX-bTWzDoQLJQtT8e+ZU34PIy!qf@WAo%eej^UZ!2TE^FVv_rxfirPx z<x{Rkg^BK0$!$eLN=9XtaMFRms9pV%NDA-ioiCQc@wq_)E;l!H42@pfq5=br-*q-r zXX4^dYmL|<ME}_i(T>vmt6}<2E5%yRes)dinEq2n0xd-yuX#<c72WcV?@;}qsl)JC zhu++8dCD}$JEqCdv(^Q9uA}sznp&gpmVz+67l@aZ0NelEW{Yl(NBkxz@PvrH6{FE2 z_g%F7=TU&+R~#vq!>WP#lamKNl_JyRPg*fUS@YrtKPD!=Q!0?XbSX_H_9_5*0J)pL z)KS#5OiIq*HeAI`Df8bwXdjXas!x!Zt&u_*-0MAW%-09jD$OQfa*=o_?N_3!zkjXd z#|K`<R~KCtUy_u>5)jDQ*+#P1P{Nnldy;~&Nv5=IZgYxEbLFHa6*)xN_igNTny`j! zq@|tX(u0L>!sQD6<S=X?5`5TN!h^zA+O1{`WewWN$8umS`q28@B2N%Qe^a<X1YbxL z(aEdK+JnCGFGxu5TMg=Yrfh@0${EWhXdQ9h(QA}<?J=~FeXuctxn3}oyiUBHhZ9$K zkQcgyI=k*_Qk64>&*LMDBv!DnNDGHY&iOe;Qf9@8w-5=}OF^r!JB#8%$`U(hB2WZp zxkF;1qF#>g$@q6G6R_|WCLEHWUuRa0H|kXjhbJYT07|cU*ka%f8;9qG6L~Y|Lq8Lg zc{H~FEaY*A|MwM5-f#9&NrEL&_Ft?4q_ds6lYW8k^v+OYL;SW3JYLd5uk1d536D-# zQHhGwUbix4(e3mcw5f8J5SY_Ap-{g(UDTc6OI_~tI-|SYRSn>@un7w8`e<lKfFO`K zljs<xbzOBdBH7TZJYw<~(I{w-+h|x#x?I>c)n(Bod$%(%xZ#1OWF7a(Z4tQmv6R6r zOoBS7E+8OOs8@6G@-WTf12Xyd-XBrRz9ae!rS_pUCMM!jSk!S$MK{i^{dmn}F|17- zX;Ou2dLJ(Rph|Ov8)h9p3=!cq2BAyu2L}7jk2Oa(-G7yu9G_%<eBR|i1t{OeFFgfJ z<mM#fl+_DJ*W+HsMr{<b&eVQvhRU{j5k?8@P%4k!x@bD%Vx4R5t&Q$BSyf{2|BhJm zVuv0dFaHX})bTR0qN0P_y)nC=^5STiEOY&M-R$*vRy`28rbnkG>ow@_^Wt>Tz-yP{ z(s$&AKn_iEVG3^xTCNXmdcP@4;{W9)n?UB{KX=Qe=sUzsiE}c2?JBO8w_W)Jka+^I z<ZL|wpk`TZT6M{-5S=1Z^ZVCgV_LRZ>KPlZ$wx6}PXKY>=1%g2*-MlIWRMFAS?1P; za}UE~0@23Q#OL2CiWfn02N)&<raNtiS7|3Y_cY-w>3f`M6CwgbP@2wXe%~vrIV!fR zAa1RG`H2naCzc*3ZhtY{Cx9Hku>ixbiACiR)1dhP=}WqrD#Ptb&}%C)JbyBt6qsAj z{^mM9Ol9!S`TCsZ5AD%5bd&trp(He*tMa^|7BcW?q<l&R%5K(^&a);g2#O?<qvea2 z8#6Ck#DJv&S=RFc&*%<T9}PbX+CQY!?(d~s#|yBx4W;b3jZqw>T|5E$clvC~V$ky! z?NEwdoRR3Z&O8BpXXG9yGjUXFj{fF!{ikjFKNnbXDSE5-)1Ls0woiaMwVdsX8KOt! z6rsBYnN-xd_RR%lwgY6nK$Pv0>nFgxf5a~H6F|lJd0u1cJINDgXAr6|ovS;x>u&@W z;=H8OZsQ#~e3dWEIS(*c=<+vv9Ea@f*NVC9n>$7>^3SyBq^c#K8P6YxRO<$7dBhjG zCOEh4sy9=>30CVfjqD!;7;0YRx~UtOc1F~P5kS5pOUvfql{p%h$~dM+F6gm;@<Ava zc%ynsw~n)RvCw^L^MF<<nmId4PEJGSN~i%W`j8V??;eKOYfs1M**}!Tw4PjV@N>`M zCr4@`7no$4jg3xAtHJ5gc?W+7C)}@k*Q$L=?LF57cKDc4n1D9Z#uBaHbXrGb?G&lx zu1AxKhv=Me;ETIEfnbpuGp|6#jUpHO#%4Ux++Xuvjzy6h+U<GOC0!P>yIori&0Yms zo&#Y?yxHw<=+dNU*{OUKP5;-+AMO8NYyYR7bOwBx;P&-Ov<dT&yJ6egGP&`+Qa+mc ziKf#yKAhmtA*XqMye)yKHApM-15O?;G<36}%IP%kD&PsQiPWHy`4>q_TzQK^)8WxG z0%Q`p9;b%-&=k~=uY3ePKzUA9Xw%E?Cnf0f%pI>aaNY1Sl<jJJmH1!zvy-YHtEM&f zqdq5S`L6{W)ATJ%Q=6yCtmoQoI;Li|-5YnCi>#u0j`}XBCwX4t*pFApf3d^~12z!_ z7zy!<JpqJPYFCH2HaiAaXCm|#haskgG?dILo!c-B7H6^##e0#pp&bK8UGAy}jVqPr zvzcPkk%`X)TDEc?wUk+FMwZxWGoo0SbH(O~xC4K}FO~_cNNrHTdealY!2z`l<kGjk zx>Lu8zdqC8xg%HWy`^51WUDeemqKb|Y-4f(%nO#?E4;0dh4Ht>@uE&_!jbU#P%Yo? zYOzXf$C{h=b_6?;u@sywxKQqMaXqG@wyPg&rUb!fdoGnvzqfVeC^@=XMF2r@)-&v? zEctN0Qu2ScLjO0b^$*LI;ZKYh#wFuUeWh1|<-{>>44y^0S1VbYsl?HT+b=ZI=QKDo z_{9J(eWh)sl)2D;J?cYk4oap3r){rG<*t>~Tq8XK{J?*B7qzxvAOAM6Da?%7YC$Ax zb(Yo`yN$Sn8!}H^V5uXUx=hko^!D~=Mq*Ue9n*uI>H-DBr2R*VxBwlPr)-mk$Rv-$ z;Dff_wel<SpMn^~no!Kf+P4|;@t5sCxrik#B<DV<sA*{V;VPLl(-JozXEA=DIas%; zG-;Bp#)uLWLq}$FINwJHzXYf_Rn0>gmHg3d)oMy|f=zw!1&<4}yh}mDxm4myVFVf? z@Rr0=gIw{cjMtzZO(Un=8ufephXD^4jrSc^aXkr3sRpwP%GQ&sY^fNY8>u>*p{{DA z)Z^xnL5ZP>v>Apn_wP-s56sRO?wxJdLlueM8_c)CeNqpmZ1U?X68t~qS>3z!+yNO# z*kuL=9W54b+$dJHbj<6q!B%6!R(LeD-+JvU_MguK%tW4O+p{cpb#dE^fY)@)LeWhT zzu}`Mn%LJ?1RMnTR~ZJ)i=$l@*zgW^Jg14z${(Z^cUG4xKS_qBz8>tf+@9@E`Tu$E z{_~Nn{L%^tdv$N7EIPtlKMLtWoYoT@Oc!!OO;=vx6&0I*AT@R$9GLHWm6Dx#zQ->t zL*Q(c>*Cvp-e~=HeM|qgj;j1%z<sLaYI6hW1#6GDtMIJ@zklg@lHS*|%jhjxfj5+D z{dty`7bHMVPtv)o*K}}A<{wy7mr@=b9x|-NN6uD2BbKF>oPjuhf5ydEmF22U$vo+Z z1A54f*MmPdAC-D6#`a4JW7^s=#yY<L+|;*{*`Eu~UCBO@$Ym}zg#aL8fEQz|th~_a z56_gDz`wJ|nZEgm9%&DFpiRB~iAYrE$dBv1!%-!a7L~}fmNXD82i&EObivT02oCSk zo@OWX4{L^BCdm!7$9{NS)3zXO+h-GzO~6~ewMabW#mETV@qGeFtPeph@?fP>fzISN z{oT!BkUB0*WzFWXOlqZCuA(2~Q$vV#<s0sJv3+5-OAw|DuCfc}uC!0ZY$Kw|W<3Aj z!CMxcgK2+Ycr;{{y~3dz5}53hiJKNk*O6y%)VF-CcJV1C{!UH4OxdD<R2xM)lN|$G ztvX@V(5nd(5}0Q?MTu8!f?Q4LF;b7L%Mwpu?aJ?Ex!Jsmt{H%}b}$s%4}XZOJDbSR z<i>x@@q$_-Mx5JQc}V3|Z6L-dUW^r-U;Y=Y^qd6lNckarYd=)p<mzFP*}mWQS6ffj zrb$=V0#RJTu6FN0)Xu~tuqYSD6NF6tcyLEqAysW}HutlwMJ(KqUZX;kr@`6XWkdIa zz~&U~TG*?Ecc0lq@DY>-hw|($&WjbBf8Ay=Ka<Nn=M*mO#ngX0v^G4zZs@GCf|c-m zd!&cfZ2RjARC;n+LM3Gge~uNP|F<p#LZZdgtw^12F;~X<&2Q(2yj-X~mPZ+dI=aqJ zgoe)S9;7ScbgTpskVMBclN{3>w5hDF7e`BG?L2rbyN1@iu)-A%iCe^%-<1W4#y0z7 zSbr(WG#IOMArdpnjXLms{~)h-$#Jn0{piozy8E6e%)_a0SeCR8#?L6d`5@`R>*kxr z1*=zWbp0ogm9H-3V^Hjj<tuN_QH92XWM+!C3zXePu4_*IX~hc$sHF)Bb$>`PMNeMp zLl?z?m<+q66zxvD9z`8EF7Q}=X-phev({r#dr(#@Q?9XAHU27L$*s2cl(Vidq@J3x zmQk&9Z6-Wi;egh+WcnE?LYK;+fS7LPIm1pGf0t;KKS)Y*==X7*iewBKhaSsb8{xZQ zV5lWG^U|}&7511m8;qXB_^|#X1@$lasDCQtiKj{Mr)F@z4klc^RDdpdW$v!&-zI#} zcHe&jNa3~^jm|Q0>Fe#lv%DB370Jm@McqeLI9g4Hlw>TiL5o=|%vm#Jg?sBJ2Pu+C zf8+5=+rr<;<>G`7FF85Ae_Ym-OfaJ(P(Tbe)bFLESFbYHn4m0|)@@m2>2UTtk|@c- zW-|~!Yr;{Ad$(RWed40Bp-9DlpChQ5qUE3cAIErn2n07r5VBK#e{@OtVA2yKV0xL) z1d5zp**bQI`9~hMbuaH$M5RqW0nSfoh2yyDJ0qQ=hM*$K*!3yB*=Yk-b5@1*BeUbI z)Vxb#jx7*f=?L-DWuH(_;mdIn!Y;$SDy5z9R$y(5P-ohh%I1(o<>oF|6OZlsm88## zYDptOKY)hin-4OwoQ0*)Z*6ibDN#zq_}yn_m&X%8vB)Z^Z}I_1$F0J1+!Q|+&1QuC zClN@<67Wy=ejyoIG(I#b&$=xCryBF`olGY_VYqetL0VQ21`7g`G=XTA%vg({6v7S* z+<Dw?8zZQz7&!5q*n&AI;tl=42=}R#qP_$7oZt_%{8<xtwhIMyV&GVgni+>qb(o{h zO9F+ila#h6K!#2{H>=#+{4Iy0f(L0&O3_%(E?`!S?=#z0o6{GpH$~*1(j-G&^SGp3 z?y(J_PA{+&0iKJ4gdOM@)teoS2Q}#Z7O(GlDE&>%4olFug0eBr4Np#Y3oF0Y2nf7U z=-5(<(Cf@Y=pU<fdrtd43tv>2^NFzZ4wl0_>T6T};*3+f(4_uFX}qSoGy7j_;chW> z7gdgNEMPLQ+#%b^8L$<Pv`XI2)lXL}T;5k}Ya|aP+`mTn=8bJVDKJTZ5#!Z^-C{WM zkw8u@GPY2n$x#(?Y?yhRfL?g*yHCvLLvl_U(ml|EydOg16nP<T%(brhLz9(;X;Z7# zVW1Q@vo}eHF-P2v+O6zE_p%x{CX1h5hnjNZC_VxD1OkT0s2y6ymJXSdZzZ5UeyWae z;~!W3Uy{tt37!D)zTqUAHfo}v9Of$_#*#9#ApVSu{NIese5X;+Dd^f3xOa}=gW`~l zy&w{%i|-t6;2C<jq*$Q(O!=TQaw$IfGg1;NK@<q%o*tVggA_4_7{?05M(n5hD%#aO z0VJ3BrN(VsY!egHZ2TwdrqMQKBaPSy6w>?6uwN>Pk3~;V{4I3Ndxj4qvgp`S2!u`h z|7=9hq3oYM#q1eSltS(+<N2~#f%|1pn{LiO;!>Joio|`Y>~$#4gI&fhU(3#|qt=%S z<qDs5eqnj077fDgFe@ODZguFq0xPC((R`wM#Vr0#xGsW?(Jt4{PU)NhmeK*g#gBjm zVsM9xw(2f7{Z6T!bX9gEOs~6C&Tli*#l<Mxy~S&dz4gAnb>r6~1?R?LT-^~K{<TWq z$x>yQs_D&#OZUCqp|0=M<)T;Ns-huW?rOTEWodZbu$$wFPoCMr(bh<@KaViXkHTkc zj839D3t7%#(P!u;>_c4SK5Hc>o4MkL*>#pu<6g?>&+h1~l=jkdzOhCwek#86vGib9 zwFopj1h7z}BGC9P&K1s7cWMi?X45)pC@Cu3(57Kfu0HXfknZv6C3yl+c3C)O@9Mh* zM@UCB4A|iK{LxePA|l1@6Uj^F2VItT(_l}{Qz+!T2uj2-I&D;1-!qqHRBy1CtF3aa z0$;Od@k;w4KAZI2mLW0O`3ML-iJ7iidsImDm^*jsA#@(Bo;vAn>yc6|PWckQTGLGE z)!#d3MiYO)wkGzyYn<5p8d;=&&xOURu8CtJ&mgb$(>K6xq8Q5DnFqC$fr@gRP~q2a z%>MX2@4US-8m$|qMzLmlrBHsI{ZzfzE{@OZ$#raMpEGY!npypEsdxqnC!@6Qfh#cv zUT)`#S7=4<8_$$v`Bfww%i+6`b&?H%U7vG%BcxIWRhnUzZdGz-1@z7g-+T5q_Ey|g zs65%r7cN~r$>@@U9=8vqL{l2TbZn-5e}kvZ{|ls^;Fci-E2a>#Wc>}j{u^E$Dv>3c zJ@(9^B4np(eHj}XJGZ6GA5%TlDdcWj=lV$9rf$oX>b9S|OT1lne&VJZ4>0|Wpm}?o z@v!ON#DvH74TZSa*nqFMbde*bJWk{@;_~la=Qj+6wF2@%!}${yX}-p}xvmAgl7ZS+ zq<P*2Em9i~YOx7b0~^)l@3Q|!=LmQg&iK_$+y({o+6hC}0(XgfLRVV3kF4M_yJlf` z037LJmIE4V(|^FrSi5LBBH*vv%2}^n;IV2npzFSdytm=k{8CfKQ%U4kust2F*y%>( z7`S?(@}&m@1CorIusOc8QYJAXvG^&aR$gzX7Y7gj<JS#1cH@w}VGGdJHw=xh@ZnOO zVk#SQQNL=c-o3`xoG<=-fa1?dj^k0Kgj^@)-6~t#?JDCTZ53E~b>@4~I+#h_P^pQ2 z*3{P(ytJXd8aK~jv#No?cQ}p!e6yw18GKZr59Q-5uTeAZ5KOOmFf?s&v!w}bJif=w zqxHBNdZK?5Q+Z=0mtb_B1DA;}L$vi>K5P%%sRxgPqB~^W=)1Avl-}}GZJO0$vwPxS zYGhu5SOW<)U9o&e%!fR;!OTqU-PFg=G4|&H2_#H$3g`FIa@O&<ZaDXm^X6Meyb15O zR#a-=Bw^n&EQeEf7XRMrEi#QyqaSkJ<pLHgB1<8z+idmyL#=8ZjfRh=QIn+oM6oGp zx!(|L^57`-uFDEAohO4lSk;scP)SnpwHsn$LnYED)BnTGlMVe(UKNX9sJQ85BAdBV zmZ&lzJMB2YZsny^*a`|eGd3u6m(v=vZhv}!yQ>;1{+lS6oLb;imDrQC8bVXQC}%qt z=m;Sk1(*WR`+H^r6s<h<coNq00{VbHnoCAtw=Q7)GptOj7CbqF63Z07(>w}o>?~xE zW0|8?NyBh6oTs(f+sv0s@%}0Q^N?ur`kGAKY%6&UKlKSfRa_KydGS|3f^|pb6|I-u z^qbBVJQ-(=gF^yQpp>CSwafZPiia+XN1aHITxPjmC(S1G@h@I5r5h{Z2Lg!9*Lsn= zpC{KOF{Lo#3ozIIXkw}<rwsNSd}@g6NUwpd-9Von+#(^qiY^tLP7R2P9NBMlPVOtd zT$r$Akt@*7bThQ7;Z@RU!Yl)tR#}m}an^W=`FvOtrM=K;LU>0ng`OC&_N&jc_mFc{ zo1<ZGNHD(?s{hwr-Ocw0)S^@lS((PNolG;%G}=TUI}X+LDkSZQ&#)AxE$#duWNC(D z?f3n+zC)+5tKslFzjvlgiRkaeuScYi4(Jo9_{f}%AT@MaFbW0GsN)?o;^{7De9B?U z0bMJnOi9yN>1?J4(6Nf0jgh_}q{_}_=}ni)W{0~{fnTty`SeCry5jdQvg%41rgKTd zne%jc&{n7Qkv6Sk7q_s1T5xM;@$OXf=1KJdy$uqU_p7zkm2m7jCF?t4Qa%2BKdvLD z#_y-wb@n!E?ql|yyOnwqF_HyA<{Hu}%sjLxxOEJ#6(Kw^kDsFZh>BY@k8R2iEDqA5 zG@TOJ^UU(u^T!rmR`c+FoleP3|IhDaBKyl~!sog~wmwgmlst=(+>6pFoo8S!>@EE4 z=b`C!$?WmcV@6+ELNJnN!Ra<GdO}Whl>|Aq^4%eke`G~RPYK`Nz_4BY4eQ8$8sh7m z_LEPcfnjbi!s(Dmmrs_a#a0q2G_{RIhe|)kMR+mrms%)Y4)v()78F3lwM~OrY82|( zm~R!MYG-%%zByYP;XNZt+jy!NxY8{iLOkmU8Z=IJerXsHDV4Xa{(YKjE8x7E>mJNl zL(8ungoHc@zH>Omu71{<UwWC+u?2l82G+pcq@$~29Y7+*nyVM2ttK>u>^xNQhI|Vh z8+B(k%o`W0rL$|Amu+gsKb2Ijc64p}UOu4oq-!3FN@LGii<j=LsZyo%cmIz@&NHgX zt!vj<5Tz?19i&SKArPb^y#%CpL^=WKH59>35rNP<M0yQKO{j`AArv9>&_j?SRf-hx zi|;%39^XD=oHNe+@sz*Mv&Nirt$E)UkNY22>TMS5Pgkx4*udu^Pi`isGY~%dvrjBi zr40ENDK%>*c55~;@}WejJ42eba#a8v7Ahk4{N~TbOtD<G$a0)#S(ht1B>b<NaF>(s z%6Bsq*}A)XDZTHmryokcnK*2mVY5*Oz*?X_12#09fk9Y7nM+?R!j~)ZyPL=xO`K~{ ztIFK8!W<EMAT;jt&z*2jOpKhiSes_H->gP<=KMDbrlQmn%OIfFUiC1uqx?znwUH(! z)bG|iFt5WqrY~R4Yb|U$!)WPRfermzjul~ntXy?72xVg(SHHXCaA_S4xVZmdMOoq; zpxhN=Ka(~gt@GjlJFe@oN(F$X!4Xb-hzF$9wO|U`!9@~>z%xY8J9&9%oa~+niE5Aj zXXQ+KSvKq}V@})QA$ylw>AGJ?<{`9KFiDX{<|WV$Ob5IZPdIbGPBYisT{=5dr1Wk2 z13rk6uW)#w0w^PINKKwlcT$S+I^X=s@~WkgxifWS#NOkQ0^>dst))FOrfH*+^?YM0 z_|Tlw+-BwRn8{o2b#!;tPQoWRhkuNU=+1nI_>I+Z(``nxl{f$OuH3pS(^=Sa+n$>K z){Q%Q|2-u6a}B{|0JE#qq9rSVc=504LhPJ>B!;RfC&A{+J<FDj)jHI@&KEJxf(_ET zB`!SC@0CpQqnAqJ(=}8Cyb*>TV9caY)ly4Bk7RL_*k#=4*V$&*>f%?-{pthqlvS;H z@&UylOUMu6k0}+-)Q^-AHO>8zT~ZW_$gS{{Ev!Rckln#(#$?+qOA<xKZtD~tFNDEF zl42y0G7D#%6a${EvJwPz;Fd6U>~f8&os*V*rJd#uh5|=ngRU(Mx=4S!ZKn9Ja%Xec z9FG6UrJ5VsJ?o8@(Y&_$d9h)7S;#8<{irE)#8>S+=R*PK)l=|{%e5hxIillMoB2zb zp@E-T62A$g@!K5mWO(CcV<M}pw3?oV?yBIq@=3@2Z8$RA$!BkOkL*^KoxD+=7lZqZ z-Ia4{*)JHzPO35|r~}}_s?yNm+LOv-wr(-=*Dhf+M)8e~3YBh$s_uw;ydhL?1%(>R z+;31PxN~#%n?2sZpjhfxLoKck3P=(epM*2T*C(dB*n$0fV6uD3d&%E~yf|Sr8)cAk zZ(KHJsGpK|dH~6mQsk&Y0+1c>G}BLo_;=rLoj7!8Qh61_L!NiBe;pA_F8mN_cjjlD zd{3;~Pb`EF>{6*HHr#JlX}+72cJ??sR;}Gd@coLm)%s_=^eVCE-1dZTwyXoQ4dSSD ztc~%W0~zyQWIT6H!)u;UMch1SZbSUw{a<kxH8R2P_B4Mfy@%Av2sOB_%CL`%+Mh2q zo}M)RV)LBM|JTU+awI+>a+@un3f!N}nESB`fHXrG-JTmyK38YeW%JMjVGk_4oCf1C zZyhX#g)%H^0v<O=ryyotcCH=S0m1`RgdhF|qnQ%@NIJP&))Z$ZD|A1$0I~w%sVdz# zY<Fs7n&Yh#i7;wAm}Vzr34J#`YII@MAgd+}Meau)TMB$Mpw_BpM%;6loy8Ar9zE(; z;&5EoNQy}Nk8K36S1)e?I85|uQuq~Hyxti!@Du2InKYiUO#CgS%9*+Z+fL6@6#F)t z)+)d0f(DrLLY7@I^{1Lj=x40z)4p;{HQw^=Qg9=n(L@-5y_K({s+bf!b{0b8B%F)6 z;6sPx99L^_;DSQxd=`R`RS@gxGeIgbVLllS6rHa8gRFVuDM-cpK=5D+xjPT=$SN<) zs(x%6uk}o2nK3uRRz@{^UfBTJ^DhK(a6t;ksi+u3r+Z`n?1=vf8O@b`sZk(URkI&m zk*(ai*bhIMN&y|I^N=#%{2}!Nq&196LAQbh)hVeT>1XtH!H)sSqdoB~2kUA8#2t&5 zgAf0jp3hW?>c*GSr5VyUE1dxM#rr}dyK7Ys4V8YD(%bdleV&pWJgmushFS75tC(?; zkNKWyY)A<MU`%U+fK0Ap{b_U4IQ@Dz-wRis*9Sh&VsaX{5R<2pFVm5pCOT_)UD=y& z0yS?-C#2xc8`vm(OO|ClRr3m6qGOGouWTSwPwq*BOwS)S==LQ3QX>p|?&IDm24XA8 z##RC?s(WFXTx}y9lYm78Xv{w*;9Z8-=Vg@1kGkIk56uwPzwZ5%<%y|Fc{=lb;f=d9 zi$Vc?(N703;=wZ6@eW=2p4RxXdvg}0QLkla%6FQwSq~e}y}sd|%-sfM;QizdL7QDP zRf`f=+HJak+e~}Ak|mZ^Ts%@iw+4d>R4$K(k^9maMPGXrB^yrh`|GOXw~Se9t7|yh zPu<I}eiOvH_c7+z+FEOsGKbZQOPsSz+)mtU9P#mP3>APx)3y{Uapq+{0QsbUlUx*Y z@s6W>^oVzQ0yg&)OQu!Hvfr2rAyTRd4q$%?;c91YUiBp2$94W2+7l`1%qcq0hqn%z zMU9~HUuMwDP2Cn2$Kf^TH*bcioH=nmG22?e7VOcMtYX^99A<QzIZd?t=c*w#YPEN_ z=bzZ^wKEe}Z<_{~c7%v;)LvD^<w6pgh?NUQKB}ydUFK)}qBS9&A0s`yv>_tgTvVcn z(lHdTr+4LYb7Rs<q@Hf{&<Pl{^lBd}^us7w+O?>P_B5wn5MtiF{V1XD{j?ts1)wpn z?W%3=n=*Q!QJ}ncE;NLNhqxG|%2}pf;A$nwP!b6WZ||&2ur;Q*QBVdYy2!VQry!PJ zNt{X6=e52$^Y*}3e)0B33TX-6r8AOH7`T$3X|`&hSQ~Ul*Z0bV+*)8}Sm<Y`es+gN zZw=hj^UI^eLZ2XW<=*qR!OC4my5G0f!&Rw{&5uCUVwdcpQe_%Tf%!YAF$C?G_XM1; z?`SMMknEa0m$M=tSAAT;9y3pdg6ap>>Gby<*Q;2i*A^lX4MzSW->hUT5v>L%Qa>oi zv(1eJ|9s)()1sib7NSIU#q*j&P=j(q9YURCvYiF5mi%9FcjrnKtfR%)u{Ad6<Gr&O z?Th~`t`T|r)-GSz@tqOrD$m!CZr@cIRit$#w$JM{dg@-$#W-*nX$Y0+xNZ{aaDHun zGp~fsNp{s{U$PywTqO5l-VskS$<EqcbQn0oJK^Va&pU-LB7D8%KN=fe=HCl8^()** zY(tc-uCMl(zeFsB=qe!Ay4_MQfvq9)FQAKKLIHf$dHv>yZ^cAaQ%>4OC9Z6^AKrCe z@-aO+ZvQzP_*3o44?FK)mJ3*D7`S;RS{dkngXlgCq8Z7B(kAo<nRx}{4}jqtwNcM3 z$o!;v%97+HeF%-`8_gy=g#?;Wrp;U%o8hRcaCE?W>yO_Aua>v+%X?eDuFz)2Fh1t= z56hi+HBMoh4e27OjsaaA{)`^>YPHGfWO`P?r()r@_O!AL*IDw*NZz0h<CyoMrm7tH z9)D)>>GG?xQ!W1FO`ouUVWdI%NzE%O=IY6w`YrYUWbwZ*haAu5HwtdQsBx5Jz-K3` zihPfn5M}1uxR~ysE)Z{D(3O;+^_)wsKl>vEgBADrO_+`87sl2O>tMo<&^RA!c6#IX zOr?avcrxct&Y!GP>MPLoyY?b_KA1@*#%3*fmcm18r*!KDG`Vzt&4fASQhlS<QkrjA zn4+&2$Hlln^_h#~yw-w$ob?{_^GCgI*VR)iJ<IZq<N-p!<6jF)MJ}$6zCXU$@FS4v zVD-5ELYzm+%tt>MAeC%?IF?vKSv$_@(<e{qi04R_UJv|4_yDx&fbr=4u+iGpXeskK zK#9BMN+#ykFs~ib0aVJ~Zvcl-zt_oCpYx!a+m=>u*vt!?kOLk5F!%nWDPB9O8$kF5 z`<hJl*f^({2e>92GT9C4d%FNii^3_)w3|`TuBuz1dL1=^Sw2sa1lnoI9V+t|6iA6N zr8AJmFuF5-JrlC;@1dPv<1X&8vmo(q(5R82o)a%T3Wc_IRl!G#X#@GNwfr`VN)SqU z+OYu#BYmv!o|5|A!$Aua&d&}Ljc6OAnlktO{xJI@!=q1EI=zWM<5cg@Li;Cd6~@~z zFOlf1^@Y_=DBiS`sK(M-{SCutEJ$qidCo}TN{ik{N_{-3qS31^E>vn)BRWylD}A^J z#Tn6CqJeAmXfZPBxNFDOv9$V{R#iy$Xe`#jT)Va<*WP$jTy4o~>8yaWdP$x|)Wk+8 zZi20=%`8?#PhSFFi0}^G>^5Xp0%VV5?mer$)AB3Fd5e#;CU<Wo9`+=V&;c#-3#8^I z+G4)8r1eM$kg~vUUzL~du_8M@4sq2N#s5IO9ycTv0+<d4Q&YeJGE@4ehU0A}$M|tv zCwR{cKXqx@EpfL;e77<zdD`HwyzEshWQo{N4z1RfWk357G|{cmVB8jNP9@g4#iWTt zupc!Ipn=Cf=Ru620=Mv(o@H*h0Yn#7)e&NJVzQw6NmBG97c=_YEzVe0VKZw_z~u)q zr2I&SUvz^Zb#9YS?lglvJd@<{p!2yif{Lv3GfU&kO|HRmpOt`!FXw_&IBQwt(Q&-w zWe9%&b2@T-J4C^-UvfiEo@)x4Y7v+Y3d_u-%{uzaQ_u?>0gj<mCEhxe%cG)Vxe|$` zJO{bKS1?t-7@Qn4-mlJ`S_ajEtSKrrvP_Rhb;l77<-PUdp=ou{0KeW>)+C(%OLm9+ zGf{E0WQngHa|M{u%xEXP%=TTqG$yFQ;2A)V>RQ;$vbR1Ao+pB?x7#zj<6*T0^L08G zhOUn?vT>>X8$d|6ferK4(<Z46ZdQ@zT}GJ(U4=49xxc2$x@GPDN>}Kkh+V=h_pexR z?j2URmvV>J>M4J*bMtBf!08D1hm83dVw6>3Dk;kNocq6m?lY-Wf@e29Gqui3)wF3y zNV#xHJnTkP(Sn=79^GjV<=pN;UPFdRaB?~g))uPg-xE{=Rv;rFkMLD_Df=WC&kVsY zpq3`+;qz5WLs_-UQMYAp8k1)69h`I_Q9BYDSZDTC#2?#bcE%T0p5Y!?qFa__a=4>e zTp*`$343~O_T7RDVCr^u(>8YhKGbZvXdQ*x%{TJs-SQu-UOyyhCL;q-v-6pnQK_{7 zt1g#3q|>iu4FC9hJnP+lWe<@Bw+#iWf-BOK5r<3y)mj#lfOV9%SGy*QPF<7eER_^q zO7+=z6KfBPp=qmQ=#sdY*j1@2owv}Z)8&bzwtxmYK`RcAg424vB~)WXyFVQ~f{QVn z?!wo`k@=k!_Wen*6MXx&MXeuB>!XK&n#-nw$RFk@>+7CgPEb+Yvrf}0IE7G>f7(^4 z2L)8c;hn6v+TM@6T5@fwZ^P`+=mP|>k8vhL?2>b<)OS2aeHX;|mcRETp7mL#%TGjR z>8is;*41Uqlu=uzVA3ND(^GY$eVyykd|=q*fw5rGO;T!BsTXm!Z|%VSK%j%Is|waQ z($1a7bhlPYJozdEx+)q*=WlXwiN;j&BD!@MDfAu=c^ys!P!91^&fjo{x;Xs1F#KI0 z@b_*-<#`urt>NX@fR8HQf~J>TVuZ{Vla*iJlcAN9@kcqAhN5)fG&S>K_w{84ISN8c zkICg&i=%m2DMWKQ*9RqS;XX^#BD7KiWX?>Q%W^F}EslORV*Go<-%*d}=c_iFPlzDq zs+)KS4SeiNZeUFD%JJp^^SLaXKuD#1;wJGD+MUWh;W*e$uCfPqhrHBxrCTz8tkgyx z#uSL3(8^a-<kT7nYS$*OA9@Yd#~H)GBkP?<pk1dCrxsGmyWK0r-r%F8rp4`D{TM}# z_>eWPJ=i#SFd6|B*~T6nt!7RB^v#u>V1#oxy~d_y1vVWUnTd`{yIL0~43@L!PpJzq zvs0vvtMM}pnlep@Jd0NPkF}zcKll_g5z&N^xD0D+<K8YCwH)OtuqN&y;ugGc`;m7I zbF&zPPPDZBCYUJq5`8dNl&YP>yxso8a1oq9|KXSEZvxg|8M4yi*g=d(#>L@IU){^~ z5rA?iD=f=|Stvlm*Y>!9(0O6#-;Ah#914FwDB{)uB?UK>M~m%pr$;bTBfQJ-b*Mm{ zaK_@C<ET{rT%FB*htB5P*p{%2z=+=J+Ni!<n{CXh#bn)FBpX!^l!9;vj~e{Jk_m@? zU~tCRm@bU|CTItDMqgL8r^4DGwwu9DL|X$>c=@>r11^nDvD~-Dy(`+a{Cc+p`k)bS zz@Qw53E1{YWbzca@NuUE<ympY2=Q%jv;Zg=Q#qFwCl2CO@Q?%>hdm+0qTM8RcF0%8 zDIfwbkGS04TXDLODw5+u&wJBoP48~qAbQI%)6~36Sn}e{2)pmwgrAwf`D*&+NeO30 z{Lq_sF=CsgKobqk5oUmS2u}iiB7dEnJf_qF?e@}iO)WZBZRYEG`#WoEM=N%wipZAN zhAVZ@N<x8R^B-9$4B{4NcRYr<PL+xqkzEf0)W<3;p8B1ng5t#vTB9KM%l{83$-fa9 zf8K5zj~iVGHt3VHTw}xdQ?oO-u&~9bZ+eyHf)fi>w-_^e$2!6l(IfhYo)&<QPO`jW zxcv5U8XaZ<1weAI`mGU&94t{3tyjJyab4<iFg-`2j+{9~lcGO)E1u?m5nRaYOxul- z2d({b%SBZDCOF+9qoc!HZYYo6Qc~Qe3GGTBZmfUfnW9Gl1x)oOEE-G;iw?|eSpG8W znC`_VY|`W<BEt5`5XP+h0faR|-M*+i>Co3*UPUW#5`|gIpWr!lCw%wfwVvz3<F(q7 zlpKFtiX>6DgO-ky=Tt74kG_l3W90KeMH4~so=(PkSfDrGM#g?@R^Y;HIn74nL95wg zjQ?EhTELRBdcr_5F|^9781ONmcnf_39KU2M49VDeW5wY+NOIXjGCb{c$3_SSXe?4X z?Go9@Yl@HT6m)8<7eb8Vi5>s1kU_30$8`?z?q`Df2~-4#$TKs7uvJxKT1Vd7a<eW? zI;AfPi{s+*KYUsc4;iZOi9=RbxW`UDhWJ#@^xuhZufI{;XX$xmm)|j9^3EdtK5G=p z2|j`_Uwcg|&rlGItYt#vV!XRnSL1<2Y}^ma4IbYmiX<LgQrHq0N&eWD20Zt)lF^t} zF)=9*U=4qZDX3P<{?mQgi+4ne+aseRW~9@!x48}Ox1#IxdS8}Ai+xueKQ?U1A6>#Q zLtH55NFH|IxN~=i*nb(*{ERu|Sw~Nq4NhhzfP&|zCbZ_oA_rG!%P9%>@Na^XxS8Q= zY`FSwg5BQ)8y06MF`@flM@GG6qs0*7N}Lxsqf54?4)krnaogVB<9)S@{edU>#xh|H z@hLnke-@j4!uz!y^S8_H@0{@OyW*Ove}bS?H{Du&)^fzgU5-dLCLJ>8b!y{!(@BcL z1!B}}<-(>cznk;BXgfFA;w~n+Y6J^tL5w&|_1@rE$(4(n^8#{)^gX^BOx2Y*xC=BL z1viK{J6PaX%}gefL&=0?QA>(BLnUw34GO#Zk6GKbE`gl^6!e)i^)?OHtb~FulN9t^ z4cghjexZY@o#h|OpT6DRQ}j9V_MdsaYl{v<=Sqh6KGh?JZ_oXqAiOcgY0eMvZY|xQ zuqENMXc-rj+M*X7aiI8c&_*JW`6|HmKrMOT*rL^VuWPk$qEfuO@@lAW(5GgZp0_xp zCJjO1L_{v9b#H*`)jAk=O2XOjZ@$z&t@J++FAfxIU9wzN6qyf3ZVhT%^k?}iV>&-P z6!|X#IFiCyKxA>1oIbI%pyqWb@p6nfHj_f~4M;oaj6B@4#n@uqhwr_QY5<V5>B=bG zd-@QWnS<&_#W@O-JyI1*YLP1YI;y$?Os85E#Q_}W+Ayi}mNSaFqiST|z6jC>(Ub(5 zdR_RtExE5TlP^9a>&i|${*Go0vp?Z$ILo#0K1Pb5$)x!(f1t{LdMWUPK}&w3y&VA( zd7hfm(6n2}%$_XDn(bEe$MyLC8>~_s_ODx1V<Zdd4X8x7qN*(do5Z<3%;Tg&sX5OD zuA8yAq6Hbe(w%mqVBDijDl&z;piSR<DMY)Wj+RW;sBIccx86LK@iP{xtNwolaTEQX F`yckpq;UWM literal 0 HcmV?d00001 diff --git a/navigation/capstone.md b/navigation/capstone.md index 9952a9b836..7d3ec7d55c 100644 --- a/navigation/capstone.md +++ b/navigation/capstone.md @@ -864,6 +864,18 @@ document.addEventListener('DOMContentLoaded', function(){ </div> </div> + <!-- Shoreline Project Outreach (CSP, 2026/2027) --> + <div class="ocs__grid-cell CSP" data-year="2026-2027"> + <a href="{% post_url 2026-09-11-shoreline-volunteer-capstone %}"> + <img src="/images/capstone/shoreline.jpeg" alt="Shoreline Community Services logo" class="ocs__image-frame ocs__image-frame--thumbnail" /> + </a> + <div> + <h3><a href="{% post_url 2026-09-11-shoreline-volunteer-capstone %}">Shoreline Community Services</a></h3> + <p>Extending Shoreline Community Services' outreach through smarter volunteer coordination and easier giving, this capstone project bridges technology and grassroots community care in San Diego.</p> + <p>Team: Vanshika Keswani, Nitya Kasse, Hsu-Cheng Lin</p> + </div> + </div> + <!-- OCS Assignment Tracker (CSA) --> <div class="ocs__grid-cell CSA" data-year="2026-2027"> <a href="{% post_url capstone/2026-09-03-chuds-capstone %}"> From 19f385deff5a7376f702d0b1cae55c7ad4a38fae Mon Sep 17 00:00:00 2001 From: Phantom-deploy <vmalik0609@gmail.com> Date: Wed, 16 Sep 2026 13:46:46 -0700 Subject: [PATCH 17/43] Updated Grids with Placeholders --- _projects/lessons/sass/navigation/grids.md | 347 ++++++++++++--------- 1 file changed, 192 insertions(+), 155 deletions(-) diff --git a/_projects/lessons/sass/navigation/grids.md b/_projects/lessons/sass/navigation/grids.md index 3de326ba1a..2c89448f2c 100644 --- a/_projects/lessons/sass/navigation/grids.md +++ b/_projects/lessons/sass/navigation/grids.md @@ -1,212 +1,249 @@ --- layout: post -title: SASS Grids Grammar -description: Explore the Open Coding Society grid grammar through living examples. +assignment: true +title: OCS Grid Grammar categories: [SASS, Grids] lesson_language: SASS lesson_topic: Grids lesson_part: interactive lesson_type: lesson -microblog: true permalink: /sass/grids/ +author: Aryan M, Raymond L, Pranay K --- -<!-- markdownlint-disable MD033 MD046 --> +## The Core Rule -Hi! My name is [Your Full Name] +Use HTML for content and OCS grid classes for layout. This example shows how OCS classes turn plain divs into a responsive, theme aware grid. -## Learning Grids - -> SASS Grid Mixins examples and code — multiple grid layouts that adapt to the active theme, just like buttons do. - -<div class="ocs__links"> - <a class="ocs__btn" href="{{site.baseurl}}/github/pages/about_sass_buttons/"> - Buttons Lesson - </a> - <a class="ocs__btn" href="https://github.com/Open-Coding-Society/pages/blob/main/_sass/open-coding/mixins/_grid.scss"> - Grid Mixins - </a> - <a class="ocs__btn" href="https://github.com/Open-Coding-Society/pages/blob/main/_sass/open-coding/elements/grids/_main.scss"> - Grid Classes - </a> +```html +<div class="ocs__card"> + <div class="ocs__grid ocs__grid--standard cols-2"> + <div class="ocs__grid-cell">Frontend</div> + <div class="ocs__grid-cell ocs__grid-cell--accent">Backend</div> + </div> </div> +``` + +### Grid Structure + +Every grid is built from the same three layers. + +| Class | Meaning | OCS usage | +| --- | --- | --- | +| `ocs__card` | Framed panel | Wrap a grid so it gets a surface and spacing | +| `ocs__grid` | Grid root | Always the outer element of a grid | +| `ocs__grid--*` | Grid variant | Pick exactly one per grid | +| `ocs__grid-cell` | Grid item | Every direct child of the grid | +| `ocs__grid-cell--*` | Cell modifier | Changes one cell without new CSS | +| `<h3>` | Cell heading | Use for a title inside a card cell | +| `<p>` | Cell text | Use for normal text inside a cell | + +### OCS Grid Grammar + +Use OCS classes to express layout without hardcoded CSS. + +| Rule | Use | +| --- | --- | +| `ocs__grid--standard` | Fixed 3 columns, 2 on mobile | +| `cols-2`, `cols-4` | Change standard grid column count | +| `ocs__grid--card` | Auto fill cards at least 200px wide | +| `cols-3` | Fixed 3 column card grid | +| `ocs__grid--color` | Each cell shows its own color on hover | +| `ocs__grid--holographic` | Cells cycle the rainbow in a wave | +| `ocs__grid--calculator` | 4 column square keypad | +| `ocs__grid--gallery` | Auto fill square tiles | +| `ocs__grid-cell--header` | Spans the full row | +| `ocs__grid-cell--wide` | Spans 2 columns | +| `ocs__grid-cell--accent` | Accent tinted cell | +| `ocs__grid-cell--muted` | Subtle background cell | --- -## Standard Grid +## 1. LxD Cycle Process -> Fixed 3-column grid that collapses to 2 on mobile. Hover on desktop, tap on touch — both give the same visual feedback. +**Empathize:** We noticed students build layouts by hand with inline styles (like `<div style="display:flex; width:33%">`) or made up classes like `my-row`. These layouts break on mobile, ignore the user's theme, and look different on every page. -<div class="ocs__grid ocs__grid--standard" style="margin-bottom: 1.5rem;"> - <div class="ocs__grid-cell ocs__grid-cell--header">Learning Resources</div> - <div class="ocs__grid-cell"> - <strong>JavaScript</strong><br> - Variables, loops, functions, and DOM manipulation. - </div> - <div class="ocs__grid-cell"> - <strong>Python</strong><br> - Data types, control flow, and algorithmic thinking. - </div> - <div class="ocs__grid-cell"> - <strong>Networking</strong><br> - TCP/IP, HTTP, and the OSI model. - </div> - <div class="ocs__grid-cell ocs__grid-cell--accent"> - <strong>SASS</strong><br> - Mixins, variables, and theme-aware styling. - </div> - <div class="ocs__grid-cell"> - <strong>Git</strong><br> - Commits, branches, pull requests. - </div> - <div class="ocs__grid-cell"> - <strong>APIs</strong><br> - REST, fetch, and JSON data handling. - </div> -</div> +**Define:** -**2-column** (`.cols-2`) and **4-column** (`.cols-4`) variants: +* **POV:** CSP students need a reusable way to arrange content in rows and columns because hand written layout CSS breaks on small screens and clashes with the site theme. +* **Learning Goal:** Students will build responsive layouts using only the OCS grid grammar (`ocs__grid`, a variant, `ocs__grid-cell`, and modifiers) instead of custom CSS. -<div class="ocs__grid ocs__grid--standard cols-2" style="margin-bottom: 1rem;"> - <div class="ocs__grid-cell">Frontend</div> - <div class="ocs__grid-cell">Backend</div> -</div> +**Ideate:** -<div class="ocs__grid ocs__grid--standard cols-4" style="margin-bottom: 1.5rem;"> - <div class="ocs__grid-cell">HTML</div> - <div class="ocs__grid-cell">CSS</div> - <div class="ocs__grid-cell">JS</div> - <div class="ocs__grid-cell">SASS</div> -</div> +* **HMW Question:** How might we teach students to trust the OCS grid mixins and stop writing their own layout CSS? +* **Activity:** Refactoring a hand styled layout into clean OCS grid classes that automatically respond to screen size and theme. + +**Prototype & Test:** We taught a trial run to our project team. They said the first homework used too many grid variants at once, so we cut it to two grids: one standard and one calculator (documented below). --- -## Card Grid +## 2. Lesson Plan -> Auto-fill responsive grid — fits as many 200 px cards as possible per row. Cards lift on hover/tap. +**Learning Objective:** By the end of this lesson, you will be able to lay out content with OCS grid classes so it is responsive and theme aware without writing any CSS. -<div class="ocs__grid ocs__grid--card" style="margin-bottom: 1.5rem;"> - <div class="ocs__grid-cell"> - <strong>OCS</strong><br> - Open Coding Society home and resources. - </div> - <div class="ocs__grid-cell"> - <strong>GitHub</strong><br> - Version control for all your projects. - </div> - <div class="ocs__grid-cell"> - <strong>VSCode</strong><br> - Your browser-based development environment. - </div> - <div class="ocs__grid-cell"> - <strong>Code Runner</strong><br> - Execute JavaScript and Python in the browser. - </div> +**Success Criteria:** You can take a hand styled layout, replace it with the correct grid root, variant, cells, and modifiers, and have it match our site's design system on desktop and mobile. + +### Tech Talk (3 minutes) + +We are using a shared SASS grid system. This means **you don't need to write CSS for your layout**. Mixins in `mixins/_grid.scss` already handle columns, gaps, breakpoints, hover, and theme colors. You just pick the class that describes *what kind* of grid you want. + +* **The Rule:** Use OCS grid classes. Let the system handle the layout. +* ✅ **Do this:** `<div class="ocs__grid ocs__grid--standard">` +* ❌ **Don't do this:** `<div style="display:grid; grid-template-columns:1fr 1fr 1fr">` or `<div class="my-row">` + +Why do we do this? It keeps every page consistent, works on phones automatically, and follows the user's color preferences. + +### Code Examples + +#### A. Simple: Standard Grid + +```html +<!-- One root, one variant, and cells. Collapses to 2 columns on mobile. --> +<div class="ocs__grid ocs__grid--standard"> + <div class="ocs__grid-cell">JavaScript</div> + <div class="ocs__grid-cell">Python</div> + <div class="ocs__grid-cell">SASS</div> +</div> +``` + +#### B. Intermediate: Adding Modifiers + +```html +<!-- Modifiers change single cells. cols-4 changes the column count. --> +<div class="ocs__grid ocs__grid--standard cols-4"> + <div class="ocs__grid-cell ocs__grid-cell--header">Web Stack</div> + <div class="ocs__grid-cell">HTML</div> + <div class="ocs__grid-cell">CSS</div> + <div class="ocs__grid-cell ocs__grid-cell--muted">JS</div> + <div class="ocs__grid-cell ocs__grid-cell--accent">SASS</div> +</div> +``` + +#### C. Complex: Full Card Composition + +```html +<!-- Card, then grid, then cells with semantic content inside --> +<div class="ocs__card"> + <h3 class="ocs__section-title">Our Tools</h3> + <div class="ocs__grid ocs__grid--card"> <div class="ocs__grid-cell"> - <strong>Game Runner</strong><br> - Build and play interactive browser games. + <h3>GitHub</h3> + <p class="ocs__card-description">Version control for projects.</p> </div> <div class="ocs__grid-cell"> - <strong>Calculator</strong><br> - The calculator that inspired these grid styles. + <h3>VSCode</h3> + <p class="ocs__card-description">Where we write our code.</p> </div> + </div> </div> +``` --- -## Color Grid +## 3. Hacks & Practice Tasks -> Each box reveals its own unique color on hover or tap. The base state is fully themed; the color appears on interaction. +### Prepare your submission IPYNB -<div class="ocs__grid ocs__grid--color" style="margin-bottom: 1.5rem;"> - <div class="ocs__grid-cell">Red</div> - <div class="ocs__grid-cell">Orange</div> - <div class="ocs__grid-cell">Yellow</div> - <div class="ocs__grid-cell">Chartreuse</div> - <div class="ocs__grid-cell">Green</div> - <div class="ocs__grid-cell">Teal</div> - <div class="ocs__grid-cell">Blue</div> - <div class="ocs__grid-cell">Violet</div> - <div class="ocs__grid-cell">Magenta</div> -</div> +Complete this quick-start flow so you can begin in about 2 minutes. + +1. Create a new notebook in your portfolio homework area: `_notebooks/homework`. +2. Add one markdown cell at the top with the frontmatter below. +3. Add code cells for Popcorn and Homework. Keep the `%%html` and `UI_RUNNER` comment in each code cell. +4. Run each cell and verify the rendered output before submitting. +```raw --- +layout: post +title: OCS Grid Grammar HW +categories: [SASS] +lesson_language: SASS +lesson_topic: Grids HW +lesson_part: interactive +lesson_type: lesson +permalink: /sass/grids-hw +author: githubID +--- +``` -## Holographic Grid +### Submission Safety Rules (Read First) -> All cells are identical but continuously cycle through the rainbow with staggered timing, so the color wave flows across the grid. +> [!IMPORTANT] +> To avoid grading errors, follow these rules exactly: +> +> * Submit only your final grid HTML for each hack. +> * Do not add custom CSS, inline styles, or made up classes. +> * Keep `%%html` and the `UI_RUNNER` comment line in each submission cell. +> * Use only OCS grid grammar for this lesson: `ocs__card`, `ocs__grid`, `ocs__grid--*`, `cols-*`, `ocs__grid-cell`, and `ocs__grid-cell--*`. +> * Use exactly one variant class on each grid. -<div class="ocs__grid ocs__grid--holographic" style="margin-bottom: 1.5rem;"> - <div class="ocs__grid-cell">✦</div> - <div class="ocs__grid-cell">✦</div> - <div class="ocs__grid-cell">✦</div> - <div class="ocs__grid-cell">✦</div> - <div class="ocs__grid-cell">✦</div> - <div class="ocs__grid-cell">✦</div> - <div class="ocs__grid-cell">✦</div> - <div class="ocs__grid-cell">✦</div> - <div class="ocs__grid-cell">✦</div> -</div> +### Popcorn Hack (In-Class) ---- +> [!TIP] +> 2-minute challenge: refactor and run, then paste only your corrected code in chat. + +**Task:** Look at the bad code below. Replace the inline style and custom classes with OCS grid classes and run it with UI_RUNNER. -## Calculator-Style Grid +```html +%%html -> Equal square tiles in a 4-column keypad — same structure as the OCS calculator, fully theme-aware. +<!-- UI_RUNNER: Grids Popcorn Base --> -<div class="ocs__grid ocs__grid--calculator" style="margin-bottom: 1.5rem;"> - <div class="ocs__grid-cell ocs__grid-cell--muted">C</div> - <div class="ocs__grid-cell ocs__grid-cell--muted">+/-</div> - <div class="ocs__grid-cell ocs__grid-cell--muted">%</div> - <div class="ocs__grid-cell ocs__grid-cell--accent">÷</div> +<div style="display: flex;"> + <div class="box">HTML</div> + <div class="box">CSS</div> + <div class="box">JS</div> +</div> +``` + +**Expected direction:** one grid root, one standard variant, and three grid cells. - <div class="ocs__grid-cell">7</div> - <div class="ocs__grid-cell">8</div> - <div class="ocs__grid-cell">9</div> - <div class="ocs__grid-cell ocs__grid-cell--accent">×</div> +### Homework Hack - <div class="ocs__grid-cell">4</div> - <div class="ocs__grid-cell">5</div> - <div class="ocs__grid-cell">6</div> - <div class="ocs__grid-cell ocs__grid-cell--accent">−</div> +**Task:** Refactor the following code block. Remove all inline styles and custom classes and replace them with OCS grid grammar. The first grid should be a standard grid with a full row header and one accent cell. The second should be a calculator grid with an accent key. Run with UI_RUNNER, then submit the clean HTML in your notebook. - <div class="ocs__grid-cell">1</div> - <div class="ocs__grid-cell">2</div> - <div class="ocs__grid-cell">3</div> - <div class="ocs__grid-cell ocs__grid-cell--accent">+</div> +```html +%%html - <div class="ocs__grid-cell ocs__grid-cell--wide">0</div> - <div class="ocs__grid-cell">.</div> - <div class="ocs__grid-cell ocs__grid-cell--accent">=</div> +<!-- UI_RUNNER: Grids Homework Base --> +<div class="my-row"> + <div class="title-box" style="width: 100%;">Team Tools</div> + <div class="tool-card">GitHub</div> + <div class="tool-card">VSCode</div> + <div class="tool-card highlight">SASS</div> </div> +<div style="display: grid; grid-template-columns: repeat(4, 1fr);"> + <div class="key">7</div> + <div class="key">8</div> + <div class="key">9</div> + <div class="key orange">+</div> +</div> +``` --- -## Gallery Grid +## 4. Grading Plan (1 Point Total) -> Auto-fill grid of square tiles for images, icons, or visual content. +### Classroom Rubric -<div class="ocs__grid ocs__grid--gallery" style="margin-bottom: 1.5rem;"> - <div class="ocs__grid-cell ocs__grid-cell--wide"> - <span style="font-size: 2rem;">🐍</span><br>Snake - </div> - <div class="ocs__grid-cell"> - <span style="font-size: 2rem;">🐟</span><br>Fish - </div> - <div class="ocs__grid-cell"> - <span style="font-size: 2rem;">🎮</span><br>Gamify - </div> - <div class="ocs__grid-cell"> - <span style="font-size: 2rem;">🧮</span><br>Calc - </div> - <div class="ocs__grid-cell"> - <span style="font-size: 2rem;">🌐</span><br>Network - </div> - <div class="ocs__grid-cell"> - <span style="font-size: 2rem;">💻</span><br>Code - </div> -</div> +* **0.2 points: Popcorn completion** + Student submitted a grid refactor attempt and kept the code runnable with `%%html`. +* **0.8 points: Homework completion** + * **0.4 grid structure:** Both grids use `ocs__grid`, one variant, and `ocs__grid-cell` on every child. + * **0.3 modifier use:** Converts the title box to `ocs__grid-cell--header` and the highlight to `ocs__grid-cell--accent`. + * **0.1 calculator variant:** Converts the inline grid to `ocs__grid--calculator` with the `+` key as an accent cell. + +### Quick Validation Checklist + +* Present: `%%html` and `UI_RUNNER` comment line. +* Absent: inline style attributes and made up classes like `box`, `my-row`, `tool-card`, or `key`. +* Present: `ocs__grid`, a variant class, and `ocs__grid-cell` in every grid. +* Present: at least one `--header` and one `--accent` modifier. -<br> +--- + +## 5. Lesson Revisions & Feedback Evidence -<!-- markdownlint-enable MD033 MD046 --> +* **Feedback Received:** During our peer practice run, a teammate said the original homework asked for four different grid variants, which took too long and caused confusion about which modifiers work where. +* **Revision Made:** We cut the homework to two grids (standard and calculator) and added a short grammar table at the top. This keeps the task under 10 minutes and focused on the core pattern. + +--- From bdf67fb2e3ac25d24dd05a8283c1db59e3828aaa Mon Sep 17 00:00:00 2001 From: ruhaanb622 <ruhamobile@gmail.com> Date: Wed, 16 Sep 2026 14:19:16 -0700 Subject: [PATCH 18/43] Add starter Python lesson structures --- ...09-15-boolean_scratchers_py_hw_IPYNB_2_.md | 54 +++++++++++++ ...2026-09-15-random_py_sprinters_IPYNB_2_.md | 54 +++++++++++++ .../2026-09-15-boolean_scratchers_py_hw.ipynb | 77 +++++++++++++++++++ .../2026-09-15-random_py_sprinters.ipynb | 77 +++++++++++++++++++ 4 files changed, 262 insertions(+) create mode 100644 _notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md create mode 100644 _notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md create mode 100644 _projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb create mode 100644 _projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb diff --git a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md new file mode 100644 index 0000000000..ff19aa8cc5 --- /dev/null +++ b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md @@ -0,0 +1,54 @@ +--- +layout: post +categories: [Python, Boolean-Expressions] +lesson_language: Python +lesson_topic: Boolean-Expressions +lesson_part: interactive +lesson_type: lesson +codemirror: true +microblog: true +toc: false +comments: false +title: 3.5 Boolean Expressions (PY) +description: Boolean expressions lesson starter. +permalink: /python/boolean/py +authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar +--- + +# 3.5 Boolean Expressions in Python + +## 1. LxD Cycle Process + +### Empathize + +### Define + +### Ideate + +### Prototype & Test + +## 2. Lesson Plan + +### Learning Objective + +### Success Criteria + +### Part 1: Comparisons + +### Part 2: `and`, `or`, and `not` + +### Part 3: Boolean `if` Statements + +## 3. Classwork & Practice Tasks + +### Classwork 1 + +### Classwork 2 + +### Classwork 3 + +### Homework + +## 4. Grading Plan + +## 5. Lesson Revisions & Feedback Evidence diff --git a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md new file mode 100644 index 0000000000..37007572af --- /dev/null +++ b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md @@ -0,0 +1,54 @@ +--- +layout: post +categories: [Python, Random-Values] +lesson_language: Python +lesson_topic: Random-Values +lesson_part: interactive +lesson_type: lesson +codemirror: true +microblog: true +toc: false +comments: false +title: 3.15 Python Random Generator (PY) +description: Python random generator lesson starter. +permalink: /csp/big-idea-3/RandomPY/p3/Lesson +authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar +--- + +# 3.15 Python Random Generator + +## 1. LxD Cycle Process + +### Empathize + +### Define + +### Ideate + +### Prototype & Test + +## 2. Lesson Plan + +### Learning Objective + +### Success Criteria + +### Part 1: Random Integers + +### Part 2: Random Choices + +### Part 3: Random Values in Decisions + +## 3. Classwork & Practice Tasks + +### Classwork 1 + +### Classwork 2 + +### Classwork 3 + +### Homework + +## 4. Grading Plan + +## 5. Lesson Revisions & Feedback Evidence diff --git a/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb b/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb new file mode 100644 index 0000000000..0f7e21c4f4 --- /dev/null +++ b/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb @@ -0,0 +1,77 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "frontmatter", + "metadata": {"vscode": {"languageId": "raw"}}, + "source": [ + "---\n", + "layout: post\n", + "categories: [Python, Boolean-Expressions]\n", + "lesson_language: Python\n", + "lesson_topic: Boolean-Expressions\n", + "lesson_part: interactive\n", + "lesson_type: lesson\n", + "codemirror: true\n", + "microblog: true\n", + "toc: false\n", + "comments: false\n", + "title: 3.5 Boolean Expressions (PY)\n", + "description: Boolean expressions lesson starter.\n", + "permalink: /python/boolean/py\n", + "authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "lesson-structure", + "metadata": {}, + "source": [ + "# 3.5 Boolean Expressions in Python\n", + "\n", + "## 1. LxD Cycle Process\n", + "\n", + "### Empathize\n", + "\n", + "### Define\n", + "\n", + "### Ideate\n", + "\n", + "### Prototype & Test\n", + "\n", + "## 2. Lesson Plan\n", + "\n", + "### Learning Objective\n", + "\n", + "### Success Criteria\n", + "\n", + "### Part 1: Comparisons\n", + "\n", + "### Part 2: `and`, `or`, and `not`\n", + "\n", + "### Part 3: Boolean `if` Statements\n", + "\n", + "## 3. Classwork & Practice Tasks\n", + "\n", + "### Classwork 1\n", + "\n", + "### Classwork 2\n", + "\n", + "### Classwork 3\n", + "\n", + "### Homework\n", + "\n", + "## 4. Grading Plan\n", + "\n", + "## 5. Lesson Revisions & Feedback Evidence" + ] + } + ], + "metadata": { + "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, + "language_info": {"name": "python", "version": "3"} + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb new file mode 100644 index 0000000000..34bcb43bc5 --- /dev/null +++ b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb @@ -0,0 +1,77 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "frontmatter", + "metadata": {"vscode": {"languageId": "raw"}}, + "source": [ + "---\n", + "layout: post\n", + "categories: [Python, Random-Values]\n", + "lesson_language: Python\n", + "lesson_topic: Random-Values\n", + "lesson_part: interactive\n", + "lesson_type: lesson\n", + "codemirror: true\n", + "microblog: true\n", + "toc: false\n", + "comments: false\n", + "title: 3.15 Python Random Generator (PY)\n", + "description: Python random generator lesson starter.\n", + "permalink: /csp/big-idea-3/RandomPY/p3/Lesson\n", + "authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "lesson-structure", + "metadata": {}, + "source": [ + "# 3.15 Python Random Generator\n", + "\n", + "## 1. LxD Cycle Process\n", + "\n", + "### Empathize\n", + "\n", + "### Define\n", + "\n", + "### Ideate\n", + "\n", + "### Prototype & Test\n", + "\n", + "## 2. Lesson Plan\n", + "\n", + "### Learning Objective\n", + "\n", + "### Success Criteria\n", + "\n", + "### Part 1: Random Integers\n", + "\n", + "### Part 2: Random Choices\n", + "\n", + "### Part 3: Random Values in Decisions\n", + "\n", + "## 3. Classwork & Practice Tasks\n", + "\n", + "### Classwork 1\n", + "\n", + "### Classwork 2\n", + "\n", + "### Classwork 3\n", + "\n", + "### Homework\n", + "\n", + "## 4. Grading Plan\n", + "\n", + "## 5. Lesson Revisions & Feedback Evidence" + ] + } + ], + "metadata": { + "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, + "language_info": {"name": "python", "version": "3"} + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file From 293ad3e9abe15757abb5d0fa7226ee843521a881 Mon Sep 17 00:00:00 2001 From: ruhaanb622 <ruhamobile@gmail.com> Date: Wed, 16 Sep 2026 14:28:46 -0700 Subject: [PATCH 19/43] Remove old Python lesson files --- ...2025-09-23-random_py_sprinters_IPYNB_2_.md | 559 --------------- ...10-02-boolean_scratchers_py_hw_IPYNB_2_.md | 88 --- .../2025-09-23-random_py_sprinters.ipynb | 669 ------------------ .../2025-10-02-boolean_scratchers_py_hw.ipynb | 195 ----- 4 files changed, 1511 deletions(-) delete mode 100644 _notebooks/2025-09-23-random_py_sprinters_IPYNB_2_.md delete mode 100644 _notebooks/2025-10-02-boolean_scratchers_py_hw_IPYNB_2_.md delete mode 100644 _projects/lessons/python/notebooks/2025-09-23-random_py_sprinters.ipynb delete mode 100644 _projects/lessons/python/notebooks/2025-10-02-boolean_scratchers_py_hw.ipynb diff --git a/_notebooks/2025-09-23-random_py_sprinters_IPYNB_2_.md b/_notebooks/2025-09-23-random_py_sprinters_IPYNB_2_.md deleted file mode 100644 index bfe9a74b61..0000000000 --- a/_notebooks/2025-09-23-random_py_sprinters_IPYNB_2_.md +++ /dev/null @@ -1,559 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Random-Values'] -lesson_language: Python -lesson_topic: Random-Values -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.15 Random Numbers (py) -description: Random Numbers in Python -breadcrumbs: True -permalink: /csp/big-idea-3/RandomPY/p3/Lesson -authors: Rudra J, Darshan S. ---- - -<style> -/* 🌌 Full Page Background */ -body { - background: linear-gradient(-45deg, #000000, #001100, #003300, #000000); - background-size: 400% 400%; - animation: bgMove 18s ease infinite; - color: #e6ffe6; - font-family: "Segoe UI", sans-serif; - margin: 0; - padding: 0; -} -@keyframes bgMove { - 0% { background-position: 0% 50%; } - 50% { background-position: 100% 50%; } - 100% { background-position: 0% 50%; } -} - -/* 🎲 Python Lesson Box */ -.py-lesson { - background: linear-gradient(135deg, #0a0f0a, #001a00, #002b00); - border: 2px solid #00ff88; - border-radius: 12px; - padding: 25px; - margin: 25px auto; - max-width: 900px; - font-family: "Segoe UI", sans-serif; - color: #e6ffe6; - box-shadow: 0 0 25px rgba(0, 255, 136, 0.5); - line-height: 1.7em; -} - -.py-lesson h1 { - font-size: 2.2em; - color: #00ff88; - text-shadow: 0 0 12px rgba(0,255,136,0.9); - margin-bottom: 15px; -} - -.py-lesson h2 { - color: #66ffcc; - text-shadow: 0 0 8px rgba(102,255,204,0.8); - margin-top: 15px; -} - -.py-lesson code { - background: #001100; - padding: 2px 6px; - border-radius: 5px; - color: #00ff88; - font-family: "Courier New", monospace; -} -</style> - -<div class="py-lesson"> - <h1>🎲 Random Numbers</h1> - - <h2>The Random Module</h2> - <p> - To make anything random in Python, you need a module called <code>random</code>. - This module must be imported into your script beforehand like this: - </p> -</div> - - - -```python -import random -``` - -<style> -/* 🪄 Spellbook Background */ -body { - background: linear-gradient(-45deg, #000000, #0a0f0a, #001a00, #000000); - background-size: 400% 400%; - animation: bgFlow 20s ease infinite; - color: #e6ffe6; - font-family: "Segoe UI", serif; - margin: 0; - padding: 0; -} -@keyframes bgFlow { - 0% { background-position: 0% 50%; } - 50% { background-position: 100% 50%; } - 100% { background-position: 0% 50%; } -} - -/* 📖 Spellbook Section */ -.spellbook { - background: linear-gradient(145deg, #0b0f0b, #001a00, #003300); - border: 2px solid #00ff88; - border-radius: 15px; - padding: 30px; - margin: 30px auto; - max-width: 900px; - font-family: "Garamond", "Georgia", serif; - color: #e6ffe6; - box-shadow: 0 0 30px rgba(0, 255, 136, 0.6); - line-height: 1.8em; -} - -/* ✨ Spellbook Headings */ -.spellbook h1 { - font-size: 2.4em; - color: #00ff88; - text-shadow: 0 0 15px rgba(0,255,136,1); - margin-bottom: 20px; - font-family: "Cinzel Decorative", serif; -} - -.spellbook h2 { - color: #66ffcc; - text-shadow: 0 0 10px rgba(102,255,204,0.9); - margin-top: 20px; - font-family: "Cinzel Decorative", serif; -} - -/* 🔮 Inline code = glowing runes */ -.spellbook code { - background: #001100; - padding: 3px 7px; - border-radius: 6px; - color: #00ff88; - font-family: "Courier New", monospace; - text-shadow: 0 0 6px rgba(0,255,136,0.8); -} -</style> - -<div class="spellbook"> - <h1>📖 The Spellbook of Randomness</h1> - - <p> - Think of this as a <b>spellbook</b>! Every Python spell must derive from the spellbook. - In this case, that spellbook we need is <code>random</code>. - </p> - - <h2>🔮 A Basic Number Generator</h2> - <p> - Let’s analyze the following generator: - </p> -</div> - - - -```python -import random -# Generate a random integer between 1 and 10 (inclusive) -random_integer = random.randint(1, 10) -print(f"Random Integer: {random_integer}") -``` - - Random Integer: 2 - - -<style> -/* 📜 Spell Explanation Box */ -.incantation { - background: linear-gradient(135deg, #0a0a0a, #001000, #002200); - border: 2px solid #00ff88; - border-radius: 10px; - padding: 20px; - margin: 20px 0; - font-family: "Courier New", monospace; - color: #e6ffe6; - box-shadow: 0 0 15px rgba(0,255,136,0.5); - line-height: 1.6em; -} - -.incantation code { - color: #00ff88; - font-weight: bold; - text-shadow: 0 0 6px rgba(0,255,136,0.9); -} - -.spellbook h2 { - color: #66ffcc; - text-shadow: 0 0 10px rgba(102,255,204,0.9); - margin-top: 20px; - font-family: "Cinzel Decorative", serif; -} -</style> - -<div class="spellbook"> - - <div class="incantation"> - <p><code>import random</code>: Allows us to access the random module</p> - <p><code>random_integer</code>: This is our variable to hold the number we generate</p> - <p><code>random.randint(1,10)</code>: This basically says “from the random module, use the <b>randint</b> function and use parameters 1 and 10.” - Randint is the function used to determine a random integer in a range. In this case, that range is 1 and 10.</p> - <p><code>print(f"Random Integer: {random_integer}")</code>: Prints the number</p> - </div> - - <h2>✨ Another Type of Generator</h2> - <p>Let’s look at one more generator:</p> - -</div> - - - -```python -import random -# Generate a random float between 0 and 1 (inclusive) -random_float = random.uniform(0, 1) -print(f"Random Float: {random_float}") -``` - - Random Float: 0.1742626429831371 - - -<style> -/* 📜 Comparison Scroll */ -.scroll { - background: linear-gradient(135deg, #0b0b0b, #001100, #002200); - border: 2px solid #00ff88; - border-radius: 12px; - padding: 20px; - margin: 25px auto; - max-width: 900px; - font-family: "Georgia", serif; - color: #e6ffe6; - box-shadow: 0 0 20px rgba(0,255,136,0.4); - line-height: 1.7em; -} - -.scroll h2 { - color: #66ffcc; - text-shadow: 0 0 10px rgba(102,255,204,0.9); - font-family: "Cinzel Decorative", serif; - margin-bottom: 10px; -} - -.scroll strong { - color: #00ff88; - text-shadow: 0 0 6px rgba(0,255,136,0.7); -} - -/* 🪄 Hacks Section */ -.hacks { - background: linear-gradient(135deg, #0a0000, #220000, #330000); - border: 2px solid #ff4d4d; - border-radius: 12px; - padding: 20px; - margin: 25px auto; - max-width: 900px; - font-family: "Georgia", serif; - color: #ffeaea; - box-shadow: 0 0 25px rgba(255,0,0,0.5); - line-height: 1.7em; -} - -.hacks h2 { - color: #ff4d4d; - text-shadow: 0 0 12px rgba(255,77,77,0.9); - font-family: "Cinzel Decorative", serif; - margin-bottom: 10px; -} -</style> - -<div class="scroll"> - <h2>📜 Before We Begin: Types of Random</h2> - - <p><strong>Randint</strong>: - - What it does: Picks a whole number between two values, with equal chance for each. - - Distribution type: <b>Discrete</b> uniform distribution.</p> - - <p><strong>Uniform</strong>: - - What it does: Picks a decimal (float) between two numbers, again with equal chance for every value in that range. - - Distribution type: <b>Continuous</b> uniform distribution.</p> - - <p><strong>Normalvariate</strong>: - - What it does: Picks a number where values near the average (mean) are more likely, and extreme values are rare. - - Distribution type: <b>Normal</b> (bell curve).</p> - - <p>This code right here uses <b>Uniform</b>. It needs to pick a <b>float</b> or <b>decimal</b> and the <b>Uniform</b> function works best when dealing with decimals between 2 numbers with equal chance to roll it.</p> -</div> - -<div class="hacks"> - <h2>🪄 Hacks!</h2> - <p>Here are a few challenges you can try making with the concept of RNG in Python:</p> - <ol> - <li>🎲 Dice or Lottery Numbers</li> - <li>📏 Random Decimal Precision</li> - <li>🔀 Random Shuffle with Numbers</li> - </ol> -</div> - - - -<html lang="en"> -<head> - <meta charset="UTF-8"> - <title>Learn About Random Module & RNG - - - - -

Learn the Random Module & Try RNGs

- -
-

About Python’s random Module

-

The random module in Python is used to generate random numbers. Some key functions include:

-
    -
  • random(): Returns a float between 0.0 and 1.0.
  • -
  • randint(a, b): Returns an integer between a and b (inclusive).
  • -
  • uniform(a, b): Returns a float between a and b.
  • -
  • choice(seq): Returns a random element from a sequence.
  • -
-
- -
-

Generate Random Float (0.0 – 1.0)

- -
-
- -
-

Generate Random Integer (randint(a, b))

- - -
- -
-
- -
-

Generate Random Float in Range (uniform(a, b))

- - -
- -
-
- - - - - - - - - -
-

🧪 Extra Demos (Python)

-

- Below are small, self-contained Python snippets you can run inside the notebook. - They use the standard random module and a tiny seeded helper so results can be reproduced for tests. -

-
- - - -```python -# Seeded RNG helper using random.Random (reproducible) -from random import Random, choices, randint, shuffle, uniform, gauss - -def make_rng(seed): - return Random(seed) - -rng = make_rng(42) -print('rng sample floats:', [rng.random() for _ in range(3)]) - -``` - - -```python -# Two-dice simulation and heatmap (counts for face1 vs face2) -import numpy as np -import matplotlib.pyplot as plt -from random import Random - -def two_dice_heatmap(trials=10000, seed=1): - rng = Random(seed) - grid = np.zeros((6,6), dtype=int) - for _ in range(trials): - a = rng.randint(1,6) - 1 - b = rng.randint(1,6) - 1 - grid[a,b] += 1 - return grid - -g = two_dice_heatmap(5000, seed=7) -print(g) -# If matplotlib is available, show a simple heatmap (optional) -try: - plt.imshow(g, cmap='viridis') - plt.colorbar() - plt.title('Two-dice frequency heatmap (face1 x face2)') - plt.xlabel('Die 2 face (1-6)') - plt.ylabel('Die 1 face (1-6)') - plt.show() -except Exception as e: - print('matplotlib display skipped:', e) - -``` - - -```python -# Loot box simulator (with adjustable probabilities) -from random import Random - -def simulate_loot(n=1000, seed=0, pool=None): - if pool is None: - pool = [('Common',0.7), ('Rare',0.25), ('Epic',0.045), ('Legendary',0.005)] - rng = Random(seed) - names = [p[0] for p in pool] - weights = [p[1] for p in pool] - counts = {name:0 for name in names} - for _ in range(n): - pick = rng.random() - s = 0 - for name,w in zip(names, weights): - s += w - if pick < s: counts[name] += 1; break - return counts - -print(simulate_loot(1000, seed=42)) - -``` - - -```python -# Seeded shuffle and reproducible playlist example -from random import Random - -def seeded_shuffle(arr, seed): - rng = Random(seed) - a = list(arr) - rng.shuffle(a) - return a - -songs = ['Song A','Song B','Song C','Song D','Song E'] -print('seed=1:', seeded_shuffle(songs,1)) -print('seed=1 again:', seeded_shuffle(songs,1)) -print('seed=2:', seeded_shuffle(songs,2)) - -``` diff --git a/_notebooks/2025-10-02-boolean_scratchers_py_hw_IPYNB_2_.md b/_notebooks/2025-10-02-boolean_scratchers_py_hw_IPYNB_2_.md deleted file mode 100644 index 732d9e4c02..0000000000 --- a/_notebooks/2025-10-02-boolean_scratchers_py_hw_IPYNB_2_.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Boolean-Expressions'] -lesson_language: Python -lesson_topic: Boolean-Expressions -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.5 Boolean Expressions (PY) -description: Boolean Hacks For Students To Try In Python -permalink: /python/boolean/py ---- - -# 🔑 Boolean Hacks in Python: A Few New Codes! - -This notebook has short Boolean challenges. Edit the code where it says `TODO` to make it work. - -## Challenge 1: Positive Number -Fix the condition so it prints `num is positive` if the number is greater than 0. - - -```python -num = 3 # Try changing this number! - -# TODO: change the condition -if num < 0: # <-- wrong, fix this - print(num, "is positive") -else: - print(num, "is NOT positive") -``` - - 3 is NOT positive - - -## Challenge 2: Is Even? -Change the condition so it prints `num is even` when the number is divisible by 2. - - -```python -num = 7 - -# TODO: check if num is even -if num % 2 == 0: # <-- not correct - print(num, "is even") -else: - print(num, "is odd") -``` - - 7 is odd - - -## Challenge 3: Teenager Check -Print `Teenager` if age is between 13 and 19 (inclusive). Otherwise print `Not Teenager`. Fix the condition. - - -```python -age = 20 - -# TODO: fix the condition -if age > 12 and age < 20: # <-- wrong - print("Teenager") -else: - print("Not Teenager") -``` - - Not Teenager - - -## Challenge 4: Lamp Logic -We have two switches: `a` and `b`. The lamp should turn ON if **at least one** is True. - -Fix the condition. - - -```python -a, b = True, False - -# TODO: fix condition for at least one True -if a or b: # <-- wrong - print("Lamp is ON") -else: - print("Lamp is OFF") -``` - - Lamp is ON - diff --git a/_projects/lessons/python/notebooks/2025-09-23-random_py_sprinters.ipynb b/_projects/lessons/python/notebooks/2025-09-23-random_py_sprinters.ipynb deleted file mode 100644 index d12bb305f5..0000000000 --- a/_projects/lessons/python/notebooks/2025-09-23-random_py_sprinters.ipynb +++ /dev/null @@ -1,669 +0,0 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "id": "cb3b4231", - "metadata": { - "vscode": { - "languageId": "yaml" - } - }, - "outputs": [], - "source": [ - "---\n", - "layout: post\n", - "categories: [Python, Random-Values]\n", - "lesson_language: Python\n", - "lesson_topic: Random-Values\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "toc: false\n", - "comments: false\n", - "title: 3.15 Random Numbers (py)\n", - "description: Random Numbers in Python\n", - "breadcrumbs: True\n", - "permalink: /csp/big-idea-3/RandomPY/p3/Lesson\n", - "authors: Rudra J, Darshan S.\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "93583304", - "metadata": {}, - "source": [ - "\n", - "\n", - "
\n", - "

🎲 Random Numbers

\n", - "\n", - "

The Random Module

\n", - "

\n", - " To make anything random in Python, you need a module called random. \n", - " This module must be imported into your script beforehand like this:\n", - "

\n", - "
\n" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "fd064aad", - "metadata": {}, - "outputs": [], - "source": [ - "import random" - ] - }, - { - "cell_type": "markdown", - "id": "aef52b84", - "metadata": {}, - "source": [ - "\n", - "\n", - "
\n", - "

📖 The Spellbook of Randomness

\n", - " \n", - "

\n", - " Think of this as a spellbook! Every Python spell must derive from the spellbook. \n", - " In this case, that spellbook we need is random.\n", - "

\n", - "\n", - "

🔮 A Basic Number Generator

\n", - "

\n", - " Let’s analyze the following generator:\n", - "

\n", - "
\n" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "b924aacc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Random Integer: 2\n" - ] - } - ], - "source": [ - "import random\n", - "# Generate a random integer between 1 and 10 (inclusive)\n", - "random_integer = random.randint(1, 10)\n", - "print(f\"Random Integer: {random_integer}\")" - ] - }, - { - "cell_type": "markdown", - "id": "55ec718a", - "metadata": {}, - "source": [ - "\n", - "\n", - "
\n", - "\n", - "
\n", - "

import random: Allows us to access the random module

\n", - "

random_integer: This is our variable to hold the number we generate

\n", - "

random.randint(1,10): This basically says “from the random module, use the randint function and use parameters 1 and 10.” \n", - " Randint is the function used to determine a random integer in a range. In this case, that range is 1 and 10.

\n", - "

print(f\"Random Integer: {random_integer}\"): Prints the number

\n", - "
\n", - "\n", - "

✨ Another Type of Generator

\n", - "

Let’s look at one more generator:

\n", - "\n", - "
\n" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "95fc0b98", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Random Float: 0.1742626429831371\n" - ] - } - ], - "source": [ - "import random\n", - "# Generate a random float between 0 and 1 (inclusive)\n", - "random_float = random.uniform(0, 1)\n", - "print(f\"Random Float: {random_float}\")" - ] - }, - { - "cell_type": "markdown", - "id": "d35735ec", - "metadata": {}, - "source": [ - "\n", - "\n", - "
\n", - "

📜 Before We Begin: Types of Random

\n", - "\n", - "

Randint: \n", - " - What it does: Picks a whole number between two values, with equal chance for each. \n", - " - Distribution type: Discrete uniform distribution.

\n", - "\n", - "

Uniform: \n", - " - What it does: Picks a decimal (float) between two numbers, again with equal chance for every value in that range. \n", - " - Distribution type: Continuous uniform distribution.

\n", - "\n", - "

Normalvariate: \n", - " - What it does: Picks a number where values near the average (mean) are more likely, and extreme values are rare. \n", - " - Distribution type: Normal (bell curve).

\n", - "\n", - "

This code right here uses Uniform. It needs to pick a float or decimal and the Uniform function works best when dealing with decimals between 2 numbers with equal chance to roll it.

\n", - "
\n", - "\n", - "
\n", - "

🪄 Hacks!

\n", - "

Here are a few challenges you can try making with the concept of RNG in Python:

\n", - "
    \n", - "
  1. 🎲 Dice or Lottery Numbers
  2. \n", - "
  3. 📏 Random Decimal Precision
  4. \n", - "
  5. 🔀 Random Shuffle with Numbers
  6. \n", - "
\n", - "
\n" - ] - }, - { - "cell_type": "markdown", - "id": "2323a0e5", - "metadata": {}, - "source": [ - "\n", - "\n", - "\n", - " \n", - " Learn About Random Module & RNG\n", - " \n", - "\n", - "\n", - "\n", - "

Learn the Random Module & Try RNGs

\n", - "\n", - "
\n", - "

About Python’s random Module

\n", - "

The random module in Python is used to generate random numbers. Some key functions include:

\n", - "
    \n", - "
  • random(): Returns a float between 0.0 and 1.0.
  • \n", - "
  • randint(a, b): Returns an integer between a and b (inclusive).
  • \n", - "
  • uniform(a, b): Returns a float between a and b.
  • \n", - "
  • choice(seq): Returns a random element from a sequence.
  • \n", - "
\n", - "
\n", - "\n", - "
\n", - "

Generate Random Float (0.0 – 1.0)

\n", - " \n", - "
\n", - "
\n", - "\n", - "
\n", - "

Generate Random Integer (randint(a, b))

\n", - " \n", - " \n", - "
\n", - " \n", - "
\n", - "
\n", - "\n", - "
\n", - "

Generate Random Float in Range (uniform(a, b))

\n", - " \n", - " \n", - "
\n", - " \n", - "
\n", - "
\n", - "\n", - " \n", - "\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "749f380a", - "metadata": {}, - "source": [ - "\n", - "\n", - "
\n", - "

🧪 Extra Demos (Python)

\n", - "

\n", - " Below are small, self-contained Python snippets you can run inside the notebook. \n", - " They use the standard random module and a tiny seeded helper so results can be reproduced for tests.\n", - "

\n", - "
\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "22ef88c1", - "metadata": {}, - "outputs": [], - "source": [ - "# Seeded RNG helper using random.Random (reproducible)\n", - "from random import Random, choices, randint, shuffle, uniform, gauss\n", - "\n", - "def make_rng(seed):\n", - " return Random(seed)\n", - "\n", - "rng = make_rng(42)\n", - "print('rng sample floats:', [rng.random() for _ in range(3)])\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ba1c8a5f", - "metadata": {}, - "outputs": [], - "source": [ - "# Two-dice simulation and heatmap (counts for face1 vs face2)\n", - "import numpy as np\n", - "import matplotlib.pyplot as plt\n", - "from random import Random\n", - "\n", - "def two_dice_heatmap(trials=10000, seed=1):\n", - " rng = Random(seed)\n", - " grid = np.zeros((6,6), dtype=int)\n", - " for _ in range(trials):\n", - " a = rng.randint(1,6) - 1\n", - " b = rng.randint(1,6) - 1\n", - " grid[a,b] += 1\n", - " return grid\n", - "\n", - "g = two_dice_heatmap(5000, seed=7)\n", - "print(g)\n", - "# If matplotlib is available, show a simple heatmap (optional)\n", - "try:\n", - " plt.imshow(g, cmap='viridis')\n", - " plt.colorbar()\n", - " plt.title('Two-dice frequency heatmap (face1 x face2)')\n", - " plt.xlabel('Die 2 face (1-6)')\n", - " plt.ylabel('Die 1 face (1-6)')\n", - " plt.show()\n", - "except Exception as e:\n", - " print('matplotlib display skipped:', e)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bdc71b91", - "metadata": {}, - "outputs": [], - "source": [ - "# Loot box simulator (with adjustable probabilities)\n", - "from random import Random\n", - "\n", - "def simulate_loot(n=1000, seed=0, pool=None):\n", - " if pool is None:\n", - " pool = [('Common',0.7), ('Rare',0.25), ('Epic',0.045), ('Legendary',0.005)]\n", - " rng = Random(seed)\n", - " names = [p[0] for p in pool]\n", - " weights = [p[1] for p in pool]\n", - " counts = {name:0 for name in names}\n", - " for _ in range(n):\n", - " pick = rng.random()\n", - " s = 0\n", - " for name,w in zip(names, weights):\n", - " s += w\n", - " if pick < s: counts[name] += 1; break\n", - " return counts\n", - "\n", - "print(simulate_loot(1000, seed=42))\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "468e8cf4", - "metadata": {}, - "outputs": [], - "source": [ - "# Seeded shuffle and reproducible playlist example\n", - "from random import Random\n", - "\n", - "def seeded_shuffle(arr, seed):\n", - " rng = Random(seed)\n", - " a = list(arr)\n", - " rng.shuffle(a)\n", - " return a\n", - "\n", - "songs = ['Song A','Song B','Song C','Song D','Song E']\n", - "print('seed=1:', seeded_shuffle(songs,1))\n", - "print('seed=1 again:', seeded_shuffle(songs,1))\n", - "print('seed=2:', seeded_shuffle(songs,2))\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.12.3" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/_projects/lessons/python/notebooks/2025-10-02-boolean_scratchers_py_hw.ipynb b/_projects/lessons/python/notebooks/2025-10-02-boolean_scratchers_py_hw.ipynb deleted file mode 100644 index 67dd0220e3..0000000000 --- a/_projects/lessons/python/notebooks/2025-10-02-boolean_scratchers_py_hw.ipynb +++ /dev/null @@ -1,195 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "ae51c009", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Python, Boolean-Expressions]\n", - "lesson_language: Python\n", - "lesson_topic: Boolean-Expressions\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "toc: false\n", - "comments: false\n", - "title: 3.5 Boolean Expressions (PY)\n", - "description: Boolean Hacks For Students To Try In Python\n", - "permalink: /python/boolean/py\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "b100cb48", - "metadata": {}, - "source": [ - "# 🔑 Boolean Hacks in Python: A Few New Codes!\n", - "\n", - "This notebook has short Boolean challenges. Edit the code where it says `TODO` to make it work." - ] - }, - { - "cell_type": "markdown", - "id": "1a047e65", - "metadata": {}, - "source": [ - "## Challenge 1: Positive Number\n", - "Fix the condition so it prints `num is positive` if the number is greater than 0." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "dfeb6542", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "3 is NOT positive\n" - ] - } - ], - "source": [ - "num = 3 # Try changing this number!\n", - "\n", - "# TODO: change the condition\n", - "if num < 0: # <-- wrong, fix this\n", - " print(num, \"is positive\")\n", - "else:\n", - " print(num, \"is NOT positive\")" - ] - }, - { - "cell_type": "markdown", - "id": "60856dbd", - "metadata": {}, - "source": [ - "## Challenge 2: Is Even?\n", - "Change the condition so it prints `num is even` when the number is divisible by 2." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "088eec27", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "7 is odd\n" - ] - } - ], - "source": [ - "num = 7\n", - "\n", - "# TODO: check if num is even\n", - "if num % 2 == 0: # <-- not correct\n", - " print(num, \"is even\")\n", - "else:\n", - " print(num, \"is odd\")" - ] - }, - { - "cell_type": "markdown", - "id": "030a2f2f", - "metadata": {}, - "source": [ - "## Challenge 3: Teenager Check\n", - "Print `Teenager` if age is between 13 and 19 (inclusive). Otherwise print `Not Teenager`. Fix the condition." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "d0d9e37c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Not Teenager\n" - ] - } - ], - "source": [ - "age = 20\n", - "\n", - "# TODO: fix the condition\n", - "if age > 12 and age < 20: # <-- wrong\n", - " print(\"Teenager\")\n", - "else:\n", - " print(\"Not Teenager\")" - ] - }, - { - "cell_type": "markdown", - "id": "6e1a1124", - "metadata": {}, - "source": [ - "## Challenge 4: Lamp Logic\n", - "We have two switches: `a` and `b`. The lamp should turn ON if **at least one** is True.\n", - "\n", - "Fix the condition." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "814b8f63", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Lamp is ON\n" - ] - } - ], - "source": [ - "a, b = True, False\n", - "\n", - "# TODO: fix condition for at least one True\n", - "if a or b: # <-- wrong\n", - " print(\"Lamp is ON\")\n", - "else:\n", - " print(\"Lamp is OFF\")" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "venv (3.13.7)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.13.7" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} From 65fe563798c6ce08caea4f3563313469236c8f02 Mon Sep 17 00:00:00 2001 From: Rydenb Date: Wed, 16 Sep 2026 18:15:26 -0700 Subject: [PATCH 20/43] create 3.14 libraries lesson --- .../2026-09-16-libraries_python.ipynb | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 _projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb diff --git a/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb b/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb new file mode 100644 index 0000000000..830db5d35f --- /dev/null +++ b/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb @@ -0,0 +1,42 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "layout: post\n", + "categories: [Python, Libraries]\n", + "lesson_language: Python\n", + "lesson_topic: Libraries\n", + "lesson_part: interactive\n", + "lesson_type: lesson\n", + "codemirror: true\n", + "microblog: true\n", + "toc: false\n", + "title: 3.14 Libraries\n", + "description: Learn how to import and use Python libraries (modules).\n", + "permalink: /python/libraries\n", + "type: lesson\n", + "---" + ], + "id": "096a1e6e" + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 44d18b57bdcc36f1868a5a1fc3f6107d998e0c2d Mon Sep 17 00:00:00 2001 From: samanviy17-crypto Date: Wed, 16 Sep 2026 18:27:09 -0700 Subject: [PATCH 21/43] Update lesson 3.12 Calling Procedures --- ...ing_procedures_remakers_lesson_IPYNB_2_.md | 270 +++++++++++++----- 1 file changed, 204 insertions(+), 66 deletions(-) diff --git a/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md b/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md index 4f491c74b0..013eec76e9 100644 --- a/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md +++ b/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md @@ -11,106 +11,244 @@ comments: False title: 3.12 Calling Procedures description: 3.12 Calling Procedures permalink: /csp/big-idea-3/calling-procedures/p4/lesson -author: Sathwik Kintada +author: Samanvi Yachareni, Joan Kim, Ainsley Albert +date: 2026-09-16 --- -## 3.12 Calling Procedures +### 3.12 Calling Procedures -Every morning you brush your teeth, wash your face, and eat breakfast. You don’t rewrite those steps every day — you just do them. That’s what calling a procedure is: you already have the steps (the function), and you just call it whenever you need it. +Every time you send a text message, your phone encodes the characters, transmits a wireless signal to a cell tower, and routes it to your friend. You don’t route network packets by hand — you just press send. That’s calling a procedure: the steps are saved, and you run them whenever you need them. -What is it? -- A procedure is a reusable group of instructions. -- Also called a function in Python or JavaScript. -- Procedures allow you to avoid rewriting the same code. -What does it mean? -- Calling a procedure means telling the computer to run the instructions in that procedure. -- You can call a procedure multiple times with different input values without rewriting it. -- This is different from defining the procedure — defining is creating it, calling is using it. +**What is calling a procedure?** +A procedure (a function in Python) is a named set of re-usable code instructions. +- You can call a procedure multiple times with different input values without having to rewrite it +- Different from defining the procedure: defining is creating it, calling is using it +- Calling allows you to run the same set of instructions whenever you need them without rewriting the lines of code. +**Passing Inputs (Parameters)** +You can make procedures more flexible by giving them parameters—input variables that hold data passed into the procedure when you call it. -Python Example: -- Use def to define a procedure -- You can use the name of the functionand paranthesis after to call it +- Parameters act as temporary placeholders inside the procedure definition. +- Arguments are the actual values you send into the procedure when you call it. +This allows a single procedure to run the same set of instructions on completely different data without rewriting the code. +Python Example: -```python -# Define a procedure -def show_message(): - print("Welcome to the program!") +- Use def to define the function/procedure +- To call a procedure write the name of the procedure followed by parenthesis, and variables if included -# Call the procedure -show_message() # Output: Welcome to the program! ``` +# 1. DEFINE the procedure with a parameter (variable input) +def send_notification(username): + print("New message for " + username + "!") - Welcome to the program! +# 2. CALL the procedure passing different inputs +send_notification("Joan") +``` +**Calling Procedures Inside Procedures (Decomposition)** +In computer science, large problems are broken down into smaller steps—a process called decomposition. You can call a helper procedure inside an outer procedure to handle a specific part of a task. Each step can become its own procedure, and one procedure can call another one. This allows programs to become easier to read, use, and debug. -Javascript Example: -- You use function to define a procedure -- Just like python if you type the name of the function with parenthesis right after it, you can call the procedure +Python Example: +``` +# Helper procedure: Calculates the final price with sales tax +def calculate_tax(price): + return price * 1.07 -```javascript -%%js -// Define a procedure -function showMessage() { - console.log("Welcome to the program!"); -} +# Outer procedure: Handles the checkout process +def checkout(item_name, base_price): + total = calculate_tax(base_price) # Calling the helper procedure + print("Purchased " + item_name + " for $" + str(total)) -// Call the procedure -showMessage(); // Output: Welcome to the program! +# Execution starts here +checkout("Sneakers", 80.0) ``` -### Calling A Procedure Inside Another Procedure +**Key Takeaways** -Why? -- Large problems can often be broken into smaller steps (decomposition). -- Each step can be a procedure, and one procedure can call another. -- This makes programs easier to read, debug, and reuse. +- Defining vs. Calling: Defining a procedure (def) creates the instructions; calling a procedure using its name with parentheses () actually executes them. +- Reusability: Calling procedures allows you to run the same code multiple times throughout your program without retyping it. +- Decomposition: Breaking complex tasks into smaller, manageable steps makes code easier to read, debug, and maintain. +- Helper Procedures: Outer procedures can call smaller helper procedures to handle specific sub-tasks and combine the results. +**1. LxD Cycle Process** +**Empathize:** I noticed students were copy-pasting repetitive blocks of code throughout their Python scripts rather than writing modular functions. This made their code cluttered, difficult to debug, and hard to update. -Python Example: -- Calling the procedure format_name returns the formatted name so the other procedure can use it +**Define:** +- POV: AP CSP students need a clear way to practice writing and calling Python procedures so they can eliminate code duplication and organize programs logically. +- Learning Goal: Students will define procedures with parameters and call helper procedures within outer functions using Python. +**Ideate:** -```python -def format_name(first, last): - return first + " " + last +- HMW Question: How might we teach procedural decomposition and calling syntax in under 2 minutes so students can quickly jump to hands-on execution? +- Activity: A quick code-refactoring challenge where students convert duplicate print/math statements into a modular function with helper procedures. +**Prototype & Test:** During peer feedback, my team mentioned that the original reading material was too long and wordy. I streamlined the explanation down to core bullet points and replaced the open-ended coding task with two runnable code challenges. -def greet_person(first, last): - full_name = format_name(first, last) - print("Hello, " + full_name + "!") +**2. Lesson Plan** -greet_person("Sathwik", "Kintada") # Output: Hello, Sathwik Kintada! +- **Learning Objective:** Define a Python procedure with parameters, call it using arguments, and utilize helper procedures to decompose tasks. +- **Success Criteria:** You can identify the difference between defining and calling a function, pass parameters correctly, and execute a helper procedure inside an outer procedure in the code runner. +**3. Hacks & Practice Tasks** +**Popcorn Hack (In-Class Code Runner)** +Task: The code below prints receipt lines manually. Refactor it by defining a procedure apply_discount(price) that takes a price, subtracts $5, and returns the new price. Then call it inside print_receipt. +Code Runner: ``` +# UI_RUNNER: Procedures Popcorn Base - Hello, Sathwik Kintada! - +# TODO: Define the apply_discount(price) helper procedure here -JavaScript Example: -- Calling the procedure formatName returns the formatted name so the other procedure can use it +def print_receipt(item, original_price): + # TODO: Call apply_discount here to get the final_price + final_price = original_price + print("Item: " + item + " | Final Price: $" + str(final_price)) +# Test your code +print_receipt("Game Controller", 60.0) +``` -```javascript -%%js -function formatName(first, last) { - return first + " " + last; -} +**Homework Hack (Code Runner Challenge)** +Task: Refactor the messy code below. -function greetPerson(first, last) { - let fullName = formatName(first, last); - console.log("Hello, " + fullName + "!"); -} +1. Create a helper procedure is_passing(score) that returns True if score >= 70, and False otherwise. +2. Create an outer procedure evaluate_student(name, score) that calls is_passing(score). +3. If passing, print "| Status: Passed". Otherwise, print "| Status: Needs Review". +4. Call evaluate_student twice with different values. +Code Runner(the code runner is only used to check if your code works, save your code in a file to submit): -greetPerson("Lucas", "Masterson"); // Output: Hello, Lucas Masterson! ``` +# UI_RUNNER: Procedures Homework Base +# TODO: Write your helper procedure 'is_passing' here - +# TODO: Write your outer procedure 'evaluate_student' here +# TODO: Call evaluate_student twice below +``` -### Key Takeaways -- Helper procedures do one simple task. -- Outer procedures call helpers to combine or display results. -- This is decomposition — breaking a problem into smaller steps. -- Calling procedures inside procedures makes code reusable and organized. +**4. Grading Plan (1 Point Total)** +Classroom Rubric + +- 0.2 points: Popcorn Completion: Student successfully defined apply_discount, integrated it into print_receipt, and ran the cell cleanly using %%python. +- 0.8 points: Homework Completion +- 0.3 Parameter & Procedure Definition: Correctly uses def with appropriate parameters for both procedures. +- 0.3 Helper Calling Logic: Calls is_passing inside evaluate_student to handle the conditional check. +- 0.2 Execution & Outputs: Calls the outer procedure twice with different inputs and produces correct status outputs. +**Quick Validation Checklist** +[ ] Present: %%python and UI_RUNNER headers in code blocks. +[ ] Present: Helper procedure called inside the main procedure. +[ ] Absent: Hardcoded repetitive logic or global variables outside of procedures. + +**5. Lesson Revisions & Feedback Evidence** +**Feedback Received:** Peer reviewers noted that the original lesson was dense, taking over 5 minutes to read, and lacked interactive execution elements on the page. + +**Revision Made:** Reduced explanation text to three bullet points, replaced theoretical game discussions with direct in-browser Code Runner challenges, and structured the Popcorn Hack so it can be completed in under 2 minutes. + +By Joan Kim, Samanvi Yachareni, Ainsley Albert + +
+ + +
+ ↑ + Submit Assignment +
+ +
+ + + +
+
From 2e030ac9ad6c5f18290d599a848fb8f6fba28b25 Mon Sep 17 00:00:00 2001 From: Rydenb Date: Wed, 16 Sep 2026 18:45:18 -0700 Subject: [PATCH 22/43] create libraries lesson --- .../2026-09-16-libraries_python.ipynb | 493 +++++++++++++++++- 1 file changed, 492 insertions(+), 1 deletion(-) diff --git a/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb b/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb index 830db5d35f..54f6ad749f 100644 --- a/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb @@ -2,6 +2,7 @@ "cells": [ { "cell_type": "raw", + "id": "8a7d457b", "metadata": { "vscode": { "languageId": "raw" @@ -10,6 +11,7 @@ "source": [ "---\n", "layout: post\n", + "assignment: true\n", "categories: [Python, Libraries]\n", "lesson_language: Python\n", "lesson_topic: Libraries\n", @@ -23,8 +25,497 @@ "permalink: /python/libraries\n", "type: lesson\n", "---" + ] + }, + { + "cell_type": "markdown", + "id": "07efb274", + "metadata": {}, + "source": [ + "## The Core Rule\n", + "\n", + "Don't rewrite code that already exists and has been tested. **Find a library, read its API documentation, import it, and call its procedures.**\n", + "\n", + "~~~python\n", + "import random # 1. import the library\n", + "roll = random.randint(1, 6) # 2. call a procedure described in its API\n", + "print(\"You rolled\", roll)\n", + "~~~\n", + "\n", + "### College Board Big Idea 3.14: Libraries\n", + "\n", + "**Learning Objective (AAP-3.D):** Select appropriate libraries or existing code segments to use in creating new programs.\n", + "\n", + "| Essential Knowledge | What it means |\n", + "| --- | --- |\n", + "| AAP-3.D.1 | A **software library** contains procedures that may be used in creating new programs. |\n", + "| AAP-3.D.2 | Existing code segments can come from **internal or external sources**, such as libraries or previously written code. |\n", + "| AAP-3.D.3 | The use of libraries **simplifies** the task of creating complex programs. |\n", + "| AAP-3.D.4 | An **API** (Application Program Interface) is a specification for how the procedures in a library behave and can be used. |\n", + "| AAP-3.D.5 | **Documentation** for an API or library is necessary to understand its behaviors and how to use them. |\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "f96ea615", + "metadata": {}, + "source": [ + "## 1. LxD Cycle Process\n", + "\n", + "**Empathize:** Students often write long code to do things Python can already do, such as random numbers, averages, dates, and JSON. When a teammate's Flask project fails with `ModuleNotFoundError`, they also don't know why it works on one computer but not another.\n", + "\n", + "**Define:**\n", + "\n", + "* **POV:** CSP students need to know how to find, read, and use libraries because rewriting existing code wastes time and missing packages break shared projects.\n", + "* **Learning Goal:** Students will import standard library modules, read API documentation to use their procedures, and explain how `requirements.txt` lists the external libraries a project needs.\n", + "\n", + "**Ideate:**\n", + "\n", + "* **HMW Question:** How might we show students that the libraries they use in class are the same ones that power Open Coding Society?\n", + "* **Activity:** Three short cycles of a tech talk followed by a code runner exercise, ending with a homework challenge that combines several libraries.\n", + "\n", + "**Prototype & Test:** _Add notes from your trial run with your project team here._\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "752231fd", + "metadata": {}, + "source": [ + "## 2. Lesson Plan\n", + "\n", + "**Learning Objective:** By the end of this lesson, you will be able to import Python libraries, use API documentation to call their procedures correctly, and read a `requirements.txt` file.\n", + "\n", + "**Success Criteria:** You can complete a program using procedures from at least three libraries and explain which libraries a project must install.\n", + "\n", + "| Cycle | Tech Talk (1-2 min) | Popcorn Hack (5 min) |\n", + "| --- | --- | --- |\n", + "| 1 | What is a library? APIs and documentation | Read the docs and use `math` and `random` |\n", + "| 2 | Libraries in Open Coding Society | Read a notebook with `json`, like the OCS converter |\n", + "| 3 | `pip` and `requirements.txt` | Check a `requirements.txt` file |\n", + "| Homework | | Build a Study Session Report |\n", + "\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "2770ac3c", + "metadata": {}, + "source": [ + "### Cycle 1 Tech Talk: What is a Library? (2 minutes)\n", + "\n", + "A **library** is a collection of procedures that someone already wrote and tested. In Python, one file of reusable code is called a **module**, and a group of modules is a **package**.\n", + "\n", + "Python comes with a **standard library**, so modules like `math`, `random`, `datetime`, `statistics`, and `json` are ready to use with no installing.\n", + "\n", + "**Three ways to import:**\n", + "\n", + "~~~python\n", + "import math # use as math.sqrt(16)\n", + "from random import randint # use as randint(1, 6)\n", + "import statistics as stats # use as stats.mean([1, 2, 3])\n", + "~~~\n", + "\n", + "**How do you know what a procedure does?** You read its **API**, which tells you the procedure's name, its parameters, and what it returns. You don't need to know how `random.randint` works inside. You only need to know it returns a random integer between `a` and `b`, including both. This is **procedural abstraction**.\n", + "\n", + "* ✅ **Do this:** `average = statistics.mean(scores)`\n", + "* ❌ **Don't do this:** write your own loop to add and divide when a tested procedure already exists\n", + "\n", + "**Where is the documentation?** Look at [docs.python.org](https://docs.python.org/3/library/), or ask Python directly with `help(math.sqrt)` or `print(math.sqrt.__doc__)`." + ] + }, + { + "cell_type": "markdown", + "id": "b9f8c025", + "metadata": {}, + "source": [ + "### Popcorn Hack 1: Read the API, Then Use It (5 minutes)\n", + "\n", + "**Task:** Run the code to print the documentation for each procedure. Then finish the three TODOs using only `math` and `random`." + ] + }, + { + "cell_type": "code", + "id": "3f0655c0", + "metadata": {}, + "source": [ + "# CODE_RUNNER: Popcorn Hack 1 - Read the API documentation, then finish the TODOs using math and random\n", + "\n", + "import math\n", + "import random\n", + "\n", + "# Step 1: Read the API documentation before using a procedure\n", + "print(\"random.randint:\", random.randint.__doc__)\n", + "print(\"math.ceil:\", math.ceil.__doc__)\n", + "print()\n", + "\n", + "scores = [88, 92, 75, 64, 99]\n", + "\n", + "# Example: pick a random score to review\n", + "print(\"Random score to review:\", random.choice(scores))\n", + "\n", + "# TODO 1: Use random.randint to roll one 20-sided die (1 to 20)\n", + "roll = 0\n", + "print(\"d20 roll:\", roll)\n", + "\n", + "# TODO 2: Use math.sqrt to find the square root of 144\n", + "root = 0\n", + "print(\"sqrt(144):\", root)\n", + "\n", + "# TODO 3: Use math.ceil to round the average score UP to a whole number\n", + "average = sum(scores) / len(scores)\n", + "rounded_up = average\n", + "print(\"Average:\", average, \"-> rounded up:\", rounded_up)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "8da383d5", + "metadata": {}, + "source": [ + "---\n", + "\n", + "### Cycle 2 Tech Talk: Libraries in Open Coding Society (2 minutes)\n", + "\n", + "The libraries you are learning are not just for practice. They run the Open Coding Society website and backend.\n", + "\n", + "**This website (the pages repo)** is written in Jupyter notebooks. A Python script called `scripts/convert_notebooks.py` uses libraries to turn every `.ipynb` into a page:\n", + "\n", + "| Library | What it does | How OCS uses it |\n", + "| --- | --- | --- |\n", + "| `nbformat` | Reads and writes notebook files | Opens each lesson `.ipynb` |\n", + "| `nbconvert` | Converts notebooks to other formats | Turns notebooks into Markdown posts |\n", + "| `pyyaml` | Reads YAML front matter | Reads the `title`, `permalink`, and `categories` at the top of lessons |\n", + "\n", + "**The Flask backend** that handles logins, grades, and the code runner uses:\n", + "\n", + "| Library | What it does | How OCS uses it |\n", + "| --- | --- | --- |\n", + "| `Flask` | Builds web servers and APIs | Runs the whole backend |\n", + "| `Flask_Login`, `PyJWT` | Handles users and login tokens | Signs you in and keeps you logged in |\n", + "| `SQLAlchemy` | Talks to a database with Python objects | Stores users, sections, and grades |\n", + "| `python-dotenv` | Loads secret settings from a `.env` file | Keeps passwords out of the code |\n", + "| `pandas`, `scikit-learn` | Data tables and machine learning | Grade prediction in `model/grade_model.py` |\n", + "\n", + "**Key idea:** a notebook file is just **JSON** text. The OCS converter reads it as data. Python's built-in `json` library can do the same thing." + ] + }, + { + "cell_type": "markdown", + "id": "8f76e599", + "metadata": {}, + "source": [ + "### Popcorn Hack 2: Read a Notebook Like the OCS Converter (5 minutes)\n", + "\n", + "**Task:** A tiny `.ipynb` file is stored as JSON text. Use the `json` library to load it, then finish the TODOs to find information the OCS converter needs." + ] + }, + { + "cell_type": "code", + "id": "7dd45399", + "metadata": {}, + "source": [ + "# CODE_RUNNER: Popcorn Hack 2 - Use the json library to read a notebook the way the OCS converter does\n", + "\n", + "import json\n", + "\n", + "# A tiny .ipynb file is just JSON text\n", + "notebook_text = '''\n", + "{\n", + " \"cells\": [\n", + " {\"cell_type\": \"raw\", \"source\": [\"---\\\\n\", \"title: 3.14 Libraries\\\\n\", \"permalink: /python/libraries\\\\n\", \"---\"]},\n", + " {\"cell_type\": \"markdown\", \"source\": [\"## What is a Library?\"]},\n", + " {\"cell_type\": \"code\", \"source\": [\"import math\\\\n\", \"print(math.pi)\"]},\n", + " {\"cell_type\": \"code\", \"source\": [\"import random\\\\n\", \"print(random.randint(1, 6))\"]}\n", + " ]\n", + "}\n", + "'''\n", + "\n", + "# json.loads turns JSON text into a Python dictionary\n", + "notebook = json.loads(notebook_text)\n", + "cells = notebook[\"cells\"]\n", + "print(\"Number of cells:\", len(cells))\n", + "\n", + "# TODO 1: Count how many cells have a cell_type of \"code\"\n", + "code_cells = 0\n", + "print(\"Code cells:\", code_cells)\n", + "\n", + "# TODO 2: Find the line that starts with \"title:\" in the front matter and save only the title text\n", + "front_matter = \"\".join(cells[0][\"source\"])\n", + "title = \"\"\n", + "print(\"Title:\", title)\n", + "\n", + "# TODO 3: Use json.dumps with indent=2 to print the last cell as formatted JSON" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "cdd1cde7", + "metadata": {}, + "source": [ + "---\n", + "\n", + "### Cycle 3 Tech Talk: pip and requirements.txt (2 minutes)\n", + "\n", + "Standard library modules come with Python. **External libraries** like `Flask` and `pandas` do not. You install them with **pip**, Python's package installer:\n", + "\n", + "~~~bash\n", + "pip install flask\n", + "~~~\n", + "\n", + "A real project needs many libraries, so projects list them in a file called **`requirements.txt`**. Here is part of the OCS Flask backend's file:\n", + "\n", + "~~~text\n", + "Flask\n", + "Flask_Login\n", + "SQLAlchemy\n", + "PyJWT\n", + "pandas\n", + "scikit-learn\n", + "python_dotenv\n", + "~~~\n", + "\n", + "When you clone a project, one command installs everything, usually inside a virtual environment (`venv`) so each project keeps its own packages:\n", + "\n", + "~~~bash\n", + "python3 -m venv venv\n", + "source venv/bin/activate\n", + "pip install -r requirements.txt\n", + "~~~\n", + "\n", + "**Why it matters:**\n", + "\n", + "* **Teammates** get the same libraries you have, so the project runs on every computer.\n", + "* **Deployment** servers, such as the OCS Docker backend, read the same file.\n", + "* **Versions** can be set with `Flask==3.0.0` (exactly this version) or `Flask>=3.0` (this version or newer).\n", + "\n", + "**Watch out:** the name you `pip install` is not always the name you `import`:\n", + "\n", + "| pip install | import |\n", + "| --- | --- |\n", + "| `python-dotenv` | `import dotenv` |\n", + "| `scikit-learn` | `import sklearn` |\n", + "| `PyJWT` | `import jwt` |\n", + "\n", + "If a library is missing, Python shows `ModuleNotFoundError`. That usually means you forgot `pip install -r requirements.txt`, or your `venv` is not active." + ] + }, + { + "cell_type": "markdown", + "id": "3eeced9f", + "metadata": {}, + "source": [ + "### Popcorn Hack 3: Check a requirements.txt (5 minutes)\n", + "\n", + "**Task:** Finish `parse_requirements` so it skips blank lines and comments and removes version numbers. The program then uses `importlib` to check which packages are installed on the code runner." + ] + }, + { + "cell_type": "code", + "id": "4749e167", + "metadata": {}, + "source": [ + "# CODE_RUNNER: Popcorn Hack 3 - Finish the requirements.txt checker using importlib\n", + "\n", + "import importlib.util\n", + "\n", + "requirements_txt = '''\n", + "# Web framework\n", + "Flask>=3.0\n", + "requests\n", + "\n", + "# Data and machine learning\n", + "pandas==2.2.2\n", + "scikit-learn\n", + "python-dotenv\n", + "'''\n", + "\n", + "# The name you pip install is not always the name you import\n", + "IMPORT_NAMES = {\n", + " \"Flask\": \"flask\",\n", + " \"scikit-learn\": \"sklearn\",\n", + " \"python-dotenv\": \"dotenv\",\n", + "}\n", + "\n", + "def parse_requirements(text):\n", + " '''Return a list of package names from requirements.txt text.'''\n", + " packages = []\n", + " for line in text.splitlines():\n", + " line = line.strip()\n", + " # TODO 1: Skip blank lines and lines that start with \"#\"\n", + "\n", + " # TODO 2: Remove version specifiers such as \"==2.2.2\" or \">=3.0\"\n", + " name = line\n", + " packages.append(name)\n", + " return packages\n", + "\n", + "def is_installed(package):\n", + " '''Return True if Python can find the package on this computer.'''\n", + " import_name = IMPORT_NAMES.get(package, package)\n", + " try:\n", + " return importlib.util.find_spec(import_name) is not None\n", + " except (ValueError, ModuleNotFoundError):\n", + " return False\n", + "\n", + "for package in parse_requirements(requirements_txt):\n", + " if is_installed(package):\n", + " print(f\"{package!r:20} installed\")\n", + " else:\n", + " print(f\"{package!r:20} missing -> pip install {package}\")\n", + "\n", + "# TODO 3: Print is_installed(\"json\"). Why is json installed even though it is not in requirements.txt?" ], - "id": "096a1e6e" + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "f667e856", + "metadata": {}, + "source": [ + "---\n", + "\n", + "## 3. Hacks & Practice Tasks\n", + "\n", + "### Prepare your submission IPYNB\n", + "\n", + "Complete this quick-start flow so you can begin in about 2 minutes.\n", + "\n", + "1. Create a new notebook in your portfolio homework area: `_notebooks/homework`.\n", + "2. Add one raw cell at the top with the frontmatter below.\n", + "3. Add a code cell for each Popcorn Hack and the Homework. Keep the `# CODE_RUNNER:` comment as the first line of each code cell.\n", + "4. Run each cell and check the output before submitting.\n", + "\n", + "~~~raw\n", + "---\n", + "layout: post\n", + "title: 3.14 Libraries HW\n", + "categories: [Python]\n", + "lesson_language: Python\n", + "lesson_topic: Libraries HW\n", + "lesson_part: interactive\n", + "lesson_type: lesson\n", + "permalink: /python/libraries-hw\n", + "author: githubID\n", + "---\n", + "~~~\n", + "\n", + "### Submission Safety Rules (Read First)\n", + "\n", + "> [!IMPORTANT]\n", + "> To avoid grading errors, follow these rules exactly:\n", + ">\n", + "> * Keep the `# CODE_RUNNER:` comment as the first line of each submission cell.\n", + "> * Your code must run in the code runner with no errors.\n", + "> * Only import **standard library** modules (such as `math`, `random`, `statistics`, `datetime`, `json`). The code runner may not have external packages installed.\n", + "> * Do not use `input()`. The code runner cannot type answers for you." + ] + }, + { + "cell_type": "markdown", + "id": "c6a4265c", + "metadata": {}, + "source": [ + "### Homework Hack: Study Session Report\n", + "\n", + "**Task:** Finish a program that reports on a student's study sessions. Your finished program must:\n", + "\n", + "1. **Use at least 3 standard library modules.** `json` and `datetime` are already imported. Add at least one more, such as `statistics`, `random`, or `math`.\n", + "2. **Complete `summarize_sessions`** so it returns the total minutes, average minutes, longest session, and minutes per subject.\n", + "3. **Document your API.** Replace the TODO docstring with the procedure's parameters and return value, so someone else could use it without reading the code.\n", + "4. **Use `datetime`** to add how many days are left until a test date you choose.\n", + "5. **Write a `requirements.txt`.** Imagine a real version of this app that uses `pandas` for data and `Flask` for a web page. List those packages, and add a comment explaining why `json` and `datetime` are not listed." + ] + }, + { + "cell_type": "code", + "id": "63eee878", + "metadata": {}, + "source": [ + "# CODE_RUNNER: Homework - Build a Study Session Report using at least 3 libraries\n", + "\n", + "import json\n", + "from datetime import date\n", + "# TODO: import at least one more standard library module (statistics, random, math, ...)\n", + "\n", + "study_sessions = [\n", + " {\"day\": \"2026-09-14\", \"subject\": \"CSP\", \"minutes\": 45},\n", + " {\"day\": \"2026-09-15\", \"subject\": \"Math\", \"minutes\": 30},\n", + " {\"day\": \"2026-09-15\", \"subject\": \"CSP\", \"minutes\": 60},\n", + " {\"day\": \"2026-09-16\", \"subject\": \"English\", \"minutes\": 25},\n", + "]\n", + "\n", + "def summarize_sessions(sessions):\n", + " '''\n", + " TODO: Document this procedure's API.\n", + " Parameters: ...\n", + " Returns: ...\n", + " '''\n", + " total = sum(session[\"minutes\"] for session in sessions)\n", + " # TODO: add average minutes, longest session, and minutes per subject\n", + " return {\"total_minutes\": total}\n", + "\n", + "report = summarize_sessions(study_sessions)\n", + "\n", + "# TODO: use date to add \"days_until_test\" to the report for a test date you choose\n", + "\n", + "print(json.dumps(report, indent=2))\n", + "\n", + "# TODO: list the external packages a real version of this app would need\n", + "requirements_txt = '''\n", + "'''\n", + "print(\"requirements.txt:\")\n", + "print(requirements_txt)" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "markdown", + "id": "5621c480", + "metadata": {}, + "source": [ + "---\n", + "\n", + "## 4. Grading Plan (1 Point Total)\n", + "\n", + "### Classroom Rubric\n", + "\n", + "* **0.3 points: Popcorn completion** (0.1 each)\n", + " Student completed all TODOs in each Popcorn Hack and the cell runs without errors.\n", + "* **0.7 points: Homework completion**\n", + " * **0.2 libraries:** Imports and uses at least 3 standard library modules.\n", + " * **0.2 procedure:** `summarize_sessions` returns total, average, longest session, and minutes per subject.\n", + " * **0.1 API documentation:** The docstring describes the parameters and the return value.\n", + " * **0.1 datetime:** The report includes days until a chosen test date.\n", + " * **0.1 requirements.txt:** Lists `pandas` and `Flask`, and explains why standard library modules are not listed.\n", + "\n", + "### Quick Validation Checklist\n", + "\n", + "* Present: `# CODE_RUNNER:` comment as the first line of each cell.\n", + "* Present: at least 3 different `import` statements from the standard library.\n", + "* Present: a docstring on `summarize_sessions` with no remaining `TODO`.\n", + "* Present: `json.dumps` output showing the report.\n", + "* Absent: `input()`, external package imports, and errors when run.\n", + "\n", + "---\n", + "\n", + "## 5. Lesson Revisions & Feedback Evidence\n", + "\n", + "* **Feedback Received:** _Add feedback from your peer practice run here._\n", + "* **Revision Made:** _Describe what you changed because of that feedback._\n", + "\n", + "---" + ] } ], "metadata": { From 04d42b603cf30bb456c97c19f3915bc4f6e59ea6 Mon Sep 17 00:00:00 2001 From: samanviy17-crypto Date: Wed, 16 Sep 2026 19:38:47 -0700 Subject: [PATCH 23/43] Fix lesson heading structure and runner layout --- ...ing_procedures_remakers_lesson_IPYNB_2_.md | 51 +-- ...8-calling_procedures_remakers_lesson.ipynb | 351 +++++++----------- 2 files changed, 167 insertions(+), 235 deletions(-) diff --git a/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md b/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md index 013eec76e9..0dbdc9fc51 100644 --- a/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md +++ b/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md @@ -7,6 +7,8 @@ lesson_topic: Calling-Procedures lesson_part: interactive lesson_type: lesson toc: True +codemirror: True +challenge_submit: True comments: False title: 3.12 Calling Procedures description: 3.12 Calling Procedures @@ -19,13 +21,13 @@ date: 2026-09-16 Every time you send a text message, your phone encodes the characters, transmits a wireless signal to a cell tower, and routes it to your friend. You don’t route network packets by hand — you just press send. That’s calling a procedure: the steps are saved, and you run them whenever you need them. -**What is calling a procedure?** +#### What is calling a procedure? A procedure (a function in Python) is a named set of re-usable code instructions. - You can call a procedure multiple times with different input values without having to rewrite it - Different from defining the procedure: defining is creating it, calling is using it - Calling allows you to run the same set of instructions whenever you need them without rewriting the lines of code. -**Passing Inputs (Parameters)** +#### Passing Inputs (Parameters) You can make procedures more flexible by giving them parameters—input variables that hold data passed into the procedure when you call it. - Parameters act as temporary placeholders inside the procedure definition. @@ -46,7 +48,7 @@ def send_notification(username): send_notification("Joan") ``` -**Calling Procedures Inside Procedures (Decomposition)** +#### Calling Procedures Inside Procedures (Decomposition) In computer science, large problems are broken down into smaller steps—a process called decomposition. You can call a helper procedure inside an outer procedure to handle a specific part of a task. Each step can become its own procedure, and one procedure can call another one. This allows programs to become easier to read, use, and debug. Python Example: @@ -65,13 +67,13 @@ def checkout(item_name, base_price): checkout("Sneakers", 80.0) ``` -**Key Takeaways** +#### Key Takeaways - Defining vs. Calling: Defining a procedure (def) creates the instructions; calling a procedure using its name with parentheses () actually executes them. - Reusability: Calling procedures allows you to run the same code multiple times throughout your program without retyping it. - Decomposition: Breaking complex tasks into smaller, manageable steps makes code easier to read, debug, and maintain. - Helper Procedures: Outer procedures can call smaller helper procedures to handle specific sub-tasks and combine the results. -**1. LxD Cycle Process** +#### 1. LxD Cycle Process **Empathize:** I noticed students were copy-pasting repetitive blocks of code throughout their Python scripts rather than writing modular functions. This made their code cluttered, difficult to debug, and hard to update. **Define:** @@ -84,49 +86,56 @@ checkout("Sneakers", 80.0) - Activity: A quick code-refactoring challenge where students convert duplicate print/math statements into a modular function with helper procedures. **Prototype & Test:** During peer feedback, my team mentioned that the original reading material was too long and wordy. I streamlined the explanation down to core bullet points and replaced the open-ended coding task with two runnable code challenges. -**2. Lesson Plan** +#### 2. Lesson Plan - **Learning Objective:** Define a Python procedure with parameters, call it using arguments, and utilize helper procedures to decompose tasks. - **Success Criteria:** You can identify the difference between defining and calling a function, pass parameters correctly, and execute a helper procedure inside an outer procedure in the code runner. -**3. Hacks & Practice Tasks** -**Popcorn Hack (In-Class Code Runner)** +#### 3. Hacks & Practice Tasks + +#### Popcorn Hack (In-Class Code Runner) Task: The code below prints receipt lines manually. Refactor it by defining a procedure apply_discount(price) that takes a price, subtracts $5, and returns the new price. Then call it inside print_receipt. -Code Runner: -``` -# UI_RUNNER: Procedures Popcorn Base +{% capture popcorn_challenge %} +Refactor the receipt code by defining an `apply_discount(price)` helper procedure and calling it inside `print_receipt`. +{% endcapture %} +{% capture popcorn_code %} # TODO: Define the apply_discount(price) helper procedure here def print_receipt(item, original_price): # TODO: Call apply_discount here to get the final_price - final_price = original_price + final_price = original_price print("Item: " + item + " | Final Price: $" + str(final_price)) # Test your code print_receipt("Game Controller", 60.0) -``` +{% endcapture %} + +{% include runners/code.html runner_id="procedures-popcorn" language="python" challenge=popcorn_challenge code=popcorn_code %} -**Homework Hack (Code Runner Challenge)** +#### Homework Hack (Code Runner Challenge) Task: Refactor the messy code below. 1. Create a helper procedure is_passing(score) that returns True if score >= 70, and False otherwise. 2. Create an outer procedure evaluate_student(name, score) that calls is_passing(score). 3. If passing, print "| Status: Passed". Otherwise, print "| Status: Needs Review". 4. Call evaluate_student twice with different values. -Code Runner(the code runner is only used to check if your code works, save your code in a file to submit): -``` -# UI_RUNNER: Procedures Homework Base +{% capture homework_challenge %} +Create a helper procedure `is_passing(score)` and an outer procedure `evaluate_student(name, score)` that calls it twice with different values. +{% endcapture %} +{% capture homework_code %} # TODO: Write your helper procedure 'is_passing' here # TODO: Write your outer procedure 'evaluate_student' here # TODO: Call evaluate_student twice below -``` +{% endcapture %} + +{% include runners/code.html runner_id="procedures-homework" language="python" challenge=homework_challenge code=homework_code %} -**4. Grading Plan (1 Point Total)** +#### 4. Grading Plan (1 Point Total) Classroom Rubric - 0.2 points: Popcorn Completion: Student successfully defined apply_discount, integrated it into print_receipt, and ran the cell cleanly using %%python. @@ -134,12 +143,12 @@ Classroom Rubric - 0.3 Parameter & Procedure Definition: Correctly uses def with appropriate parameters for both procedures. - 0.3 Helper Calling Logic: Calls is_passing inside evaluate_student to handle the conditional check. - 0.2 Execution & Outputs: Calls the outer procedure twice with different inputs and produces correct status outputs. -**Quick Validation Checklist** +#### Quick Validation Checklist [ ] Present: %%python and UI_RUNNER headers in code blocks. [ ] Present: Helper procedure called inside the main procedure. [ ] Absent: Hardcoded repetitive logic or global variables outside of procedures. -**5. Lesson Revisions & Feedback Evidence** +#### 5. Lesson Revisions & Feedback Evidence **Feedback Received:** Peer reviewers noted that the original lesson was dense, taking over 5 minutes to read, and lacked interactive execution elements on the page. **Revision Made:** Reduced explanation text to three bullet points, replaced theoretical game discussions with direct in-browser Code Runner challenges, and structured the Popcorn Hack so it can be completed in under 2 minutes. diff --git a/_projects/lessons/python/notebooks/2025-10-08-calling_procedures_remakers_lesson.ipynb b/_projects/lessons/python/notebooks/2025-10-08-calling_procedures_remakers_lesson.ipynb index 1eaf4bb15a..e0a3826399 100644 --- a/_projects/lessons/python/notebooks/2025-10-08-calling_procedures_remakers_lesson.ipynb +++ b/_projects/lessons/python/notebooks/2025-10-08-calling_procedures_remakers_lesson.ipynb @@ -2,12 +2,8 @@ "cells": [ { "cell_type": "raw", - "id": "58d6ad13", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, + "id": "580798a7", + "metadata": {}, "source": [ "---\n", "layout: post\n", @@ -23,232 +19,159 @@ "title: 3.12 Calling Procedures\n", "description: 3.12 Calling Procedures\n", "permalink: /csp/big-idea-3/calling-procedures/p4/lesson\n", - "author: Sathwik Kintada\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "1a67b4ac", - "metadata": {}, - "source": [ - "## 3.12 Calling Procedures" - ] - }, - { - "cell_type": "markdown", - "id": "546f608a", - "metadata": {}, - "source": [ - "Every morning you brush your teeth, wash your face, and eat breakfast. You don’t rewrite those steps every day — you just do them. That’s what calling a procedure is: you already have the steps (the function), and you just call it whenever you need it." - ] - }, - { - "cell_type": "markdown", - "id": "da19290b", - "metadata": {}, - "source": [ - "What is it?\n", - "- A procedure is a reusable group of instructions.\n", - "- Also called a function in Python or JavaScript.\n", - "- Procedures allow you to avoid rewriting the same code.\n", - "What does it mean?\n", - "- Calling a procedure means telling the computer to run the instructions in that procedure.\n", - "- You can call a procedure multiple times with different input values without rewriting it.\n", - "- This is different from defining the procedure — defining is creating it, calling is using it.\n" + "author: Samanvi Yachareni, Joan Kim, Ainsley Albert\n", + "---\n" ] }, { "cell_type": "markdown", - "id": "7924f727", + "id": "e418580e", "metadata": {}, "source": [ + "### 3.12 Calling Procedures\n", + "\n", + "Every time you send a text message, your phone encodes the characters, transmits a wireless signal to a cell tower, and routes it to your friend. You don’t route network packets by hand — you just press send. That’s calling a procedure: the steps are saved, and you run them whenever you need them.\n", + "\n", + "#### What is calling a procedure?\n", + "A procedure (a function in Python) is a named set of re-usable code instructions.\n", + "\n", + "- You can call a procedure multiple times with different input values without having to rewrite it\n", + "- Different from defining the procedure: defining is creating it, calling is using it\n", + "- Calling allows you to run the same set of instructions whenever you need them without rewriting the lines of code.\n", + "\n", + "#### Passing Inputs (Parameters)\n", + "You can make procedures more flexible by giving them parameters—input variables that hold data passed into the procedure when you call it.\n", + "\n", + "- Parameters act as temporary placeholders inside the procedure definition.\n", + "- Arguments are the actual values you send into the procedure when you call it.\n", + "\n", + "This allows a single procedure to run the same set of instructions on completely different data without rewriting the code.\n", + "\n", "Python Example:\n", - "- Use def to define a procedure\n", - "- You can use the name of the functionand paranthesis after to call it" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "3e89f8df", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Welcome to the program!\n" - ] - } - ], - "source": [ - "# Define a procedure\n", - "def show_message():\n", - " print(\"Welcome to the program!\")\n", "\n", - "# Call the procedure\n", - "show_message() # Output: Welcome to the program!" - ] - }, - { - "cell_type": "markdown", - "id": "a0f35669", - "metadata": {}, - "source": [ - "Javascript Example:\n", - "- You use function to define a procedure\n", - "- Just like python if you type the name of the function with parenthesis right after it, you can call the procedure" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "095d5a3c", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "// Define a procedure\n", - "function showMessage() {\n", - " console.log(\"Welcome to the program!\");\n", - "}\n", - "\n", - "// Call the procedure\n", - "showMessage(); // Output: Welcome to the program!" - ] - }, - { - "cell_type": "markdown", - "id": "c0bad1ca", - "metadata": {}, - "source": [ - "### Calling A Procedure Inside Another Procedure" - ] - }, - { - "cell_type": "markdown", - "id": "5cc114cd", - "metadata": {}, - "source": [ - "Why?\n", - "- Large problems can often be broken into smaller steps (decomposition).\n", - "- Each step can be a procedure, and one procedure can call another.\n", - "- This makes programs easier to read, debug, and reuse." - ] - }, - { - "cell_type": "markdown", - "id": "aeb3a821", - "metadata": {}, - "source": [ + "- Use def to define the function/procedure\n", + "- To call a procedure write the name of the procedure followed by parenthesis, and variables if included\n", + "\n", + "```python\n", + "# 1. DEFINE the procedure with a parameter (variable input)\n", + "def send_notification(username):\n", + " print(\"New message for \" + username + \"!\")\n", + "\n", + "# 2. CALL the procedure passing different inputs\n", + "send_notification(\"Joan\")\n", + "```\n", + "\n", + "#### Calling Procedures Inside Procedures (Decomposition)\n", + "In computer science, large problems are broken down into smaller steps—a process called decomposition. You can call a helper procedure inside an outer procedure to handle a specific part of a task. Each step can become its own procedure, and one procedure can call another one. This allows programs to become easier to read, use, and debug.\n", + "\n", "Python Example:\n", - "- Calling the procedure format_name returns the formatted name so the other procedure can use it" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "f5dcd556", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello, Sathwik Kintada!\n" - ] - } - ], - "source": [ - "def format_name(first, last):\n", - " return first + \" \" + last\n", "\n", - "def greet_person(first, last):\n", - " full_name = format_name(first, last)\n", - " print(\"Hello, \" + full_name + \"!\")\n", + "```python\n", + "# Helper procedure: Calculates the final price with sales tax\n", + "def calculate_tax(price):\n", + " return price * 1.07\n", "\n", - "greet_person(\"Sathwik\", \"Kintada\") # Output: Hello, Sathwik Kintada!\n" - ] - }, - { - "cell_type": "markdown", - "id": "400a7933", - "metadata": {}, - "source": [ - "JavaScript Example:\n", - "- Calling the procedure formatName returns the formatted name so the other procedure can use it" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "5d26a0f4", - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [ - { - "data": { - "application/javascript": "function formatName(first, last) {\n return first + \" \" + last;\n}\n\nfunction greetPerson(first, last) {\n let fullName = formatName(first, last);\n console.log(\"Hello, \" + fullName + \"!\");\n}\n\ngreetPerson(\"Lucas\", \"Masterson\"); // Output: Hello, Lucas Masterson!\n", - "text/plain": [ - "" - ] - }, - "metadata": {}, - "output_type": "display_data" - } - ], - "source": [ - "%%js\n", - "function formatName(first, last) {\n", - " return first + \" \" + last;\n", - "}\n", + "# Outer procedure: Handles the checkout process\n", + "def checkout(item_name, base_price):\n", + " total = calculate_tax(base_price) # Calling the helper procedure\n", + " print(\"Purchased \" + item_name + \" for $\" + str(total))\n", "\n", - "function greetPerson(first, last) {\n", - " let fullName = formatName(first, last);\n", - " console.log(\"Hello, \" + fullName + \"!\");\n", - "}\n", + "# Execution starts here\n", + "checkout(\"Sneakers\", 80.0)\n", + "```\n", "\n", - "greetPerson(\"Lucas\", \"Masterson\"); // Output: Hello, Lucas Masterson!" - ] - }, - { - "cell_type": "markdown", - "id": "9f3c6f63", - "metadata": {}, - "source": [ - "### Key Takeaways\n", - "- Helper procedures do one simple task.\n", - "- Outer procedures call helpers to combine or display results.\n", - "- This is decomposition — breaking a problem into smaller steps.\n", - "- Calling procedures inside procedures makes code reusable and organized." + "#### Key Takeaways\n", + "\n", + "- Defining vs. Calling: Defining a procedure (def) creates the instructions; calling a procedure using its name with parentheses () actually executes them.\n", + "- Reusability: Calling procedures allows you to run the same code multiple times throughout your program without retyping it.\n", + "- Decomposition: Breaking complex tasks into smaller, manageable steps makes code easier to read, debug, and maintain.\n", + "- Helper Procedures: Outer procedures can call smaller helper procedures to handle specific sub-tasks and combine the results.\n", + "\n", + "#### 1. LxD Cycle Process\n", + "\n", + "**Empathize:** I noticed students were copy-pasting repetitive blocks of code throughout their Python scripts rather than writing modular functions. This made their code cluttered, difficult to debug, and hard to update.\n", + "\n", + "**Define:**\n", + "\n", + "- POV: AP CSP students need a clear way to practice writing and calling Python procedures so they can eliminate code duplication and organize programs logically.\n", + "- Learning Goal: Students will define procedures with parameters and call helper procedures within outer functions using Python.\n", + "\n", + "**Ideate:**\n", + "\n", + "- HMW Question: How might we teach procedural decomposition and calling syntax in under 2 minutes so students can quickly jump to hands-on execution?\n", + "- Activity: A quick code-refactoring challenge where students convert duplicate print/math statements into a modular function with helper procedures.\n", + "\n", + "**Prototype & Test:** During peer feedback, my team mentioned that the original reading material was too long and wordy. I streamlined the explanation down to core bullet points and replaced the open-ended coding task with two runnable code challenges.\n", + "\n", + "#### 2. Lesson Plan\n", + "\n", + "- **Learning Objective:** Define a Python procedure with parameters, call it using arguments, and utilize helper procedures to decompose tasks.\n", + "- **Success Criteria:** You can identify the difference between defining and calling a function, pass parameters correctly, and execute a helper procedure inside an outer procedure in the code runner.\n", + "\n", + "#### 3. Hacks & Practice Tasks\n", + "\n", + "#### Popcorn Hack (In-Class Code Runner)\n", + "Task: The code below prints receipt lines manually. Refactor it by defining a procedure apply_discount(price) that takes a price, subtracts $5, and returns the new price. Then call it inside print_receipt.\n", + "Code Runner:\n", + "\n", + "```python\n", + "# UI_RUNNER: Procedures Popcorn Base\n", + "\n", + "# TODO: Define the apply_discount(price) helper procedure here\n", + "\n", + "def print_receipt(item, original_price):\n", + " # TODO: Call apply_discount here to get the final_price\n", + " final_price = original_price \n", + " print(\"Item: \" + item + \" | Final Price: $\" + str(final_price))\n", + "\n", + "# Test your code\n", + "print_receipt(\"Game Controller\", 60.0)\n", + "```\n", + "\n", + "#### Homework Hack (Code Runner Challenge)\n", + "Task: Refactor the messy code below.\n", + "\n", + "1. Create a helper procedure is_passing(score) that returns True if score >= 70, and False otherwise.\n", + "2. Create an outer procedure evaluate_student(name, score) that calls is_passing(score).\n", + "3. If passing, print \"| Status: Passed\". Otherwise, print \"| Status: Needs Review\".\n", + "4. Call evaluate_student twice with different values.\n", + "Code Runner(the code runner is only used to check if your code works, save your code in a file to submit):\n", + "\n", + "```python\n", + "# UI_RUNNER: Procedures Homework Base\n", + "\n", + "# TODO: Write your helper procedure 'is_passing' here\n", + "\n", + "# TODO: Write your outer procedure 'evaluate_student' here\n", + "\n", + "# TODO: Call evaluate_student twice below\n", + "```\n", + "\n", + "#### 4. Grading Plan (1 Point Total)\n", + "Classroom Rubric\n", + "\n", + "- 0.2 points: Popcorn Completion: Student successfully defined apply_discount, integrated it into print_receipt, and ran the cell cleanly using %%python.\n", + "- 0.8 points: Homework Completion\n", + "- 0.3 Parameter & Procedure Definition: Correctly uses def with appropriate parameters for both procedures.\n", + "- 0.3 Helper Calling Logic: Calls is_passing inside evaluate_student to handle the conditional check.\n", + "- 0.2 Execution & Outputs: Calls the outer procedure twice with different inputs and produces correct status outputs.\n", + "#### Quick Validation Checklist\n", + "[ ] Present: %%python and UI_RUNNER headers in code blocks.\n", + "[ ] Present: Helper procedure called inside the main procedure.\n", + "[ ] Absent: Hardcoded repetitive logic or global variables outside of procedures.\n", + "\n", + "#### 5. Lesson Revisions & Feedback Evidence\n", + "**Feedback Received:** Peer reviewers noted that the original lesson was dense, taking over 5 minutes to read, and lacked interactive execution elements on the page.\n", + "\n", + "**Revision Made:** Reduced explanation text to three bullet points, replaced theoretical game discussions with direct in-browser Code Runner challenges, and structured the Popcorn Hack so it can be completed in under 2 minutes.\n", + "\n", + "By Joan Kim, Samanvi Yachareni, Ainsley Albert\n" ] } ], "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.10.1" + "name": "python" } }, "nbformat": 4, From 564f9f3c4ec27a6aca5d01fc30f170df8df682d5 Mon Sep 17 00:00:00 2001 From: samanviy17-crypto Date: Wed, 16 Sep 2026 19:43:17 -0700 Subject: [PATCH 24/43] Add new targets for current builds and update Python command usage in Makefile --- Makefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index e7aefd2a0c..862b40724b 100644 --- a/Makefile +++ b/Makefile @@ -25,6 +25,7 @@ DEV_PROJECTS := $(shell grep -v '^\#' $(PROJECT_FILE) 2>/dev/null | grep -v '^$$ # Known top-level targets (add to this if needed) KNOWN_TARGETS := \ default dev serve build clean stop reload refresh help \ + serve-current build-current \ serve-minima serve-cayman serve-yat serve-so-simple serve-hydejack \ build-minima build-cayman build-yat build-so-simple \ convert convert-docx convert-docx-config convert-single convert-registered-notebooks \ @@ -274,11 +275,11 @@ build: build-current # Multi-course file splitting split-courses: @echo " ------ Splitting multi-course files... -------" - @python3 scripts/split_multi_course_files.py + @$(PYTHON) scripts/split_multi_course_files.py clean-courses: @echo "🧹Cleaning course-specific files..." - @python3 scripts/split_multi_course_files.py clean + @$(PYTHON) scripts/split_multi_course_files.py clean # Notebook and DOCX conversion convert: $(MARKDOWN_FILES) convert-docx From ff6ab6a77e8ba08d8600f217a73d5c9f0f2caa94 Mon Sep 17 00:00:00 2001 From: aRYA622-y <128329936+aRYA622-y@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:19:02 -0700 Subject: [PATCH 25/43] Complete Boolean expressions Python lesson --- ...09-15-boolean_scratchers_py_hw_IPYNB_2_.md | 185 ++++++++++++++++-- 1 file changed, 172 insertions(+), 13 deletions(-) diff --git a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md index ff19aa8cc5..2dd23c618e 100644 --- a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md +++ b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md @@ -10,45 +10,204 @@ microblog: true toc: false comments: false title: 3.5 Boolean Expressions (PY) -description: Boolean expressions lesson starter. +description: Learn Boolean expressions in Python using the five-part LxD lesson format. permalink: /python/boolean/py authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar --- # 3.5 Boolean Expressions in Python +A **Boolean expression** is a question that evaluates to only `True` or `False`. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms. + ## 1. LxD Cycle Process -### Empathize +**Empathize:** Boolean expressions can look simple, but it is easy to mix up `and` and `or`, forget a boundary such as `>=`, or write a condition that does not match the rule in normal English. + +**Define:** +- **POV:** CSP students need a clear way to turn real-world rules into Boolean expressions so their programs make the correct decisions. +- **Learning Goal:** Students will be able to evaluate, write, test, and explain Boolean expressions in Python. -### Define +**Ideate:** +- **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program? +- **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker. -### Ideate +**Prototype & Test:** Use the classwork below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule. -### Prototype & Test +--- ## 2. Lesson Plan -### Learning Objective +**Learning Objective:** By the end of this lesson, you will be able to use comparisons, `and`, `or`, and `not` to create Boolean expressions and use them in Python decisions. + +**Success Criteria:** You can predict whether an expression is `True` or `False`, write a condition from a rule in normal English, and test the condition with more than one set of values. + +### Part 1: Comparisons Create Booleans + +Python comparison operators return `True` or `False`. -### Success Criteria +| Python | Meaning | Example | +| --- | --- | --- | +| `==` | equal to | `score == 90` | +| `!=` | not equal to | `score != 0` | +| `>` | greater than | `score > 70` | +| `<` | less than | `age < 18` | +| `>=` | greater than or equal to | `score >= 70` | +| `<=` | less than or equal to | `age <= 18` | -### Part 1: Comparisons +```python +score = 82 + +print(score >= 70) +print(score == 100) +print(score != 0) +``` + +Remember: +- `score = 90` assigns a value. +- `score == 90` compares two values. ### Part 2: `and`, `or`, and `not` -### Part 3: Boolean `if` Statements +Sometimes one comparison is not enough. + +| Idea | Python | JavaScript | College Board pseudocode | +| --- | --- | --- | --- | +| both must be true | `and` | `&&` | `AND` | +| at least one is true | `or` | `||` | `OR` | +| reverse true/false | `not` | `!` | `NOT` | + +```python +has_id = True +has_ticket = False + +print(has_id and has_ticket) +print(has_id or has_ticket) +print(not has_ticket) +``` + +A longer expression can be read one part at a time: + +```python +age = 16 +is_teenager = age >= 13 and age <= 19 +print(is_teenager) +``` + +### Part 3: Booleans Control `if` Statements + +An `if` statement runs when its condition is true. + +```python +temperature = 72 + +if temperature >= 70: + print("It is warm outside.") +else: + print("It is not warm outside.") +``` + +The same basic decision in College Board pseudocode is: + +```text +IF(temperature ≥ 70) +{ + DISPLAY("It is warm outside.") +} +ELSE +{ + DISPLAY("It is not warm outside.") +} +``` + +--- ## 3. Classwork & Practice Tasks -### Classwork 1 +### Classwork 1: Predict Before You Run + +Predict each result first. Then run the code and compare. -### Classwork 2 +```python +print(8 > 5) +print(4 == 7) +print("cat" != "dog") +print(10 <= 10) +``` -### Classwork 3 +For each line, write `True` or `False` and one short reason. -### Homework +### Classwork 2: Fix the Logic + +A level should unlock only when the player has **at least 10 coins AND has found the key**. + +```python +coins = 12 +has_key = False + +# Fix the condition so both requirements are needed. +can_unlock = coins >= 10 or has_key + +if can_unlock: + print("Level unlocked") +else: + print("Keep looking") +``` + +Do these four things: +1. Predict what the current code prints. +2. Fix the Boolean expression. +3. Test at least three combinations of `coins` and `has_key`. +4. Explain why the rule needs `and` or `or`. + +### Classwork 3: Translate the Logic + +Start with this Python expression: + +```python +has_ticket or on_guest_list +``` + +Write the same Boolean expression in JavaScript and College Board pseudocode. Then explain what word in **"ticket or guest list"** tells you which operator to use. + +### Homework: Boolean Decision Checker + +A student can use a study room when: +- they are logged in, +- they reserved the room **or** a teacher gave permission, +- and the room is **not** closed. + +```python +logged_in = True +reserved_room = False +teacher_permission = True +room_closed = False + +# Replace False with one Boolean expression. +can_use_room = False + +if can_use_room: + print("Study room access approved") +else: + print("Study room access denied") +``` + +Test at least four cases, including one where the room is closed and one where the student is not logged in. Then explain your Boolean expression in 2–3 sentences. + +--- ## 4. Grading Plan +Point values can be decided separately. For now, the work to check is: +- classwork predictions include an explanation, +- the incorrect Boolean condition is fixed and tested, +- the homework uses the required conditions, +- the student can explain the final expression in normal English. + +--- + ## 5. Lesson Revisions & Feedback Evidence + +- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson. +- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack. +- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids. +- Feedback from a practice run can be added here with the specific change that was made because of it. From bf09fc718a7edb7a010e1b39361bdb76d933303a Mon Sep 17 00:00:00 2001 From: Deyar Raissadat <128260600+DrDeyar@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:35:41 -0700 Subject: [PATCH 26/43] Build interactive Python random numbers lesson --- .../2026-09-15-random_py_sprinters.ipynb | 382 +++++++++++++++++- 1 file changed, 376 insertions(+), 6 deletions(-) diff --git a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb index 34bcb43bc5..09ce70943a 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb @@ -3,7 +3,11 @@ { "cell_type": "raw", "id": "frontmatter", - "metadata": {"vscode": {"languageId": "raw"}}, + "metadata": { + "vscode": { + "languageId": "raw" + } + }, "source": [ "---\n", "layout: post\n", @@ -17,7 +21,7 @@ "toc: false\n", "comments: false\n", "title: 3.15 Python Random Generator (PY)\n", - "description: Python random generator lesson starter.\n", + "description: Learn how Python creates random integers, choices, and decisions through interactive examples.\n", "permalink: /csp/big-idea-3/RandomPY/p3/Lesson\n", "authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n", "---" @@ -25,52 +29,418 @@ }, { "cell_type": "markdown", - "id": "lesson-structure", + "id": "title-intro", "metadata": {}, "source": [ "# 3.15 Python Random Generator\n", "\n", + "Randomness makes programs less predictable and more interactive. It can power dice rolls, shuffled playlists, randomized quiz questions, and computer choices.\n", + "\n", + "> **Warm-up:** Think of one app or game that would become boring if it always made the same choice." + ] + }, + { + "cell_type": "markdown", + "id": "lxd", + "metadata": {}, + "source": [ "## 1. LxD Cycle Process\n", "\n", "### Empathize\n", "\n", + "Students learn random numbers best when they can **predict, run, and immediately see** what each line of code changes. Long explanations are avoided in favor of small examples and visible results.\n", + "\n", "### Define\n", "\n", + "Students need to understand three main ideas:\n", + "\n", + "1. Python must import the `random` module.\n", + "2. Different functions create different types of random results.\n", + "3. A random value can be stored in a variable and used in a decision.\n", + "\n", "### Ideate\n", "\n", + "The lesson uses familiar examples: a dice roll, a random name picker, and a simple computer opponent. Each example adds only one new idea at a time.\n", + "\n", "### Prototype & Test\n", "\n", + "Students first run working examples, then change one part, predict the result, and test their prediction. The final mini-project combines the lesson concepts." + ] + }, + { + "cell_type": "markdown", + "id": "plan", + "metadata": {}, + "source": [ "## 2. Lesson Plan\n", "\n", "### Learning Objective\n", "\n", + "Students will use Python's `random` module to generate random integers, select items from a list, and control decisions in a program.\n", + "\n", "### Success Criteria\n", "\n", + "By the end of the lesson, I can:\n", + "\n", + "- import and use the `random` module\n", + "- explain that both endpoints in `randint(a, b)` are included\n", + "- use `random.choice()` with a list\n", + "- store a random result in a variable\n", + "- use a random value inside an `if` statement" + ] + }, + { + "cell_type": "markdown", + "id": "part1", + "metadata": {}, + "source": [ "### Part 1: Random Integers\n", "\n", + "Python keeps its random tools inside a built-in **module** named `random`. A module is like a toolbox: importing it gives our program access to extra tools.\n", + "\n", + "#### Visual code trace\n", + "\n", + "| Code | What Python does |\n", + "|---|---|\n", + "| `import random` | Opens the random toolbox |\n", + "| `roll = random.randint(1, 6)` | Chooses a whole number from 1 through 6 |\n", + "| `print(roll)` | Displays the chosen number |\n", + "\n", + "The word **inclusive** matters: `random.randint(1, 6)` can return **1, 2, 3, 4, 5, or 6**.\n", + "\n", + "**Predict before running:** Could the result ever be 0? Could it ever be 6?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dice-demo", + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "# Both 1 and 6 are possible\n", + "roll = random.randint(1, 6)\n", + "print(\"You rolled:\", roll)" + ] + }, + { + "cell_type": "markdown", + "id": "part1-check", + "metadata": {}, + "source": [ + "#### Change it and test it\n", + "\n", + "Turn the six-sided die into a twenty-sided die by changing only the two arguments inside `randint()`.\n", + "\n", + "> **Quick check:** What values are possible from `random.randint(4, 8)`? \n", + "> **Answer:** 4, 5, 6, 7, and 8." + ] + }, + { + "cell_type": "markdown", + "id": "part2", + "metadata": {}, + "source": [ "### Part 2: Random Choices\n", "\n", + "`random.choice()` selects one item from a **sequence**, such as a list.\n", + "\n", + "#### Follow the data\n", + "\n", + "`[\"forest\", \"desert\", \"ocean\"]` → `random.choice(locations)` → one chosen item → `print()`\n", + "\n", + "| Piece | Purpose |\n", + "|---|---|\n", + "| `locations = [...]` | Stores all possible choices |\n", + "| `random.choice(locations)` | Selects one list item |\n", + "| `selected` | Remembers the selected item |\n", + "\n", + "**Predict before running:** Is Python returning the item's position or the actual item?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "choice-demo", + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "locations = [\"forest\", \"desert\", \"ocean\"]\n", + "selected = random.choice(locations)\n", + "\n", + "print(\"Your mission location is:\", selected)" + ] + }, + { + "cell_type": "markdown", + "id": "part2-check", + "metadata": {}, + "source": [ + "#### Try this\n", + "\n", + "Add two new locations to the list and run the code several times. Every output should be one of the items in your list.\n", + "\n", + "> `randint()` chooses a whole **number** from a range. \n", + "> `choice()` chooses an **item** from a sequence." + ] + }, + { + "cell_type": "markdown", + "id": "part3", + "metadata": {}, + "source": [ "### Part 3: Random Values in Decisions\n", "\n", + "Randomness becomes more useful when a program reacts to the value it receives. We can combine a random number with an `if` statement.\n", + "\n", + "#### Program flow\n", + "\n", + "1. Generate a number.\n", + "2. Save it in `computer_move`.\n", + "3. Compare the number.\n", + "4. Print the matching action.\n", + "\n", + "| Random value | Program action |\n", + "|---:|---|\n", + "| 1 | Move left |\n", + "| 2 | Move right |\n", + "| 3 | Stay still |\n", + "\n", + "Before running, trace the program as if `computer_move` were 2. Which message would print?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "decision-demo", + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "computer_move = random.randint(1, 3)\n", + "print(\"Computer rolled:\", computer_move)\n", + "\n", + "if computer_move == 1:\n", + " print(\"Computer moves left.\")\n", + "elif computer_move == 2:\n", + " print(\"Computer moves right.\")\n", + "else:\n", + " print(\"Computer stays still.\")" + ] + }, + { + "cell_type": "markdown", + "id": "debug-tip", + "metadata": {}, + "source": [ + "#### Common mistake\n", + "\n", + "This line generates one random value:\n", + "\n", + "```python\n", + "move = random.randint(1, 3)\n", + "```\n", + "\n", + "Reuse `move` in every comparison. Calling `randint()` again inside each condition creates new values, so the program may not behave as expected." + ] + }, + { + "cell_type": "markdown", + "id": "classwork", + "metadata": {}, + "source": [ "## 3. Classwork & Practice Tasks\n", "\n", "### Classwork 1\n", "\n", + "**Build a coin flip.**\n", + "\n", + "1. Generate either 1 or 2.\n", + "2. Print `Heads` when the value is 1.\n", + "3. Print `Tails` when the value is 2.\n", + "4. Run the program at least three times.\n", + "\n", + "**Checkpoint:** Show your code and explain why both outcomes are possible." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "classwork1", + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "# Replace the blanks to finish the coin flip\n", + "flip = random.randint(__, __)\n", + "\n", + "if flip == __:\n", + " print(\"Heads\")\n", + "else:\n", + " print(\"Tails\")" + ] + }, + { + "cell_type": "markdown", + "id": "classwork2", + "metadata": {}, + "source": [ "### Classwork 2\n", "\n", + "**Create a random student picker.**\n", + "\n", + "- Make a list containing at least five names.\n", + "- Use `random.choice()` to select one name.\n", + "- Print a complete sentence containing the selected name.\n", + "\n", + "**Extension:** Add a second list of questions and randomly select both a student and a question." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "classwork2-code", + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "students = [\"Alex\", \"Sam\", \"Jordan\", \"Taylor\", \"Casey\"]\n", + "\n", + "# Write two lines below:\n", + "# 1. Select a random student\n", + "# 2. Print the result\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "classwork3", + "metadata": {}, + "source": [ "### Classwork 3\n", "\n", + "**Create a weather simulator.**\n", + "\n", + "Generate a random number from 1 through 4 and use a decision to print:\n", + "\n", + "- 1: Sunny\n", + "- 2: Cloudy\n", + "- 3: Rainy\n", + "- 4: Windy\n", + "\n", + "Then add one extra message for each result. For example, a sunny result could print `Remember sunglasses.`\n", + "\n", + "**Requirement:** Generate the random number once, store it, and reuse that variable in the conditions." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "classwork3-code", + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "weather_number = random.randint(1, 4)\n", + "\n", + "# Add an if / elif / else decision below\n", + "" + ] + }, + { + "cell_type": "markdown", + "id": "homework", + "metadata": {}, + "source": [ "### Homework\n", "\n", + "#### Mini-project: Random Adventure Generator\n", + "\n", + "Create a short program that produces a different adventure setup each time it runs.\n", + "\n", + "Your program must include:\n", + "\n", + "- `import random`\n", + "- one list of at least four locations\n", + "- one list of at least four items\n", + "- `random.choice()` used on both lists\n", + "- one `random.randint()`\n", + "- an `if` statement that reacts to the random integer\n", + "- a clear final output that combines the results\n", + "\n", + "Example format: `You travel to the forest with a map. Challenge level: 3.`\n", + "\n", + "Do not copy the example exactly. Choose your own theme and outputs." + ] + }, + { + "cell_type": "markdown", + "id": "grading", + "metadata": {}, + "source": [ "## 4. Grading Plan\n", "\n", - "## 5. Lesson Revisions & Feedback Evidence" + "| Category | Points | Full-credit requirement |\n", + "|---|---:|---|\n", + "| Random tools | 3 | Correctly imports `random` and uses both `randint()` and `choice()` |\n", + "| Program logic | 3 | Stores results in variables and uses a correct decision |\n", + "| Required content | 2 | Includes the required lists, range, and output |\n", + "| Testing and explanation | 1 | Runs multiple tests and briefly explains what changes |\n", + "| Readability | 1 | Uses clear variable names, comments, and organized output |\n", + "| **Total** | **10** | |" + ] + }, + { + "cell_type": "markdown", + "id": "exit-ticket", + "metadata": {}, + "source": [ + "### Exit Ticket\n", + "\n", + "Answer in 1–2 sentences each:\n", + "\n", + "1. What is the difference between `random.randint()` and `random.choice()`?\n", + "2. Why should a random result usually be stored in a variable?\n", + "3. If `random.randint(2, 5)` is used, list every possible result." + ] + }, + { + "cell_type": "markdown", + "id": "revisions", + "metadata": {}, + "source": [ + "## 5. Lesson Revisions & Feedback Evidence\n", + "\n", + "After teaching the lesson, record feedback here.\n", + "\n", + "| Feedback source | What was confusing or helpful? | Revision made |\n", + "|---|---|---|\n", + "| Student feedback | | |\n", + "| Peer feedback | | |\n", + "| Teacher observation | | |\n", + "\n", + "Possible evidence includes completed quick checks, common coding errors, student explanations, and improvements between the first and final program." ] } ], "metadata": { - "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, - "language_info": {"name": "python", "version": "3"} + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3" + } }, "nbformat": 4, "nbformat_minor": 5 From ea1a355a3cd3228ba3ff78b6015065f3b0487d93 Mon Sep 17 00:00:00 2001 From: Deyar Raissadat <128260600+DrDeyar@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:38:53 -0700 Subject: [PATCH 27/43] Use plain HTML for random numbers lesson content --- .../2026-09-15-random_py_sprinters.ipynb | 212 ++---------------- 1 file changed, 19 insertions(+), 193 deletions(-) diff --git a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb index 09ce70943a..089c0839e5 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb @@ -32,11 +32,8 @@ "id": "title-intro", "metadata": {}, "source": [ - "# 3.15 Python Random Generator\n", - "\n", - "Randomness makes programs less predictable and more interactive. It can power dice rolls, shuffled playlists, randomized quiz questions, and computer choices.\n", - "\n", - "> **Warm-up:** Think of one app or game that would become boring if it always made the same choice." + "

3.15 Python Random Generator

\n\n

Randomness makes programs less predictable and more interactive. It can power dice rolls, shuffled playlists, randomized quiz questions, and computer choices.

\n\n

Warm-up: Think of one app or game that would become boring if it always made the same choice.

", + "\n\n

How to use this page: Read and trace the Python examples here. Run or edit them in the notebook or your Python editor. Expand the answers after making your prediction.

" ] }, { @@ -44,27 +41,7 @@ "id": "lxd", "metadata": {}, "source": [ - "## 1. LxD Cycle Process\n", - "\n", - "### Empathize\n", - "\n", - "Students learn random numbers best when they can **predict, run, and immediately see** what each line of code changes. Long explanations are avoided in favor of small examples and visible results.\n", - "\n", - "### Define\n", - "\n", - "Students need to understand three main ideas:\n", - "\n", - "1. Python must import the `random` module.\n", - "2. Different functions create different types of random results.\n", - "3. A random value can be stored in a variable and used in a decision.\n", - "\n", - "### Ideate\n", - "\n", - "The lesson uses familiar examples: a dice roll, a random name picker, and a simple computer opponent. Each example adds only one new idea at a time.\n", - "\n", - "### Prototype & Test\n", - "\n", - "Students first run working examples, then change one part, predict the result, and test their prediction. The final mini-project combines the lesson concepts." + "

1. LxD Cycle Process

\n\n

Empathize

\n\n

Students learn random numbers best when they can predict, run, and immediately see what each line of code changes. Long explanations are avoided in favor of small examples and visible results.

\n\n

Define

\n\n

Students need to understand three main ideas:

\n\n
    \n
  1. Python must import the random module.
  2. \n
  3. Different functions create different types of random results.
  4. \n
  5. A random value can be stored in a variable and used in a decision.
  6. \n
\n\n

Ideate

\n\n

The lesson uses familiar examples: a dice roll, a random name picker, and a simple computer opponent. Each example adds only one new idea at a time.

\n\n

Prototype & Test

\n\n

Students first run working examples, then change one part, predict the result, and test their prediction. The final mini-project combines the lesson concepts.

" ] }, { @@ -72,21 +49,7 @@ "id": "plan", "metadata": {}, "source": [ - "## 2. Lesson Plan\n", - "\n", - "### Learning Objective\n", - "\n", - "Students will use Python's `random` module to generate random integers, select items from a list, and control decisions in a program.\n", - "\n", - "### Success Criteria\n", - "\n", - "By the end of the lesson, I can:\n", - "\n", - "- import and use the `random` module\n", - "- explain that both endpoints in `randint(a, b)` are included\n", - "- use `random.choice()` with a list\n", - "- store a random result in a variable\n", - "- use a random value inside an `if` statement" + "

2. Lesson Plan

\n\n

Learning Objective

\n\n

Students will use Python's random module to generate random integers, select items from a list, and control decisions in a program.

\n\n

Success Criteria

\n\n

By the end of the lesson, I can:

\n\n
    \n
  • import and use the random module
  • \n
  • explain that both endpoints in randint(a, b) are included
  • \n
  • use random.choice() with a list
  • \n
  • store a random result in a variable
  • \n
  • use a random value inside an if statement
  • \n
" ] }, { @@ -94,21 +57,7 @@ "id": "part1", "metadata": {}, "source": [ - "### Part 1: Random Integers\n", - "\n", - "Python keeps its random tools inside a built-in **module** named `random`. A module is like a toolbox: importing it gives our program access to extra tools.\n", - "\n", - "#### Visual code trace\n", - "\n", - "| Code | What Python does |\n", - "|---|---|\n", - "| `import random` | Opens the random toolbox |\n", - "| `roll = random.randint(1, 6)` | Chooses a whole number from 1 through 6 |\n", - "| `print(roll)` | Displays the chosen number |\n", - "\n", - "The word **inclusive** matters: `random.randint(1, 6)` can return **1, 2, 3, 4, 5, or 6**.\n", - "\n", - "**Predict before running:** Could the result ever be 0? Could it ever be 6?" + "

Part 1: Random Integers

\n\n

Python keeps its random tools inside a built-in module named random. A module is like a toolbox: importing it gives our program access to extra tools.

\n\n

Visual code trace

\n\n\n\n\n\n\n\n\n
CodeWhat Python does
import randomOpens the random toolbox
roll = random.randint(1, 6)Chooses a whole number from 1 through 6
print(roll)Displays the chosen number
\n\n

The word inclusive matters: random.randint(1, 6) can return 1, 2, 3, 4, 5, or 6.

\n\n

Predict before running: Could the result ever be 0? Could it ever be 6?

" ] }, { @@ -130,12 +79,8 @@ "id": "part1-check", "metadata": {}, "source": [ - "#### Change it and test it\n", - "\n", - "Turn the six-sided die into a twenty-sided die by changing only the two arguments inside `randint()`.\n", - "\n", - "> **Quick check:** What values are possible from `random.randint(4, 8)`? \n", - "> **Answer:** 4, 5, 6, 7, and 8." + "

Change it and test it

\n\n

Turn the six-sided die into a twenty-sided die by changing only the two arguments inside randint().

\n\n

Quick check: What values are possible from random.randint(4, 8)?

\n
Reveal answer

4, 5, 6, 7, and 8. Both endpoints are included.

", + "\n\n

Each integer in the range has the same chance of being selected. Repeated calls can return the same result; a few runs do not have to contain every possible value.

" ] }, { @@ -143,21 +88,7 @@ "id": "part2", "metadata": {}, "source": [ - "### Part 2: Random Choices\n", - "\n", - "`random.choice()` selects one item from a **sequence**, such as a list.\n", - "\n", - "#### Follow the data\n", - "\n", - "`[\"forest\", \"desert\", \"ocean\"]` → `random.choice(locations)` → one chosen item → `print()`\n", - "\n", - "| Piece | Purpose |\n", - "|---|---|\n", - "| `locations = [...]` | Stores all possible choices |\n", - "| `random.choice(locations)` | Selects one list item |\n", - "| `selected` | Remembers the selected item |\n", - "\n", - "**Predict before running:** Is Python returning the item's position or the actual item?" + "

Part 2: Random Choices

\n\n

random.choice() selects one item from a sequence, such as a list.

\n\n

Follow the data

\n\n

[\"forest\", \"desert\", \"ocean\"] → random.choice(locations) → one chosen item → print()

\n\n\n\n\n\n\n\n\n
PiecePurpose
locations = [...]Stores all possible choices
random.choice(locations)Selects one list item
selectedRemembers the selected item
\n\n

Predict before running: Is Python returning the item's position or the actual item?

" ] }, { @@ -180,12 +111,7 @@ "id": "part2-check", "metadata": {}, "source": [ - "#### Try this\n", - "\n", - "Add two new locations to the list and run the code several times. Every output should be one of the items in your list.\n", - "\n", - "> `randint()` chooses a whole **number** from a range. \n", - "> `choice()` chooses an **item** from a sequence." + "

Try this

\n\n

Add two new locations to the list and run the code several times. Every output should be one of the items in your list.

\n\n

randint() chooses a whole number from a range.
\nchoice() chooses an item from a sequence.

" ] }, { @@ -193,24 +119,7 @@ "id": "part3", "metadata": {}, "source": [ - "### Part 3: Random Values in Decisions\n", - "\n", - "Randomness becomes more useful when a program reacts to the value it receives. We can combine a random number with an `if` statement.\n", - "\n", - "#### Program flow\n", - "\n", - "1. Generate a number.\n", - "2. Save it in `computer_move`.\n", - "3. Compare the number.\n", - "4. Print the matching action.\n", - "\n", - "| Random value | Program action |\n", - "|---:|---|\n", - "| 1 | Move left |\n", - "| 2 | Move right |\n", - "| 3 | Stay still |\n", - "\n", - "Before running, trace the program as if `computer_move` were 2. Which message would print?" + "

Part 3: Random Values in Decisions

\n\n

Randomness becomes more useful when a program reacts to the value it receives. We can combine a random number with an if statement.

\n\n

Program flow

\n\n
    \n
  1. Generate a number.
  2. \n
  3. Save it in computer_move.
  4. \n
  5. Compare the number.
  6. \n
  7. Print the matching action.
  8. \n
\n\n\n\n\n\n\n\n\n
Random valueProgram action
1Move left
2Move right
3Stay still
\n\n

Before running, trace the program as if computer_move were 2. Which message would print?

" ] }, { @@ -238,15 +147,7 @@ "id": "debug-tip", "metadata": {}, "source": [ - "#### Common mistake\n", - "\n", - "This line generates one random value:\n", - "\n", - "```python\n", - "move = random.randint(1, 3)\n", - "```\n", - "\n", - "Reuse `move` in every comparison. Calling `randint()` again inside each condition creates new values, so the program may not behave as expected." + "

Common mistake

\n\n

This line generates one random value:

\n\n
move = random.randint(1, 3)
\n\n

Reuse move in every comparison. Calling randint() again inside each condition creates new values, so the program may not behave as expected.

" ] }, { @@ -254,18 +155,7 @@ "id": "classwork", "metadata": {}, "source": [ - "## 3. Classwork & Practice Tasks\n", - "\n", - "### Classwork 1\n", - "\n", - "**Build a coin flip.**\n", - "\n", - "1. Generate either 1 or 2.\n", - "2. Print `Heads` when the value is 1.\n", - "3. Print `Tails` when the value is 2.\n", - "4. Run the program at least three times.\n", - "\n", - "**Checkpoint:** Show your code and explain why both outcomes are possible." + "

3. Classwork & Practice Tasks

\n\n

Classwork 1

\n\n

Build a coin flip.

\n\n
    \n
  1. Generate either 1 or 2.
  2. \n
  3. Print Heads when the value is 1.
  4. \n
  5. Print Tails when the value is 2.
  6. \n
  7. Run the program at least three times.
  8. \n
\n\n

Checkpoint: Show your code and explain why both outcomes are possible.

" ] }, { @@ -291,15 +181,7 @@ "id": "classwork2", "metadata": {}, "source": [ - "### Classwork 2\n", - "\n", - "**Create a random student picker.**\n", - "\n", - "- Make a list containing at least five names.\n", - "- Use `random.choice()` to select one name.\n", - "- Print a complete sentence containing the selected name.\n", - "\n", - "**Extension:** Add a second list of questions and randomly select both a student and a question." + "

Classwork 2

\n\n

Create a random student picker.

\n\n
    \n
  • Make a list containing at least five names.
  • \n
  • Use random.choice() to select one name.
  • \n
  • Print a complete sentence containing the selected name.
  • \n
\n\n

Extension: Add a second list of questions and randomly select both a student and a question.

" ] }, { @@ -324,20 +206,7 @@ "id": "classwork3", "metadata": {}, "source": [ - "### Classwork 3\n", - "\n", - "**Create a weather simulator.**\n", - "\n", - "Generate a random number from 1 through 4 and use a decision to print:\n", - "\n", - "- 1: Sunny\n", - "- 2: Cloudy\n", - "- 3: Rainy\n", - "- 4: Windy\n", - "\n", - "Then add one extra message for each result. For example, a sunny result could print `Remember sunglasses.`\n", - "\n", - "**Requirement:** Generate the random number once, store it, and reuse that variable in the conditions." + "

Classwork 3

\n\n

Create a weather simulator.

\n\n

Generate a random number from 1 through 4 and use a decision to print:

\n\n
    \n
  • 1: Sunny
  • \n
  • 2: Cloudy
  • \n
  • 3: Rainy
  • \n
  • 4: Windy
  • \n
\n\n

Then add one extra message for each result. For example, a sunny result could print Remember sunglasses.

\n\n

Requirement: Generate the random number once, store it, and reuse that variable in the conditions.

" ] }, { @@ -360,25 +229,7 @@ "id": "homework", "metadata": {}, "source": [ - "### Homework\n", - "\n", - "#### Mini-project: Random Adventure Generator\n", - "\n", - "Create a short program that produces a different adventure setup each time it runs.\n", - "\n", - "Your program must include:\n", - "\n", - "- `import random`\n", - "- one list of at least four locations\n", - "- one list of at least four items\n", - "- `random.choice()` used on both lists\n", - "- one `random.randint()`\n", - "- an `if` statement that reacts to the random integer\n", - "- a clear final output that combines the results\n", - "\n", - "Example format: `You travel to the forest with a map. Challenge level: 3.`\n", - "\n", - "Do not copy the example exactly. Choose your own theme and outputs." + "

Homework

\n\n

Mini-project: Random Adventure Generator

\n\n

Create a short program that can produce different adventure setups when it runs. Random results can repeat.

\n\n

Your program must include:

\n\n
    \n
  • import random
  • \n
  • one list of at least four locations
  • \n
  • one list of at least four items
  • \n
  • random.choice() used on both lists
  • \n
  • one random.randint()
  • \n
  • an if statement that reacts to the random integer
  • \n
  • a clear final output that combines the results
  • \n
\n\n

Example format: You travel to the forest with a map. Challenge level: 3.

\n\n

Do not copy the example exactly. Choose your own theme and outputs.

" ] }, { @@ -386,16 +237,7 @@ "id": "grading", "metadata": {}, "source": [ - "## 4. Grading Plan\n", - "\n", - "| Category | Points | Full-credit requirement |\n", - "|---|---:|---|\n", - "| Random tools | 3 | Correctly imports `random` and uses both `randint()` and `choice()` |\n", - "| Program logic | 3 | Stores results in variables and uses a correct decision |\n", - "| Required content | 2 | Includes the required lists, range, and output |\n", - "| Testing and explanation | 1 | Runs multiple tests and briefly explains what changes |\n", - "| Readability | 1 | Uses clear variable names, comments, and organized output |\n", - "| **Total** | **10** | |" + "

4. Grading Plan

\n\n\n\n\n\n\n\n\n\n\n\n
CategoryPointsFull-credit requirement
Random tools3Correctly imports random and uses both randint() and choice()
Program logic3Stores results in variables and uses a correct decision
Required content2Includes the required lists, range, and output
Testing and explanation1Runs multiple tests and briefly explains what changes
Readability1Uses clear variable names, comments, and organized output
Total10
" ] }, { @@ -403,13 +245,7 @@ "id": "exit-ticket", "metadata": {}, "source": [ - "### Exit Ticket\n", - "\n", - "Answer in 1–2 sentences each:\n", - "\n", - "1. What is the difference between `random.randint()` and `random.choice()`?\n", - "2. Why should a random result usually be stored in a variable?\n", - "3. If `random.randint(2, 5)` is used, list every possible result." + "

Exit Ticket

\n\n

Answer in 1–2 sentences each:

\n\n
    \n
  1. What is the difference between random.randint() and random.choice()?
  2. \n
  3. Why should a random result usually be stored in a variable?
  4. \n
  5. If random.randint(2, 5) is used, list every possible result.
  6. \n
" ] }, { @@ -417,17 +253,7 @@ "id": "revisions", "metadata": {}, "source": [ - "## 5. Lesson Revisions & Feedback Evidence\n", - "\n", - "After teaching the lesson, record feedback here.\n", - "\n", - "| Feedback source | What was confusing or helpful? | Revision made |\n", - "|---|---|---|\n", - "| Student feedback | | |\n", - "| Peer feedback | | |\n", - "| Teacher observation | | |\n", - "\n", - "Possible evidence includes completed quick checks, common coding errors, student explanations, and improvements between the first and final program." + "

5. Lesson Revisions & Feedback Evidence

\n\n

After teaching the lesson, record feedback here.

\n\n\n\n\n\n\n\n\n
Feedback sourceWhat was confusing or helpful?Revision made
Student feedback
Peer feedback
Teacher observation
\n\n

Possible evidence includes completed quick checks, common coding errors, student explanations, and improvements between the first and final program.

" ] } ], @@ -444,4 +270,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} \ No newline at end of file +} From bb4a49b9181f977365cab3a05aa34c078f9e6a4a Mon Sep 17 00:00:00 2001 From: Deyar Raissadat <128260600+DrDeyar@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:38:59 -0700 Subject: [PATCH 28/43] Sync random numbers Markdown lesson with HTML notebook content --- ...2026-09-15-random_py_sprinters_IPYNB_2_.md | 294 ++++++++++++++++-- 1 file changed, 274 insertions(+), 20 deletions(-) diff --git a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md index 37007572af..e2c4db57ec 100644 --- a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md +++ b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md @@ -10,45 +10,299 @@ microblog: true toc: false comments: false title: 3.15 Python Random Generator (PY) -description: Python random generator lesson starter. +description: Learn how Python creates random integers, choices, and decisions through interactive examples. permalink: /csp/big-idea-3/RandomPY/p3/Lesson authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar --- -# 3.15 Python Random Generator +

3.15 Python Random Generator

-## 1. LxD Cycle Process +

Randomness makes programs less predictable and more interactive. It can power dice rolls, shuffled playlists, randomized quiz questions, and computer choices.

-### Empathize +

Warm-up: Think of one app or game that would become boring if it always made the same choice.

-### Define +

How to use this page: Read and trace the Python examples here. Run or edit them in the notebook or your Python editor. Expand the answers after making your prediction.

-### Ideate +

1. LxD Cycle Process

-### Prototype & Test +

Empathize

-## 2. Lesson Plan +

Students learn random numbers best when they can predict, run, and immediately see what each line of code changes. Long explanations are avoided in favor of small examples and visible results.

-### Learning Objective +

Define

-### Success Criteria +

Students need to understand three main ideas:

-### Part 1: Random Integers +
    +
  1. Python must import the random module.
  2. +
  3. Different functions create different types of random results.
  4. +
  5. A random value can be stored in a variable and used in a decision.
  6. +
-### Part 2: Random Choices +

Ideate

-### Part 3: Random Values in Decisions +

The lesson uses familiar examples: a dice roll, a random name picker, and a simple computer opponent. Each example adds only one new idea at a time.

-## 3. Classwork & Practice Tasks +

Prototype & Test

-### Classwork 1 +

Students first run working examples, then change one part, predict the result, and test their prediction. The final mini-project combines the lesson concepts.

-### Classwork 2 +

2. Lesson Plan

-### Classwork 3 +

Learning Objective

-### Homework +

Students will use Python's random module to generate random integers, select items from a list, and control decisions in a program.

-## 4. Grading Plan +

Success Criteria

-## 5. Lesson Revisions & Feedback Evidence +

By the end of the lesson, I can:

+ +
    +
  • import and use the random module
  • +
  • explain that both endpoints in randint(a, b) are included
  • +
  • use random.choice() with a list
  • +
  • store a random result in a variable
  • +
  • use a random value inside an if statement
  • +
+ +

Part 1: Random Integers

+ +

Python keeps its random tools inside a built-in module named random. A module is like a toolbox: importing it gives our program access to extra tools.

+ +

Visual code trace

+ + + + + + + + +
CodeWhat Python does
import randomOpens the random toolbox
roll = random.randint(1, 6)Chooses a whole number from 1 through 6
print(roll)Displays the chosen number
+ +

The word inclusive matters: random.randint(1, 6) can return 1, 2, 3, 4, 5, or 6.

+ +

Predict before running: Could the result ever be 0? Could it ever be 6?

+ +
import random
+
+# Both 1 and 6 are possible
+roll = random.randint(1, 6)
+print("You rolled:", roll)
+ +

Change it and test it

+ +

Turn the six-sided die into a twenty-sided die by changing only the two arguments inside randint().

+ +

Quick check: What values are possible from random.randint(4, 8)?

+
Reveal answer

4, 5, 6, 7, and 8. Both endpoints are included.

+ +

Each integer in the range has the same chance of being selected. Repeated calls can return the same result; a few runs do not have to contain every possible value.

+ +

Part 2: Random Choices

+ +

random.choice() selects one item from a sequence, such as a list.

+ +

Follow the data

+ +

["forest", "desert", "ocean"] → random.choice(locations) → one chosen item → print()

+ + + + + + + + +
PiecePurpose
locations = [...]Stores all possible choices
random.choice(locations)Selects one list item
selectedRemembers the selected item
+ +

Predict before running: Is Python returning the item's position or the actual item?

+ +
import random
+
+locations = ["forest", "desert", "ocean"]
+selected = random.choice(locations)
+
+print("Your mission location is:", selected)
+ +

Try this

+ +

Add two new locations to the list and run the code several times. Every output should be one of the items in your list.

+ +

randint() chooses a whole number from a range.
+choice() chooses an item from a sequence.

+ +

Part 3: Random Values in Decisions

+ +

Randomness becomes more useful when a program reacts to the value it receives. We can combine a random number with an if statement.

+ +

Program flow

+ +
    +
  1. Generate a number.
  2. +
  3. Save it in computer_move.
  4. +
  5. Compare the number.
  6. +
  7. Print the matching action.
  8. +
+ + + + + + + + +
Random valueProgram action
1Move left
2Move right
3Stay still
+ +

Before running, trace the program as if computer_move were 2. Which message would print?

+ +
import random
+
+computer_move = random.randint(1, 3)
+print("Computer rolled:", computer_move)
+
+if computer_move == 1:
+    print("Computer moves left.")
+elif computer_move == 2:
+    print("Computer moves right.")
+else:
+    print("Computer stays still.")
+ +

Common mistake

+ +

This line generates one random value:

+ +
move = random.randint(1, 3)
+ +

Reuse move in every comparison. Calling randint() again inside each condition creates new values, so the program may not behave as expected.

+ +

3. Classwork & Practice Tasks

+ +

Classwork 1

+ +

Build a coin flip.

+ +
    +
  1. Generate either 1 or 2.
  2. +
  3. Print Heads when the value is 1.
  4. +
  5. Print Tails when the value is 2.
  6. +
  7. Run the program at least three times.
  8. +
+ +

Checkpoint: Show your code and explain why both outcomes are possible.

+ +
import random
+
+# Replace the blanks to finish the coin flip
+flip = random.randint(__, __)
+
+if flip == __:
+    print("Heads")
+else:
+    print("Tails")
+ +

Classwork 2

+ +

Create a random student picker.

+ +
    +
  • Make a list containing at least five names.
  • +
  • Use random.choice() to select one name.
  • +
  • Print a complete sentence containing the selected name.
  • +
+ +

Extension: Add a second list of questions and randomly select both a student and a question.

+ +
import random
+
+students = ["Alex", "Sam", "Jordan", "Taylor", "Casey"]
+
+# Write two lines below:
+# 1. Select a random student
+# 2. Print the result
+
+ +

Classwork 3

+ +

Create a weather simulator.

+ +

Generate a random number from 1 through 4 and use a decision to print:

+ +
    +
  • 1: Sunny
  • +
  • 2: Cloudy
  • +
  • 3: Rainy
  • +
  • 4: Windy
  • +
+ +

Then add one extra message for each result. For example, a sunny result could print Remember sunglasses.

+ +

Requirement: Generate the random number once, store it, and reuse that variable in the conditions.

+ +
import random
+
+weather_number = random.randint(1, 4)
+
+# Add an if / elif / else decision below
+
+ +

Homework

+ +

Mini-project: Random Adventure Generator

+ +

Create a short program that can produce different adventure setups when it runs. Random results can repeat.

+ +

Your program must include:

+ +
    +
  • import random
  • +
  • one list of at least four locations
  • +
  • one list of at least four items
  • +
  • random.choice() used on both lists
  • +
  • one random.randint()
  • +
  • an if statement that reacts to the random integer
  • +
  • a clear final output that combines the results
  • +
+ +

Example format: You travel to the forest with a map. Challenge level: 3.

+ +

Do not copy the example exactly. Choose your own theme and outputs.

+ +

4. Grading Plan

+ + + + + + + + + + + +
CategoryPointsFull-credit requirement
Random tools3Correctly imports random and uses both randint() and choice()
Program logic3Stores results in variables and uses a correct decision
Required content2Includes the required lists, range, and output
Testing and explanation1Runs multiple tests and briefly explains what changes
Readability1Uses clear variable names, comments, and organized output
Total10
+ +

Exit Ticket

+ +

Answer in 1–2 sentences each:

+ +
    +
  1. What is the difference between random.randint() and random.choice()?
  2. +
  3. Why should a random result usually be stored in a variable?
  4. +
  5. If random.randint(2, 5) is used, list every possible result.
  6. +
+ +

5. Lesson Revisions & Feedback Evidence

+ +

After teaching the lesson, record feedback here.

+ + + + + + + + +
Feedback sourceWhat was confusing or helpful?Revision made
Student feedback
Peer feedback
Teacher observation
+ +

Possible evidence includes completed quick checks, common coding errors, student explanations, and improvements between the first and final program.

From ba7942736a32df4bfb0baa4c04e22181aac6125f Mon Sep 17 00:00:00 2001 From: aRYA622-y <128329936+aRYA622-y@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:40:16 -0700 Subject: [PATCH 29/43] Restore Boolean Python lesson from converted notebook --- _notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md | 1 - 1 file changed, 1 deletion(-) diff --git a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md index 2dd23c618e..91c83deb6f 100644 --- a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md +++ b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md @@ -12,7 +12,6 @@ comments: false title: 3.5 Boolean Expressions (PY) description: Learn Boolean expressions in Python using the five-part LxD lesson format. permalink: /python/boolean/py -authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar --- # 3.5 Boolean Expressions in Python From 66578e35f468cd98a5f1249f37d2f815f7ec87da Mon Sep 17 00:00:00 2001 From: aRYA622-y <128329936+aRYA622-y@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:40:40 -0700 Subject: [PATCH 30/43] Add separate Boolean JavaScript lesson --- .../2026-09-15-boolean_scratchers_js.md | 215 ++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 _notebooks/2026-09-15-boolean_scratchers_js.md diff --git a/_notebooks/2026-09-15-boolean_scratchers_js.md b/_notebooks/2026-09-15-boolean_scratchers_js.md new file mode 100644 index 0000000000..5eaf463b6c --- /dev/null +++ b/_notebooks/2026-09-15-boolean_scratchers_js.md @@ -0,0 +1,215 @@ +--- +layout: post +categories: [JavaScript, Boolean-Expressions] +lesson_language: JavaScript +lesson_topic: Boolean-Expressions +lesson_part: interactive +lesson_type: lesson +codemirror: true +microblog: true +toc: false +comments: false +title: 3.5 Boolean Expressions (JS) +description: Learn Boolean expressions in JavaScript using the five-part LxD lesson format. +permalink: /javascript/boolean/js +--- + +# 3.5 Boolean Expressions in JavaScript + +A **Boolean expression** is a question that evaluates to only `true` or `false`. JavaScript is the main language for this lesson. Python and College Board pseudocode are only used to compare the same idea in different forms. + +## 1. LxD Cycle Process + +**Empathize:** Boolean expressions can look simple, but it is easy to mix up `&&` and `||`, forget a boundary such as `>=`, or write a condition that does not match the rule in normal English. + +**Define:** +- **POV:** CSP students need a clear way to turn real-world rules into Boolean expressions so their programs make the correct decisions. +- **Learning Goal:** Students will be able to evaluate, write, test, and explain Boolean expressions in JavaScript. + +**Ideate:** +- **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program? +- **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker. + +**Prototype & Test:** Use the classwork below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule. + +--- + +## 2. Lesson Plan + +**Learning Objective:** By the end of this lesson, you will be able to use comparisons, `&&`, `||`, and `!` to create Boolean expressions and use them in JavaScript decisions. + +**Success Criteria:** You can predict whether an expression is `true` or `false`, write a condition from a rule in normal English, and test the condition with more than one set of values. + +### Part 1: Comparisons Create Booleans + +JavaScript comparison operators return `true` or `false`. + +| JavaScript | Meaning | Example | +| --- | --- | --- | +| `===` | equal to | `score === 90` | +| `!==` | not equal to | `score !== 0` | +| `>` | greater than | `score > 70` | +| `<` | less than | `age < 18` | +| `>=` | greater than or equal to | `score >= 70` | +| `<=` | less than or equal to | `age <= 18` | + +```javascript +let score = 82; + +console.log(score >= 70); +console.log(score === 100); +console.log(score !== 0); +``` + +Remember: +- `score = 90` assigns a value. +- `score === 90` compares both value and type. + +### Part 2: `&&`, `||`, and `!` + +Sometimes one comparison is not enough. + +| Idea | JavaScript | Python | College Board pseudocode | +| --- | --- | --- | --- | +| both must be true | `&&` | `and` | `AND` | +| at least one is true | `||` | `or` | `OR` | +| reverse true/false | `!` | `not` | `NOT` | + +```javascript +let hasId = true; +let hasTicket = false; + +console.log(hasId && hasTicket); +console.log(hasId || hasTicket); +console.log(!hasTicket); +``` + +A longer expression can be read one part at a time: + +```javascript +let age = 16; +let isTeenager = age >= 13 && age <= 19; +console.log(isTeenager); +``` + +### Part 3: Booleans Control `if` Statements + +An `if` statement runs when its condition is true. + +```javascript +let temperature = 72; + +if (temperature >= 70) { + console.log("It is warm outside."); +} else { + console.log("It is not warm outside."); +} +``` + +The same basic decision in College Board pseudocode is: + +```text +IF(temperature ≥ 70) +{ + DISPLAY("It is warm outside.") +} +ELSE +{ + DISPLAY("It is not warm outside.") +} +``` + +--- + +## 3. Classwork & Practice Tasks + +### Classwork 1: Predict Before You Run + +Predict each result first. Then run the code and compare. + +```javascript +console.log(8 > 5); +console.log(4 === 7); +console.log("cat" !== "dog"); +console.log(10 <= 10); +``` + +For each line, write `true` or `false` and one short reason. + +### Classwork 2: Fix the Logic + +A level should unlock only when the player has **at least 10 coins AND has found the key**. + +```javascript +let coins = 12; +let hasKey = false; + +// Fix the condition so both requirements are needed. +let canUnlock = coins >= 10 || hasKey; + +if (canUnlock) { + console.log("Level unlocked"); +} else { + console.log("Keep looking"); +} +``` + +Do these four things: +1. Predict what the current code prints. +2. Fix the Boolean expression. +3. Test at least three combinations of `coins` and `hasKey`. +4. Explain why the rule needs `&&` or `||`. + +### Classwork 3: Translate the Logic + +Start with this JavaScript expression: + +```javascript +hasTicket || onGuestList +``` + +Write the same Boolean expression in Python and College Board pseudocode. Then explain what word in **"ticket or guest list"** tells you which operator to use. + +### Homework: Boolean Decision Checker + +A student can use a study room when: +- they are logged in, +- they reserved the room **or** a teacher gave permission, +- and the room is **not** closed. + +```javascript +let loggedIn = true; +let reservedRoom = false; +let teacherPermission = true; +let roomClosed = false; + +// Replace false with one Boolean expression. +let canUseRoom = false; + +if (canUseRoom) { + console.log("Study room access approved"); +} else { + console.log("Study room access denied"); +} +``` + +Test at least four cases, including one where the room is closed and one where the student is not logged in. Then explain your Boolean expression in 2–3 sentences. + +--- + +## 4. Grading Plan + +Point values can be decided separately. For now, the work to check is: +- classwork predictions include an explanation, +- the incorrect Boolean condition is fixed and tested, +- the homework uses the required conditions, +- the student can explain the final expression in normal English. + +--- + +## 5. Lesson Revisions & Feedback Evidence + +- The lesson is organized into the same numbered `1` through `5` structure used by the Python lesson. +- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack. +- JavaScript stays the main coding language, while Python and College Board pseudocode are short comparison aids. +- Feedback from a practice run can be added here with the specific change that was made because of it. From 82df013a1a7a60bd267d907dd5e344f69c7d13f5 Mon Sep 17 00:00:00 2001 From: Deyar Raissadat <128260600+DrDeyar@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:45:24 -0700 Subject: [PATCH 31/43] Shorten random lesson and add native HTML highlights --- .../2026-09-15-random_py_sprinters.ipynb | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb index 089c0839e5..5ea78500a0 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb @@ -32,8 +32,7 @@ "id": "title-intro", "metadata": {}, "source": [ - "

3.15 Python Random Generator

\n\n

Randomness makes programs less predictable and more interactive. It can power dice rolls, shuffled playlists, randomized quiz questions, and computer choices.

\n\n

Warm-up: Think of one app or game that would become boring if it always made the same choice.

", - "\n\n

How to use this page: Read and trace the Python examples here. Run or edit them in the notebook or your Python editor. Expand the answers after making your prediction.

" + "

3.15 Python Random Generator

\n

Warm-up: What would happen if a game’s computer opponent always made the same move?

\n

Predict → run → change. Follow the examples here; run them in your notebook or Python editor.

" ] }, { @@ -41,7 +40,7 @@ "id": "lxd", "metadata": {}, "source": [ - "

1. LxD Cycle Process

\n\n

Empathize

\n\n

Students learn random numbers best when they can predict, run, and immediately see what each line of code changes. Long explanations are avoided in favor of small examples and visible results.

\n\n

Define

\n\n

Students need to understand three main ideas:

\n\n
    \n
  1. Python must import the random module.
  2. \n
  3. Different functions create different types of random results.
  4. \n
  5. A random value can be stored in a variable and used in a decision.
  6. \n
\n\n

Ideate

\n\n

The lesson uses familiar examples: a dice roll, a random name picker, and a simple computer opponent. Each example adds only one new idea at a time.

\n\n

Prototype & Test

\n\n

Students first run working examples, then change one part, predict the result, and test their prediction. The final mini-project combines the lesson concepts.

" + "

1. LxD Cycle Process

\n
\nTeaching plan\n

Empathize

\n

Make randomness visible through short, familiar examples.

\n

Define

\n

Choose a number, pick an item, and use the result in a decision.

\n

Ideate

\n

Use a die, a location picker, and a computer opponent.

\n

Prototype & Test

\n

Students predict an output, run the code, then change one part.

\n
" ] }, { @@ -49,7 +48,7 @@ "id": "plan", "metadata": {}, "source": [ - "

2. Lesson Plan

\n\n

Learning Objective

\n\n

Students will use Python's random module to generate random integers, select items from a list, and control decisions in a program.

\n\n

Success Criteria

\n\n

By the end of the lesson, I can:

\n\n
    \n
  • import and use the random module
  • \n
  • explain that both endpoints in randint(a, b) are included
  • \n
  • use random.choice() with a list
  • \n
  • store a random result in a variable
  • \n
  • use a random value inside an if statement
  • \n
" + "

2. Lesson Plan

\n

Learning Objective

\n

Use Python’s random module to make unpredictable choices.

\n

Success Criteria

\n
    \n
  • Choose valid bounds for randint().
  • \n
  • Select a list item with choice().
  • \n
  • Store a result and use it in an if statement.
  • \n
" ] }, { @@ -57,7 +56,7 @@ "id": "part1", "metadata": {}, "source": [ - "

Part 1: Random Integers

\n\n

Python keeps its random tools inside a built-in module named random. A module is like a toolbox: importing it gives our program access to extra tools.

\n\n

Visual code trace

\n\n\n\n\n\n\n\n\n
CodeWhat Python does
import randomOpens the random toolbox
roll = random.randint(1, 6)Chooses a whole number from 1 through 6
print(roll)Displays the chosen number
\n\n

The word inclusive matters: random.randint(1, 6) can return 1, 2, 3, 4, 5, or 6.

\n\n

Predict before running: Could the result ever be 0? Could it ever be 6?

" + "

Part 1: Random Integers

\n

import random gives Python access to its built-in random tools.

\n\n\n\n\n\n\n\n\n
Read the code from top to bottom
CodeJob
import randomLoad the tools
roll = random.randint(1, 6)Pick and store a whole number
print(roll)Display it
\n

Both endpoints count. Possible results: 1, 2, 3, 4, 5, 6.

\n

Predict: Can it return 0? What about 6?

" ] }, { @@ -79,8 +78,7 @@ "id": "part1-check", "metadata": {}, "source": [ - "

Change it and test it

\n\n

Turn the six-sided die into a twenty-sided die by changing only the two arguments inside randint().

\n\n

Quick check: What values are possible from random.randint(4, 8)?

\n
Reveal answer

4, 5, 6, 7, and 8. Both endpoints are included.

", - "\n\n

Each integer in the range has the same chance of being selected. Repeated calls can return the same result; a few runs do not have to contain every possible value.

" + "

Change it: Make this a twenty-sided die.

\n

Quick check: List the possible results of random.randint(4, 8).

\n
Reveal answer

4, 5, 6, 7, 8.

\n

Each number has an equal chance. Random results can repeat. Six rolls do not guarantee six different numbers.

" ] }, { @@ -88,7 +86,7 @@ "id": "part2", "metadata": {}, "source": [ - "

Part 2: Random Choices

\n\n

random.choice() selects one item from a sequence, such as a list.

\n\n

Follow the data

\n\n

[\"forest\", \"desert\", \"ocean\"] → random.choice(locations) → one chosen item → print()

\n\n\n\n\n\n\n\n\n
PiecePurpose
locations = [...]Stores all possible choices
random.choice(locations)Selects one list item
selectedRemembers the selected item
\n\n

Predict before running: Is Python returning the item's position or the actual item?

" + "

Part 2: Random Choices

\n

random.choice() picks one item from a list.

\n

Predict: Will this code print a location or its position in the list?

" ] }, { @@ -111,7 +109,7 @@ "id": "part2-check", "metadata": {}, "source": [ - "

Try this

\n\n

Add two new locations to the list and run the code several times. Every output should be one of the items in your list.

\n\n

randint() chooses a whole number from a range.
\nchoice() chooses an item from a sequence.

" + "
Reveal answer and trace\n

It prints the location itself. For example:

\n\n\n\n\n\n\n\n
StepExample value
Available items[\"forest\", \"desert\", \"ocean\"]
Item stored in selected\"ocean\"
Printed messageYour mission location is: ocean
\n

This is one possible run, not a fixed output.

\n
\n

Change it: Add two locations. Run again.

" ] }, { @@ -119,7 +117,7 @@ "id": "part3", "metadata": {}, "source": [ - "

Part 3: Random Values in Decisions

\n\n

Randomness becomes more useful when a program reacts to the value it receives. We can combine a random number with an if statement.

\n\n

Program flow

\n\n
    \n
  1. Generate a number.
  2. \n
  3. Save it in computer_move.
  4. \n
  5. Compare the number.
  6. \n
  7. Print the matching action.
  8. \n
\n\n\n\n\n\n\n\n\n
Random valueProgram action
1Move left
2Move right
3Stay still
\n\n

Before running, trace the program as if computer_move were 2. Which message would print?

" + "

Part 3: Random Values in Decisions

\n

An if statement turns a random number into an action.

\n\n\n\n\n\n\n\n
ValueAction
1Move left
2Move right
3Stay still
\n

Trace it: If computer_move is 2, which branch runs?

" ] }, { @@ -147,7 +145,7 @@ "id": "debug-tip", "metadata": {}, "source": [ - "

Common mistake

\n\n

This line generates one random value:

\n\n
move = random.randint(1, 3)
\n\n

Reuse move in every comparison. Calling randint() again inside each condition creates new values, so the program may not behave as expected.

" + "
Reveal the branch

The elif branch prints Computer moves right.

\n

Generate once, reuse the variable. Calling randint() again makes a new draw—it may not match the first one.

" ] }, { @@ -155,7 +153,7 @@ "id": "classwork", "metadata": {}, "source": [ - "

3. Classwork & Practice Tasks

\n\n

Classwork 1

\n\n

Build a coin flip.

\n\n
    \n
  1. Generate either 1 or 2.
  2. \n
  3. Print Heads when the value is 1.
  4. \n
  5. Print Tails when the value is 2.
  6. \n
  7. Run the program at least three times.
  8. \n
\n\n

Checkpoint: Show your code and explain why both outcomes are possible.

" + "

3. Classwork & Practice Tasks

\n

Classwork 1

\n

Coin flip: Fill the blanks so 1 prints Heads and 2 prints Tails. Then run it three times.

\n

Explain: Why are both outcomes possible?

" ] }, { @@ -181,7 +179,7 @@ "id": "classwork2", "metadata": {}, "source": [ - "

Classwork 2

\n\n

Create a random student picker.

\n\n
    \n
  • Make a list containing at least five names.
  • \n
  • Use random.choice() to select one name.
  • \n
  • Print a complete sentence containing the selected name.
  • \n
\n\n

Extension: Add a second list of questions and randomly select both a student and a question.

" + "

Classwork 2

\n

Student picker: Use choice() to pick from at least five names and print a sentence with the result.

\n
Optional challenge

Add a list of questions. Pick both a student and a question.

" ] }, { @@ -206,7 +204,7 @@ "id": "classwork3", "metadata": {}, "source": [ - "

Classwork 3

\n\n

Create a weather simulator.

\n\n

Generate a random number from 1 through 4 and use a decision to print:

\n\n
    \n
  • 1: Sunny
  • \n
  • 2: Cloudy
  • \n
  • 3: Rainy
  • \n
  • 4: Windy
  • \n
\n\n

Then add one extra message for each result. For example, a sunny result could print Remember sunglasses.

\n\n

Requirement: Generate the random number once, store it, and reuse that variable in the conditions.

" + "

Classwork 3

\n

Weather simulator: Use one random draw and an if / elif / else decision.

\n\n\n\n\n\n\n\n\n
NumberWeather
1Sunny
2Cloudy
3Rainy
4Windy
\n

Print the weather and one matching suggestion, such as Bring an umbrella.

" ] }, { @@ -229,7 +227,7 @@ "id": "homework", "metadata": {}, "source": [ - "

Homework

\n\n

Mini-project: Random Adventure Generator

\n\n

Create a short program that can produce different adventure setups when it runs. Random results can repeat.

\n\n

Your program must include:

\n\n
    \n
  • import random
  • \n
  • one list of at least four locations
  • \n
  • one list of at least four items
  • \n
  • random.choice() used on both lists
  • \n
  • one random.randint()
  • \n
  • an if statement that reacts to the random integer
  • \n
  • a clear final output that combines the results
  • \n
\n\n

Example format: You travel to the forest with a map. Challenge level: 3.

\n\n

Do not copy the example exactly. Choose your own theme and outputs.

" + "

Homework

\n

Mini-project: Random Adventure Generator

\n

Choose your own theme. Your program must:

\n
    \n
  • Import random.
  • \n
  • Use choice() on two lists: at least four locations and four items.
  • \n
  • Use randint() for a challenge level from 1 to 5.
  • \n
  • Use an if statement to react to that level.
  • \n
  • Print the location, item, level, and reaction.
  • \n
\n

Possible output: You reach the ocean with a map. Level: 4. Find a guide!

\n

Submit your code, three test outputs, and one sentence explaining what can change.

" ] }, { @@ -237,7 +235,7 @@ "id": "grading", "metadata": {}, "source": [ - "

4. Grading Plan

\n\n\n\n\n\n\n\n\n\n\n\n
CategoryPointsFull-credit requirement
Random tools3Correctly imports random and uses both randint() and choice()
Program logic3Stores results in variables and uses a correct decision
Required content2Includes the required lists, range, and output
Testing and explanation1Runs multiple tests and briefly explains what changes
Readability1Uses clear variable names, comments, and organized output
Total10
" + "

4. Grading Plan

\n\n\n\n\n\n\n\n\n\n\n
Homework rubric — 10 points
RequirementPoints
Correct import, randint(), and choice()3
Stored results and a working decision3
Required lists, range, and output2
Three test outputs and an explanation1
Clear names and readable code1
" ] }, { @@ -245,7 +243,7 @@ "id": "exit-ticket", "metadata": {}, "source": [ - "

Exit Ticket

\n\n

Answer in 1–2 sentences each:

\n\n
    \n
  1. What is the difference between random.randint() and random.choice()?
  2. \n
  3. Why should a random result usually be stored in a variable?
  4. \n
  5. If random.randint(2, 5) is used, list every possible result.
  6. \n
" + "

Exit Ticket

\n
    \n
  1. randint() or choice(): which picks a name?
  2. \n
  3. Why store a random result before testing it?
  4. \n
  5. What can random.randint(2, 5) return?
  6. \n
" ] }, { @@ -253,7 +251,7 @@ "id": "revisions", "metadata": {}, "source": [ - "

5. Lesson Revisions & Feedback Evidence

\n\n

After teaching the lesson, record feedback here.

\n\n\n\n\n\n\n\n\n
Feedback sourceWhat was confusing or helpful?Revision made
Student feedback
Peer feedback
Teacher observation
\n\n

Possible evidence includes completed quick checks, common coding errors, student explanations, and improvements between the first and final program.

" + "

5. Lesson Revisions & Feedback Evidence

\n
\nRecord feedback after teaching\n\n\n\n\n\n\n\n
SourceFeedback / evidenceChange made
Student
Peer
Teacher
\n
" ] } ], From 8f3ebcf6003a9ac1ffe5953e605054e089573029 Mon Sep 17 00:00:00 2001 From: Deyar Raissadat <128260600+DrDeyar@users.noreply.github.com> Date: Wed, 16 Sep 2026 20:45:29 -0700 Subject: [PATCH 32/43] Sync concise HTML random lesson and native highlights --- ...2026-09-15-random_py_sprinters_IPYNB_2_.md | 264 ++++++------------ 1 file changed, 85 insertions(+), 179 deletions(-) diff --git a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md index e2c4db57ec..edee960bdc 100644 --- a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md +++ b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md @@ -16,73 +16,45 @@ authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar ---

3.15 Python Random Generator

- -

Randomness makes programs less predictable and more interactive. It can power dice rolls, shuffled playlists, randomized quiz questions, and computer choices.

- -

Warm-up: Think of one app or game that would become boring if it always made the same choice.

- -

How to use this page: Read and trace the Python examples here. Run or edit them in the notebook or your Python editor. Expand the answers after making your prediction.

+

Warm-up: What would happen if a game’s computer opponent always made the same move?

+

Predict → run → change. Follow the examples here; run them in your notebook or Python editor.

1. LxD Cycle Process

- +
+Teaching plan

Empathize

- -

Students learn random numbers best when they can predict, run, and immediately see what each line of code changes. Long explanations are avoided in favor of small examples and visible results.

- +

Make randomness visible through short, familiar examples.

Define

- -

Students need to understand three main ideas:

- -
    -
  1. Python must import the random module.
  2. -
  3. Different functions create different types of random results.
  4. -
  5. A random value can be stored in a variable and used in a decision.
  6. -
- +

Choose a number, pick an item, and use the result in a decision.

Ideate

- -

The lesson uses familiar examples: a dice roll, a random name picker, and a simple computer opponent. Each example adds only one new idea at a time.

- +

Use a die, a location picker, and a computer opponent.

Prototype & Test

- -

Students first run working examples, then change one part, predict the result, and test their prediction. The final mini-project combines the lesson concepts.

+

Students predict an output, run the code, then change one part.

+

2. Lesson Plan

-

Learning Objective

- -

Students will use Python's random module to generate random integers, select items from a list, and control decisions in a program.

- +

Use Python’s random module to make unpredictable choices.

Success Criteria

- -

By the end of the lesson, I can:

-
    -
  • import and use the random module
  • -
  • explain that both endpoints in randint(a, b) are included
  • -
  • use random.choice() with a list
  • -
  • store a random result in a variable
  • -
  • use a random value inside an if statement
  • +
  • Choose valid bounds for randint().
  • +
  • Select a list item with choice().
  • +
  • Store a result and use it in an if statement.

Part 1: Random Integers

- -

Python keeps its random tools inside a built-in module named random. A module is like a toolbox: importing it gives our program access to extra tools.

- -

Visual code trace

- +

import random gives Python access to its built-in random tools.

- + + - - - + + +
CodeWhat Python does
Read the code from top to bottom
CodeJob
import randomOpens the random toolbox
roll = random.randint(1, 6)Chooses a whole number from 1 through 6
print(roll)Displays the chosen number
import randomLoad the tools
roll = random.randint(1, 6)Pick and store a whole number
print(roll)Display it
- -

The word inclusive matters: random.randint(1, 6) can return 1, 2, 3, 4, 5, or 6.

- -

Predict before running: Could the result ever be 0? Could it ever be 6?

+

Both endpoints count. Possible results: 1, 2, 3, 4, 5, 6.

+

Predict: Can it return 0? What about 6?

import random
 
@@ -90,33 +62,14 @@ authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar
 roll = random.randint(1, 6)
 print("You rolled:", roll)
-

Change it and test it

- -

Turn the six-sided die into a twenty-sided die by changing only the two arguments inside randint().

- -

Quick check: What values are possible from random.randint(4, 8)?

-
Reveal answer

4, 5, 6, 7, and 8. Both endpoints are included.

- -

Each integer in the range has the same chance of being selected. Repeated calls can return the same result; a few runs do not have to contain every possible value.

+

Change it: Make this a twenty-sided die.

+

Quick check: List the possible results of random.randint(4, 8).

+
Reveal answer

4, 5, 6, 7, 8.

+

Each number has an equal chance. Random results can repeat. Six rolls do not guarantee six different numbers.

Part 2: Random Choices

- -

random.choice() selects one item from a sequence, such as a list.

- -

Follow the data

- -

["forest", "desert", "ocean"] → random.choice(locations) → one chosen item → print()

- - - - - - - - -
PiecePurpose
locations = [...]Stores all possible choices
random.choice(locations)Selects one list item
selectedRemembers the selected item
- -

Predict before running: Is Python returning the item's position or the actual item?

+

random.choice() picks one item from a list.

+

Predict: Will this code print a location or its position in the list?

import random
 
@@ -125,36 +78,31 @@ selected = random.choice(locations)
 
 print("Your mission location is:", selected)
-

Try this

- -

Add two new locations to the list and run the code several times. Every output should be one of the items in your list.

- -

randint() chooses a whole number from a range.
-choice() chooses an item from a sequence.

+
Reveal answer and trace +

It prints the location itself. For example:

+ + + + + + + +
StepExample value
Available items["forest", "desert", "ocean"]
Item stored in selected"ocean"
Printed messageYour mission location is: ocean
+

This is one possible run, not a fixed output.

+
+

Change it: Add two locations. Run again.

Part 3: Random Values in Decisions

- -

Randomness becomes more useful when a program reacts to the value it receives. We can combine a random number with an if statement.

- -

Program flow

- -
    -
  1. Generate a number.
  2. -
  3. Save it in computer_move.
  4. -
  5. Compare the number.
  6. -
  7. Print the matching action.
  8. -
- +

An if statement turns a random number into an action.

- +
Random valueProgram action
ValueAction
1Move left
2Move right
3Stay still
- -

Before running, trace the program as if computer_move were 2. Which message would print?

+

Trace it: If computer_move is 2, which branch runs?

import random
 
@@ -168,28 +116,13 @@ elif computer_move == 2:
 else:
     print("Computer stays still.")
-

Common mistake

- -

This line generates one random value:

- -
move = random.randint(1, 3)
- -

Reuse move in every comparison. Calling randint() again inside each condition creates new values, so the program may not behave as expected.

+
Reveal the branch

The elif branch prints Computer moves right.

+

Generate once, reuse the variable. Calling randint() again makes a new draw—it may not match the first one.

3. Classwork & Practice Tasks

-

Classwork 1

- -

Build a coin flip.

- -
    -
  1. Generate either 1 or 2.
  2. -
  3. Print Heads when the value is 1.
  4. -
  5. Print Tails when the value is 2.
  6. -
  7. Run the program at least three times.
  8. -
- -

Checkpoint: Show your code and explain why both outcomes are possible.

+

Coin flip: Fill the blanks so 1 prints Heads and 2 prints Tails. Then run it three times.

+

Explain: Why are both outcomes possible?

import random
 
@@ -202,16 +135,8 @@ else:
     print("Tails")

Classwork 2

- -

Create a random student picker.

- -
    -
  • Make a list containing at least five names.
  • -
  • Use random.choice() to select one name.
  • -
  • Print a complete sentence containing the selected name.
  • -
- -

Extension: Add a second list of questions and randomly select both a student and a question.

+

Student picker: Use choice() to pick from at least five names and print a sentence with the result.

+
Optional challenge

Add a list of questions. Pick both a student and a question.

import random
 
@@ -223,21 +148,17 @@ students = ["Alex", "Sam", "Jordan", "Taylor", "Casey"]
 

Classwork 3

- -

Create a weather simulator.

- -

Generate a random number from 1 through 4 and use a decision to print:

- -
    -
  • 1: Sunny
  • -
  • 2: Cloudy
  • -
  • 3: Rainy
  • -
  • 4: Windy
  • -
- -

Then add one extra message for each result. For example, a sunny result could print Remember sunglasses.

- -

Requirement: Generate the random number once, store it, and reuse that variable in the conditions.

+

Weather simulator: Use one random draw and an if / elif / else decision.

+ + + + + + + + +
NumberWeather
1Sunny
2Cloudy
3Rainy
4Windy
+

Print the weather and one matching suggestion, such as Bring an umbrella.

import random
 
@@ -247,62 +168,47 @@ weather_number = random.randint(1, 4)
 

Homework

-

Mini-project: Random Adventure Generator

- -

Create a short program that can produce different adventure setups when it runs. Random results can repeat.

- -

Your program must include:

- +

Choose your own theme. Your program must:

    -
  • import random
  • -
  • one list of at least four locations
  • -
  • one list of at least four items
  • -
  • random.choice() used on both lists
  • -
  • one random.randint()
  • -
  • an if statement that reacts to the random integer
  • -
  • a clear final output that combines the results
  • +
  • Import random.
  • +
  • Use choice() on two lists: at least four locations and four items.
  • +
  • Use randint() for a challenge level from 1 to 5.
  • +
  • Use an if statement to react to that level.
  • +
  • Print the location, item, level, and reaction.
- -

Example format: You travel to the forest with a map. Challenge level: 3.

- -

Do not copy the example exactly. Choose your own theme and outputs.

+

Possible output: You reach the ocean with a map. Level: 4. Find a guide!

+

Submit your code, three test outputs, and one sentence explaining what can change.

4. Grading Plan

- - + + - - - - - - + + + + +
CategoryPointsFull-credit requirement
Homework rubric — 10 points
RequirementPoints
Random tools3Correctly imports random and uses both randint() and choice()
Program logic3Stores results in variables and uses a correct decision
Required content2Includes the required lists, range, and output
Testing and explanation1Runs multiple tests and briefly explains what changes
Readability1Uses clear variable names, comments, and organized output
Total10
Correct import, randint(), and choice()3
Stored results and a working decision3
Required lists, range, and output2
Three test outputs and an explanation1
Clear names and readable code1

Exit Ticket

- -

Answer in 1–2 sentences each:

-
    -
  1. What is the difference between random.randint() and random.choice()?
  2. -
  3. Why should a random result usually be stored in a variable?
  4. -
  5. If random.randint(2, 5) is used, list every possible result.
  6. +
  7. randint() or choice(): which picks a name?
  8. +
  9. Why store a random result before testing it?
  10. +
  11. What can random.randint(2, 5) return?

5. Lesson Revisions & Feedback Evidence

- -

After teaching the lesson, record feedback here.

- +
+Record feedback after teaching - + - - - + + +
Feedback sourceWhat was confusing or helpful?Revision made
SourceFeedback / evidenceChange made
Student feedback
Peer feedback
Teacher observation
Student
Peer
Teacher
- -

Possible evidence includes completed quick checks, common coding errors, student explanations, and improvements between the first and final program.

+
From 1019db6c03a630bf4713929f669af4b189c88bb9 Mon Sep 17 00:00:00 2001 From: ruhaanb622 Date: Wed, 16 Sep 2026 21:11:12 -0700 Subject: [PATCH 33/43] Revamp Python Boolean and random lessons --- .../2026-09-15-boolean_scratchers_js.md | 215 ----------- ...2026-09-15-random_py_sprinters_IPYNB_2_.md | 349 ++++++++---------- .../2026-09-15-boolean_scratchers_py_hw.ipynb | 315 +++++++++++++++- .../2026-09-15-random_py_sprinters.ipynb | 266 ++++++------- 4 files changed, 593 insertions(+), 552 deletions(-) delete mode 100644 _notebooks/2026-09-15-boolean_scratchers_js.md diff --git a/_notebooks/2026-09-15-boolean_scratchers_js.md b/_notebooks/2026-09-15-boolean_scratchers_js.md deleted file mode 100644 index 5eaf463b6c..0000000000 --- a/_notebooks/2026-09-15-boolean_scratchers_js.md +++ /dev/null @@ -1,215 +0,0 @@ ---- -layout: post -categories: [JavaScript, Boolean-Expressions] -lesson_language: JavaScript -lesson_topic: Boolean-Expressions -lesson_part: interactive -lesson_type: lesson -codemirror: true -microblog: true -toc: false -comments: false -title: 3.5 Boolean Expressions (JS) -description: Learn Boolean expressions in JavaScript using the five-part LxD lesson format. -permalink: /javascript/boolean/js ---- - -# 3.5 Boolean Expressions in JavaScript - -A **Boolean expression** is a question that evaluates to only `true` or `false`. JavaScript is the main language for this lesson. Python and College Board pseudocode are only used to compare the same idea in different forms. - -## 1. LxD Cycle Process - -**Empathize:** Boolean expressions can look simple, but it is easy to mix up `&&` and `||`, forget a boundary such as `>=`, or write a condition that does not match the rule in normal English. - -**Define:** -- **POV:** CSP students need a clear way to turn real-world rules into Boolean expressions so their programs make the correct decisions. -- **Learning Goal:** Students will be able to evaluate, write, test, and explain Boolean expressions in JavaScript. - -**Ideate:** -- **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program? -- **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker. - -**Prototype & Test:** Use the classwork below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule. - ---- - -## 2. Lesson Plan - -**Learning Objective:** By the end of this lesson, you will be able to use comparisons, `&&`, `||`, and `!` to create Boolean expressions and use them in JavaScript decisions. - -**Success Criteria:** You can predict whether an expression is `true` or `false`, write a condition from a rule in normal English, and test the condition with more than one set of values. - -### Part 1: Comparisons Create Booleans - -JavaScript comparison operators return `true` or `false`. - -| JavaScript | Meaning | Example | -| --- | --- | --- | -| `===` | equal to | `score === 90` | -| `!==` | not equal to | `score !== 0` | -| `>` | greater than | `score > 70` | -| `<` | less than | `age < 18` | -| `>=` | greater than or equal to | `score >= 70` | -| `<=` | less than or equal to | `age <= 18` | - -```javascript -let score = 82; - -console.log(score >= 70); -console.log(score === 100); -console.log(score !== 0); -``` - -Remember: -- `score = 90` assigns a value. -- `score === 90` compares both value and type. - -### Part 2: `&&`, `||`, and `!` - -Sometimes one comparison is not enough. - -| Idea | JavaScript | Python | College Board pseudocode | -| --- | --- | --- | --- | -| both must be true | `&&` | `and` | `AND` | -| at least one is true | `||` | `or` | `OR` | -| reverse true/false | `!` | `not` | `NOT` | - -```javascript -let hasId = true; -let hasTicket = false; - -console.log(hasId && hasTicket); -console.log(hasId || hasTicket); -console.log(!hasTicket); -``` - -A longer expression can be read one part at a time: - -```javascript -let age = 16; -let isTeenager = age >= 13 && age <= 19; -console.log(isTeenager); -``` - -### Part 3: Booleans Control `if` Statements - -An `if` statement runs when its condition is true. - -```javascript -let temperature = 72; - -if (temperature >= 70) { - console.log("It is warm outside."); -} else { - console.log("It is not warm outside."); -} -``` - -The same basic decision in College Board pseudocode is: - -```text -IF(temperature ≥ 70) -{ - DISPLAY("It is warm outside.") -} -ELSE -{ - DISPLAY("It is not warm outside.") -} -``` - ---- - -## 3. Classwork & Practice Tasks - -### Classwork 1: Predict Before You Run - -Predict each result first. Then run the code and compare. - -```javascript -console.log(8 > 5); -console.log(4 === 7); -console.log("cat" !== "dog"); -console.log(10 <= 10); -``` - -For each line, write `true` or `false` and one short reason. - -### Classwork 2: Fix the Logic - -A level should unlock only when the player has **at least 10 coins AND has found the key**. - -```javascript -let coins = 12; -let hasKey = false; - -// Fix the condition so both requirements are needed. -let canUnlock = coins >= 10 || hasKey; - -if (canUnlock) { - console.log("Level unlocked"); -} else { - console.log("Keep looking"); -} -``` - -Do these four things: -1. Predict what the current code prints. -2. Fix the Boolean expression. -3. Test at least three combinations of `coins` and `hasKey`. -4. Explain why the rule needs `&&` or `||`. - -### Classwork 3: Translate the Logic - -Start with this JavaScript expression: - -```javascript -hasTicket || onGuestList -``` - -Write the same Boolean expression in Python and College Board pseudocode. Then explain what word in **"ticket or guest list"** tells you which operator to use. - -### Homework: Boolean Decision Checker - -A student can use a study room when: -- they are logged in, -- they reserved the room **or** a teacher gave permission, -- and the room is **not** closed. - -```javascript -let loggedIn = true; -let reservedRoom = false; -let teacherPermission = true; -let roomClosed = false; - -// Replace false with one Boolean expression. -let canUseRoom = false; - -if (canUseRoom) { - console.log("Study room access approved"); -} else { - console.log("Study room access denied"); -} -``` - -Test at least four cases, including one where the room is closed and one where the student is not logged in. Then explain your Boolean expression in 2–3 sentences. - ---- - -## 4. Grading Plan - -Point values can be decided separately. For now, the work to check is: -- classwork predictions include an explanation, -- the incorrect Boolean condition is fixed and tested, -- the homework uses the required conditions, -- the student can explain the final expression in normal English. - ---- - -## 5. Lesson Revisions & Feedback Evidence - -- The lesson is organized into the same numbered `1` through `5` structure used by the Python lesson. -- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack. -- JavaScript stays the main coding language, while Python and College Board pseudocode are short comparison aids. -- Feedback from a practice run can be added here with the specific change that was made because of it. diff --git a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md index edee960bdc..b293518a10 100644 --- a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md +++ b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md @@ -9,206 +9,171 @@ codemirror: true microblog: true toc: false comments: false -title: 3.15 Python Random Generator (PY) -description: Learn how Python creates random integers, choices, and decisions through interactive examples. +title: 3.15 Random Values (PY) +description: Learn random values in Python using the five-part LxD lesson format. permalink: /csp/big-idea-3/RandomPY/p3/Lesson authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar --- -

3.15 Python Random Generator

-

Warm-up: What would happen if a game’s computer opponent always made the same move?

-

Predict → run → change. Follow the examples here; run them in your notebook or Python editor.

- -

1. LxD Cycle Process

-
-Teaching plan -

Empathize

-

Make randomness visible through short, familiar examples.

-

Define

-

Choose a number, pick an item, and use the result in a decision.

-

Ideate

-

Use a die, a location picker, and a computer opponent.

-

Prototype & Test

-

Students predict an output, run the code, then change one part.

-
- -

2. Lesson Plan

-

Learning Objective

-

Use Python’s random module to make unpredictable choices.

-

Success Criteria

-
    -
  • Choose valid bounds for randint().
  • -
  • Select a list item with choice().
  • -
  • Store a result and use it in an if statement.
  • -
- -

Part 1: Random Integers

-

import random gives Python access to its built-in random tools.

- - - - - - - - -
Read the code from top to bottom
CodeJob
import randomLoad the tools
roll = random.randint(1, 6)Pick and store a whole number
print(roll)Display it
-

Both endpoints count. Possible results: 1, 2, 3, 4, 5, 6.

-

Predict: Can it return 0? What about 6?

- -
import random
-
-# Both 1 and 6 are possible
-roll = random.randint(1, 6)
-print("You rolled:", roll)
- -

Change it: Make this a twenty-sided die.

-

Quick check: List the possible results of random.randint(4, 8).

-
Reveal answer

4, 5, 6, 7, 8.

-

Each number has an equal chance. Random results can repeat. Six rolls do not guarantee six different numbers.

- -

Part 2: Random Choices

-

random.choice() picks one item from a list.

-

Predict: Will this code print a location or its position in the list?

- -
import random
-
-locations = ["forest", "desert", "ocean"]
-selected = random.choice(locations)
-
-print("Your mission location is:", selected)
- -
Reveal answer and trace -

It prints the location itself. For example:

- - - - - - - -
StepExample value
Available items["forest", "desert", "ocean"]
Item stored in selected"ocean"
Printed messageYour mission location is: ocean
-

This is one possible run, not a fixed output.

-
-

Change it: Add two locations. Run again.

- -

Part 3: Random Values in Decisions

-

An if statement turns a random number into an action.

- - - - - - - -
ValueAction
1Move left
2Move right
3Stay still
-

Trace it: If computer_move is 2, which branch runs?

- -
import random
-
-computer_move = random.randint(1, 3)
-print("Computer rolled:", computer_move)
-
-if computer_move == 1:
-    print("Computer moves left.")
-elif computer_move == 2:
-    print("Computer moves right.")
-else:
-    print("Computer stays still.")
+# 3.15 Random Values in Python + +A **random value** is selected from a set or range of possible values. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms. + +## 1. LxD Cycle Process + +**Empathize:** Random code can be confusing because students may expect every result to appear once before a repeat, forget that `randint` includes both endpoints, or choose a range with the wrong values. + +**Define:** +- **POV:** CSP students need a simple way to connect familiar random events, such as dice rolls, to the code that creates random values. +- **Learning Goal:** Students will be able to generate, test, and explain random values in Python. + +**Ideate:** +- **HMW Question:** How might we show randomness in a way that students can predict the possible outputs even though they cannot predict the exact next result? +- **Activity:** Predict ranges, use `random.choice`, fix a wrong range, and build a small dice game. + +**Prototype & Test:** Use the classwork below to check whether students can list possible outputs, recognize valid ranges, and use a random result inside a decision. + +--- + +## 2. Lesson Plan + +**Learning Objective:** By the end of this lesson, you will be able to use Python's `random` module to generate random integers, choose random list items, and use random results in a program. + +**Success Criteria:** You can identify every possible output of a random expression, choose the correct range, and explain why repeated results are allowed. + +### Part 1: Random Integers + +Python's built-in `random` module gives us tools for random values. -
Reveal the branch

The elif branch prints Computer moves right.

-

Generate once, reuse the variable. Calling randint() again makes a new draw—it may not match the first one.

+```python +import random -

3. Classwork & Practice Tasks

-

Classwork 1

-

Coin flip: Fill the blanks so 1 prints Heads and 2 prints Tails. Then run it three times.

-

Explain: Why are both outcomes possible?

+die_roll = random.randint(1, 6) +print("Die roll:", die_roll) +``` -
import random
+`random.randint(a, b)` can return any whole number from `a` through `b`, including both endpoints.
 
-# Replace the blanks to finish the coin flip
-flip = random.randint(__, __)
+For a normal die, the possible results are `1`, `2`, `3`, `4`, `5`, and `6`.
 
-if flip == __:
+### Part 2: Random Choices
+
+Python can choose directly from a list.
+
+```python
+import random
+
+activities = ["study", "stretch", "walk", "get water"]
+pick = random.choice(activities)
+
+print("Random activity:", pick)
+```
+
+The result must be one item from the list.
+
+The same random-integer idea looks like this in the three forms:
+
+| Form | Random integer from 1 through 6 |
+| --- | --- |
+| Python | `random.randint(1, 6)` |
+| JavaScript | `Math.floor(Math.random() * 6) + 1` |
+| College Board pseudocode | `RANDOM(1, 6)` |
+
+### Part 3: Use Random Values in Decisions
+
+A program can generate a random value and then use that result in an `if` statement.
+
+```python
+import random
+
+flip = random.randint(1, 2)
+
+if flip == 1:
     print("Heads")
 else:
-    print("Tails")
- -

Classwork 2

-

Student picker: Use choice() to pick from at least five names and print a sentence with the result.

-
Optional challenge

Add a list of questions. Pick both a student and a question.

- -
import random
-
-students = ["Alex", "Sam", "Jordan", "Taylor", "Casey"]
-
-# Write two lines below:
-# 1. Select a random student
-# 2. Print the result
-
- -

Classwork 3

-

Weather simulator: Use one random draw and an if / elif / else decision.

- - - - - - - - -
NumberWeather
1Sunny
2Cloudy
3Rainy
4Windy
-

Print the weather and one matching suggestion, such as Bring an umbrella.

- -
import random
-
-weather_number = random.randint(1, 4)
-
-# Add an if / elif / else decision below
-
- -

Homework

-

Mini-project: Random Adventure Generator

-

Choose your own theme. Your program must:

-
    -
  • Import random.
  • -
  • Use choice() on two lists: at least four locations and four items.
  • -
  • Use randint() for a challenge level from 1 to 5.
  • -
  • Use an if statement to react to that level.
  • -
  • Print the location, item, level, and reaction.
  • -
-

Possible output: You reach the ocean with a map. Level: 4. Find a guide!

-

Submit your code, three test outputs, and one sentence explaining what can change.

- -

4. Grading Plan

- - - - - - - - - - -
Homework rubric — 10 points
RequirementPoints
Correct import, randint(), and choice()3
Stored results and a working decision3
Required lists, range, and output2
Three test outputs and an explanation1
Clear names and readable code1
- -

Exit Ticket

-
    -
  1. randint() or choice(): which picks a name?
  2. -
  3. Why store a random result before testing it?
  4. -
  5. What can random.randint(2, 5) return?
  6. -
- -

5. Lesson Revisions & Feedback Evidence

-
-Record feedback after teaching - - - - - - - -
SourceFeedback / evidenceChange made
Student
Peer
Teacher
-
+ print("Tails") +``` + +Random does **not** mean every possible result appears once before a repeat. Repeats are normal. + +--- + +## 3. Classwork & Practice Tasks + +### Classwork 1: Predict the Range + +Before running this expression: + +```python +random.randint(3, 7) +``` + +answer: +1. What is the smallest possible result? +2. What is the largest possible result? +3. List every possible integer. +4. Could it return `2`? +5. Could it return `7`? + +Then test it several times. + +### Classwork 2: Random Choice + +```python +import random + +snacks = ["chips", "fruit", "cookies", "popcorn"] +snack = random.choice(snacks) + +print("Selected snack:", snack) +``` + +Do these five things: +1. List every value that can be printed. +2. Add one new snack. +3. Run the code at least five times. +4. Explain why the same snack can appear more than once. +5. Replace the list with your own category. + +### Classwork 3: Fix the Range + +This is supposed to simulate a six-sided die, but the range is wrong. + +```python +import random + +die = random.randint(0, 5) +print(die) +``` + +List the current possible results, fix the range so it returns `1` through `6`, and write the corrected random expression in JavaScript and College Board pseudocode. + +### Homework: Random Game Challenge + +Build a small Python program using randomness. You can make a dice game, random prize, activity picker, opponent move, or another simple idea. + +Your program must: +1. use `random.randint(...)` or `random.choice(...)`, +2. have at least three possible random results, +3. use the random result in an `if` / `elif` / `else` or another meaningful action, +4. still work when a value repeats, +5. include 2–3 sentences explaining the possible outputs. + +--- + +## 4. Grading Plan + +Point values can be decided separately. For now, the work to check is: +- classwork correctly identifies possible outputs, +- the incorrect random range is fixed, +- the homework uses randomness in a meaningful way, +- the student can explain why repeats are valid. + +--- + +## 5. Lesson Revisions & Feedback Evidence + +- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson. +- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack. +- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids. +- Feedback from a practice run can be added here with the specific change that was made because of it. diff --git a/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb b/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb index 0f7e21c4f4..5a4d00c8e4 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb @@ -3,7 +3,11 @@ { "cell_type": "raw", "id": "frontmatter", - "metadata": {"vscode": {"languageId": "raw"}}, + "metadata": { + "vscode": { + "languageId": "raw" + } + }, "source": [ "---\n", "layout: post\n", @@ -17,60 +21,333 @@ "toc: false\n", "comments: false\n", "title: 3.5 Boolean Expressions (PY)\n", - "description: Boolean expressions lesson starter.\n", + "description: Learn Boolean expressions in Python using the five-part LxD lesson format.\n", "permalink: /python/boolean/py\n", - "authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n", "---" ] }, { "cell_type": "markdown", - "id": "lesson-structure", + "id": "md1", "metadata": {}, "source": [ "# 3.5 Boolean Expressions in Python\n", "\n", + "A **Boolean expression** is a question that evaluates to only `True` or `False`. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n", + "\n", "## 1. LxD Cycle Process\n", "\n", - "### Empathize\n", + "**Empathize:** Boolean expressions can look simple, but it is easy to mix up `and` and `or`, forget a boundary such as `>=`, or write a condition that does not match the rule in normal English.\n", + "\n", + "**Define:**\n", + "- **POV:** CSP students need a clear way to turn real-world rules into Boolean expressions so their programs make the correct decisions.\n", + "- **Learning Goal:** Students will be able to evaluate, write, test, and explain Boolean expressions in Python.\n", "\n", - "### Define\n", + "**Ideate:**\n", + "- **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program?\n", + "- **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker.\n", "\n", - "### Ideate\n", + "**Prototype & Test:** Use the classwork below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule.\n", "\n", - "### Prototype & Test\n", + "---\n", "\n", "## 2. Lesson Plan\n", "\n", - "### Learning Objective\n", + "**Learning Objective:** By the end of this lesson, you will be able to use comparisons, `and`, `or`, and `not` to create Boolean expressions and use them in Python decisions.\n", + "\n", + "**Success Criteria:** You can predict whether an expression is `True` or `False`, write a condition from a rule in normal English, and test the condition with more than one set of values.\n", "\n", - "### Success Criteria\n", + "### Part 1: Comparisons Create Booleans\n", + "\n", + "Python comparison operators return `True` or `False`.\n", + "\n", + "| Python | Meaning | Example |\n", + "| --- | --- | --- |\n", + "| `==` | equal to | `score == 90` |\n", + "| `!=` | not equal to | `score != 0` |\n", + "| `>` | greater than | `score > 70` |\n", + "| `<` | less than | `age < 18` |\n", + "| `>=` | greater than or equal to | `score >= 70` |\n", + "| `<=` | less than or equal to | `age <= 18` |" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "code2", + "metadata": {}, + "outputs": [], + "source": [ + "score = 82\n", "\n", - "### Part 1: Comparisons\n", + "print(score >= 70)\n", + "print(score == 100)\n", + "print(score != 0)" + ] + }, + { + "cell_type": "markdown", + "id": "md3", + "metadata": {}, + "source": [ + "Remember:\n", + "- `score = 90` assigns a value.\n", + "- `score == 90` compares two values.\n", "\n", "### Part 2: `and`, `or`, and `not`\n", "\n", - "### Part 3: Boolean `if` Statements\n", + "Sometimes one comparison is not enough.\n", + "\n", + "| Idea | Python | JavaScript | College Board pseudocode |\n", + "| --- | --- | --- | --- |\n", + "| both must be true | `and` | `&&` | `AND` |\n", + "| at least one is true | `or` | `||` | `OR` |\n", + "| reverse true/false | `not` | `!` | `NOT` |" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "code4", + "metadata": {}, + "outputs": [], + "source": [ + "has_id = True\n", + "has_ticket = False\n", + "\n", + "print(has_id and has_ticket)\n", + "print(has_id or has_ticket)\n", + "print(not has_ticket)" + ] + }, + { + "cell_type": "markdown", + "id": "md5", + "metadata": {}, + "source": [ + "A longer expression can be read one part at a time:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "code6", + "metadata": {}, + "outputs": [], + "source": [ + "age = 16\n", + "is_teenager = age >= 13 and age <= 19\n", + "print(is_teenager)" + ] + }, + { + "cell_type": "markdown", + "id": "md7", + "metadata": {}, + "source": [ + "### Part 3: Booleans Control `if` Statements\n", + "\n", + "An `if` statement runs when its condition is true." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "code8", + "metadata": {}, + "outputs": [], + "source": [ + "temperature = 72\n", + "\n", + "if temperature >= 70:\n", + " print(\"It is warm outside.\")\n", + "else:\n", + " print(\"It is not warm outside.\")" + ] + }, + { + "cell_type": "markdown", + "id": "md9", + "metadata": {}, + "source": [ + "The same basic decision in College Board pseudocode is:" + ] + }, + { + "cell_type": "markdown", + "id": "md10", + "metadata": {}, + "source": [ + "```text\n", + "IF(temperature ≥ 70)\n", + "{\n", + " DISPLAY(\"It is warm outside.\")\n", + "}\n", + "ELSE\n", + "{\n", + " DISPLAY(\"It is not warm outside.\")\n", + "}\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "md11", + "metadata": {}, + "source": [ + "---\n", "\n", "## 3. Classwork & Practice Tasks\n", "\n", - "### Classwork 1\n", + "### Classwork 1: Predict Before You Run\n", + "\n", + "Predict each result first. Then run the code and compare." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "code12", + "metadata": {}, + "outputs": [], + "source": [ + "print(8 > 5)\n", + "print(4 == 7)\n", + "print(\"cat\" != \"dog\")\n", + "print(10 <= 10)" + ] + }, + { + "cell_type": "markdown", + "id": "md13", + "metadata": {}, + "source": [ + "For each line, write `True` or `False` and one short reason.\n", + "\n", + "### Classwork 2: Fix the Logic\n", "\n", - "### Classwork 2\n", + "A level should unlock only when the player has **at least 10 coins AND has found the key**." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "code14", + "metadata": {}, + "outputs": [], + "source": [ + "coins = 12\n", + "has_key = False\n", + "\n", + "# Fix the condition so both requirements are needed.\n", + "can_unlock = coins >= 10 or has_key\n", "\n", - "### Classwork 3\n", + "if can_unlock:\n", + " print(\"Level unlocked\")\n", + "else:\n", + " print(\"Keep looking\")" + ] + }, + { + "cell_type": "markdown", + "id": "md15", + "metadata": {}, + "source": [ + "Do these four things:\n", + "1. Predict what the current code prints.\n", + "2. Fix the Boolean expression.\n", + "3. Test at least three combinations of `coins` and `has_key`.\n", + "4. Explain why the rule needs `and` or `or`.\n", "\n", - "### Homework\n", + "### Classwork 3: Translate the Logic\n", + "\n", + "Start with this Python expression:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "code16", + "metadata": {}, + "outputs": [], + "source": [ + "has_ticket or on_guest_list" + ] + }, + { + "cell_type": "markdown", + "id": "md17", + "metadata": {}, + "source": [ + "Write the same Boolean expression in JavaScript and College Board pseudocode. Then explain what word in **\"ticket or guest list\"** tells you which operator to use.\n", + "\n", + "### Homework: Boolean Decision Checker\n", + "\n", + "A student can use a study room when:\n", + "- they are logged in,\n", + "- they reserved the room **or** a teacher gave permission,\n", + "- and the room is **not** closed." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "code18", + "metadata": {}, + "outputs": [], + "source": [ + "logged_in = True\n", + "reserved_room = False\n", + "teacher_permission = True\n", + "room_closed = False\n", + "\n", + "# Replace False with one Boolean expression.\n", + "can_use_room = False\n", + "\n", + "if can_use_room:\n", + " print(\"Study room access approved\")\n", + "else:\n", + " print(\"Study room access denied\")" + ] + }, + { + "cell_type": "markdown", + "id": "md19", + "metadata": {}, + "source": [ + "Test at least four cases, including one where the room is closed and one where the student is not logged in. Then explain your Boolean expression in 2–3 sentences.\n", + "\n", + "---\n", "\n", "## 4. Grading Plan\n", "\n", - "## 5. Lesson Revisions & Feedback Evidence" + "Point values can be decided separately. For now, the work to check is:\n", + "- classwork predictions include an explanation,\n", + "- the incorrect Boolean condition is fixed and tested,\n", + "- the homework uses the required conditions,\n", + "- the student can explain the final expression in normal English.\n", + "\n", + "---\n", + "\n", + "## 5. Lesson Revisions & Feedback Evidence\n", + "\n", + "- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n", + "- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack.\n", + "- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n", + "- Feedback from a practice run can be added here with the specific change that was made because of it." ] } ], "metadata": { - "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, - "language_info": {"name": "python", "version": "3"} + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3" + } }, "nbformat": 4, "nbformat_minor": 5 diff --git a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb index 5ea78500a0..e83c1abbc2 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb @@ -20,8 +20,8 @@ "microblog: true\n", "toc: false\n", "comments: false\n", - "title: 3.15 Python Random Generator (PY)\n", - "description: Learn how Python creates random integers, choices, and decisions through interactive examples.\n", + "title: 3.15 Random Values (PY)\n", + "description: Learn random values in Python using the five-part LxD lesson format.\n", "permalink: /csp/big-idea-3/RandomPY/p3/Lesson\n", "authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n", "---" @@ -29,229 +29,243 @@ }, { "cell_type": "markdown", - "id": "title-intro", + "id": "md1", "metadata": {}, "source": [ - "

3.15 Python Random Generator

\n

Warm-up: What would happen if a game’s computer opponent always made the same move?

\n

Predict → run → change. Follow the examples here; run them in your notebook or Python editor.

" - ] - }, - { - "cell_type": "markdown", - "id": "lxd", - "metadata": {}, - "source": [ - "

1. LxD Cycle Process

\n
\nTeaching plan\n

Empathize

\n

Make randomness visible through short, familiar examples.

\n

Define

\n

Choose a number, pick an item, and use the result in a decision.

\n

Ideate

\n

Use a die, a location picker, and a computer opponent.

\n

Prototype & Test

\n

Students predict an output, run the code, then change one part.

\n
" - ] - }, - { - "cell_type": "markdown", - "id": "plan", - "metadata": {}, - "source": [ - "

2. Lesson Plan

\n

Learning Objective

\n

Use Python’s random module to make unpredictable choices.

\n

Success Criteria

\n
    \n
  • Choose valid bounds for randint().
  • \n
  • Select a list item with choice().
  • \n
  • Store a result and use it in an if statement.
  • \n
" - ] - }, - { - "cell_type": "markdown", - "id": "part1", - "metadata": {}, - "source": [ - "

Part 1: Random Integers

\n

import random gives Python access to its built-in random tools.

\n\n\n\n\n\n\n\n\n
Read the code from top to bottom
CodeJob
import randomLoad the tools
roll = random.randint(1, 6)Pick and store a whole number
print(roll)Display it
\n

Both endpoints count. Possible results: 1, 2, 3, 4, 5, 6.

\n

Predict: Can it return 0? What about 6?

" + "# 3.15 Random Values in Python\n", + "\n", + "A **random value** is selected from a set or range of possible values. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n", + "\n", + "## 1. LxD Cycle Process\n", + "\n", + "**Empathize:** Random code can be confusing because students may expect every result to appear once before a repeat, forget that `randint` includes both endpoints, or choose a range with the wrong values.\n", + "\n", + "**Define:**\n", + "- **POV:** CSP students need a simple way to connect familiar random events, such as dice rolls, to the code that creates random values.\n", + "- **Learning Goal:** Students will be able to generate, test, and explain random values in Python.\n", + "\n", + "**Ideate:**\n", + "- **HMW Question:** How might we show randomness in a way that students can predict the possible outputs even though they cannot predict the exact next result?\n", + "- **Activity:** Predict ranges, use `random.choice`, fix a wrong range, and build a small dice game.\n", + "\n", + "**Prototype & Test:** Use the classwork below to check whether students can list possible outputs, recognize valid ranges, and use a random result inside a decision.\n", + "\n", + "---\n", + "\n", + "## 2. Lesson Plan\n", + "\n", + "**Learning Objective:** By the end of this lesson, you will be able to use Python's `random` module to generate random integers, choose random list items, and use random results in a program.\n", + "\n", + "**Success Criteria:** You can identify every possible output of a random expression, choose the correct range, and explain why repeated results are allowed.\n", + "\n", + "### Part 1: Random Integers\n", + "\n", + "Python's built-in `random` module gives us tools for random values." ] }, { "cell_type": "code", "execution_count": null, - "id": "dice-demo", + "id": "code2", "metadata": {}, "outputs": [], "source": [ "import random\n", "\n", - "# Both 1 and 6 are possible\n", - "roll = random.randint(1, 6)\n", - "print(\"You rolled:\", roll)" + "die_roll = random.randint(1, 6)\n", + "print(\"Die roll:\", die_roll)" ] }, { "cell_type": "markdown", - "id": "part1-check", + "id": "md3", "metadata": {}, "source": [ - "

Change it: Make this a twenty-sided die.

\n

Quick check: List the possible results of random.randint(4, 8).

\n
Reveal answer

4, 5, 6, 7, 8.

\n

Each number has an equal chance. Random results can repeat. Six rolls do not guarantee six different numbers.

" - ] - }, - { - "cell_type": "markdown", - "id": "part2", - "metadata": {}, - "source": [ - "

Part 2: Random Choices

\n

random.choice() picks one item from a list.

\n

Predict: Will this code print a location or its position in the list?

" + "`random.randint(a, b)` can return any whole number from `a` through `b`, including both endpoints.\n", + "\n", + "For a normal die, the possible results are `1`, `2`, `3`, `4`, `5`, and `6`.\n", + "\n", + "### Part 2: Random Choices\n", + "\n", + "Python can choose directly from a list." ] }, { "cell_type": "code", "execution_count": null, - "id": "choice-demo", + "id": "code4", "metadata": {}, "outputs": [], "source": [ "import random\n", "\n", - "locations = [\"forest\", \"desert\", \"ocean\"]\n", - "selected = random.choice(locations)\n", + "activities = [\"study\", \"stretch\", \"walk\", \"get water\"]\n", + "pick = random.choice(activities)\n", "\n", - "print(\"Your mission location is:\", selected)" - ] - }, - { - "cell_type": "markdown", - "id": "part2-check", - "metadata": {}, - "source": [ - "
Reveal answer and trace\n

It prints the location itself. For example:

\n\n\n\n\n\n\n\n
StepExample value
Available items[\"forest\", \"desert\", \"ocean\"]
Item stored in selected\"ocean\"
Printed messageYour mission location is: ocean
\n

This is one possible run, not a fixed output.

\n
\n

Change it: Add two locations. Run again.

" + "print(\"Random activity:\", pick)" ] }, { "cell_type": "markdown", - "id": "part3", + "id": "md5", "metadata": {}, "source": [ - "

Part 3: Random Values in Decisions

\n

An if statement turns a random number into an action.

\n\n\n\n\n\n\n\n
ValueAction
1Move left
2Move right
3Stay still
\n

Trace it: If computer_move is 2, which branch runs?

" + "The result must be one item from the list.\n", + "\n", + "The same random-integer idea looks like this in the three forms:\n", + "\n", + "| Form | Random integer from 1 through 6 |\n", + "| --- | --- |\n", + "| Python | `random.randint(1, 6)` |\n", + "| JavaScript | `Math.floor(Math.random() * 6) + 1` |\n", + "| College Board pseudocode | `RANDOM(1, 6)` |\n", + "\n", + "### Part 3: Use Random Values in Decisions\n", + "\n", + "A program can generate a random value and then use that result in an `if` statement." ] }, { "cell_type": "code", "execution_count": null, - "id": "decision-demo", + "id": "code6", "metadata": {}, "outputs": [], "source": [ "import random\n", "\n", - "computer_move = random.randint(1, 3)\n", - "print(\"Computer rolled:\", computer_move)\n", + "flip = random.randint(1, 2)\n", "\n", - "if computer_move == 1:\n", - " print(\"Computer moves left.\")\n", - "elif computer_move == 2:\n", - " print(\"Computer moves right.\")\n", + "if flip == 1:\n", + " print(\"Heads\")\n", "else:\n", - " print(\"Computer stays still.\")" - ] - }, - { - "cell_type": "markdown", - "id": "debug-tip", - "metadata": {}, - "source": [ - "
Reveal the branch

The elif branch prints Computer moves right.

\n

Generate once, reuse the variable. Calling randint() again makes a new draw—it may not match the first one.

" + " print(\"Tails\")" ] }, { "cell_type": "markdown", - "id": "classwork", + "id": "md7", "metadata": {}, "source": [ - "

3. Classwork & Practice Tasks

\n

Classwork 1

\n

Coin flip: Fill the blanks so 1 prints Heads and 2 prints Tails. Then run it three times.

\n

Explain: Why are both outcomes possible?

" + "Random does **not** mean every possible result appears once before a repeat. Repeats are normal.\n", + "\n", + "---\n", + "\n", + "## 3. Classwork & Practice Tasks\n", + "\n", + "### Classwork 1: Predict the Range\n", + "\n", + "Before running this expression:" ] }, { "cell_type": "code", "execution_count": null, - "id": "classwork1", + "id": "code8", "metadata": {}, "outputs": [], "source": [ - "import random\n", - "\n", - "# Replace the blanks to finish the coin flip\n", - "flip = random.randint(__, __)\n", - "\n", - "if flip == __:\n", - " print(\"Heads\")\n", - "else:\n", - " print(\"Tails\")" + "random.randint(3, 7)" ] }, { "cell_type": "markdown", - "id": "classwork2", + "id": "md9", "metadata": {}, "source": [ - "

Classwork 2

\n

Student picker: Use choice() to pick from at least five names and print a sentence with the result.

\n
Optional challenge

Add a list of questions. Pick both a student and a question.

" + "answer:\n", + "1. What is the smallest possible result?\n", + "2. What is the largest possible result?\n", + "3. List every possible integer.\n", + "4. Could it return `2`?\n", + "5. Could it return `7`?\n", + "\n", + "Then test it several times.\n", + "\n", + "### Classwork 2: Random Choice" ] }, { "cell_type": "code", "execution_count": null, - "id": "classwork2-code", + "id": "code10", "metadata": {}, "outputs": [], "source": [ "import random\n", "\n", - "students = [\"Alex\", \"Sam\", \"Jordan\", \"Taylor\", \"Casey\"]\n", + "snacks = [\"chips\", \"fruit\", \"cookies\", \"popcorn\"]\n", + "snack = random.choice(snacks)\n", "\n", - "# Write two lines below:\n", - "# 1. Select a random student\n", - "# 2. Print the result\n", - "" + "print(\"Selected snack:\", snack)" ] }, { "cell_type": "markdown", - "id": "classwork3", + "id": "md11", "metadata": {}, "source": [ - "

Classwork 3

\n

Weather simulator: Use one random draw and an if / elif / else decision.

\n\n\n\n\n\n\n\n\n
NumberWeather
1Sunny
2Cloudy
3Rainy
4Windy
\n

Print the weather and one matching suggestion, such as Bring an umbrella.

" + "Do these five things:\n", + "1. List every value that can be printed.\n", + "2. Add one new snack.\n", + "3. Run the code at least five times.\n", + "4. Explain why the same snack can appear more than once.\n", + "5. Replace the list with your own category.\n", + "\n", + "### Classwork 3: Fix the Range\n", + "\n", + "This is supposed to simulate a six-sided die, but the range is wrong." ] }, { "cell_type": "code", "execution_count": null, - "id": "classwork3-code", + "id": "code12", "metadata": {}, "outputs": [], "source": [ "import random\n", "\n", - "weather_number = random.randint(1, 4)\n", - "\n", - "# Add an if / elif / else decision below\n", - "" + "die = random.randint(0, 5)\n", + "print(die)" ] }, { "cell_type": "markdown", - "id": "homework", + "id": "md13", "metadata": {}, "source": [ - "

Homework

\n

Mini-project: Random Adventure Generator

\n

Choose your own theme. Your program must:

\n
    \n
  • Import random.
  • \n
  • Use choice() on two lists: at least four locations and four items.
  • \n
  • Use randint() for a challenge level from 1 to 5.
  • \n
  • Use an if statement to react to that level.
  • \n
  • Print the location, item, level, and reaction.
  • \n
\n

Possible output: You reach the ocean with a map. Level: 4. Find a guide!

\n

Submit your code, three test outputs, and one sentence explaining what can change.

" - ] - }, - { - "cell_type": "markdown", - "id": "grading", - "metadata": {}, - "source": [ - "

4. Grading Plan

\n\n\n\n\n\n\n\n\n\n\n
Homework rubric — 10 points
RequirementPoints
Correct import, randint(), and choice()3
Stored results and a working decision3
Required lists, range, and output2
Three test outputs and an explanation1
Clear names and readable code1
" - ] - }, - { - "cell_type": "markdown", - "id": "exit-ticket", - "metadata": {}, - "source": [ - "

Exit Ticket

\n
    \n
  1. randint() or choice(): which picks a name?
  2. \n
  3. Why store a random result before testing it?
  4. \n
  5. What can random.randint(2, 5) return?
  6. \n
" - ] - }, - { - "cell_type": "markdown", - "id": "revisions", - "metadata": {}, - "source": [ - "

5. Lesson Revisions & Feedback Evidence

\n
\nRecord feedback after teaching\n\n\n\n\n\n\n\n
SourceFeedback / evidenceChange made
Student
Peer
Teacher
\n
" + "List the current possible results, fix the range so it returns `1` through `6`, and write the corrected random expression in JavaScript and College Board pseudocode.\n", + "\n", + "### Homework: Random Game Challenge\n", + "\n", + "Build a small Python program using randomness. You can make a dice game, random prize, activity picker, opponent move, or another simple idea.\n", + "\n", + "Your program must:\n", + "1. use `random.randint(...)` or `random.choice(...)`,\n", + "2. have at least three possible random results,\n", + "3. use the random result in an `if` / `elif` / `else` or another meaningful action,\n", + "4. still work when a value repeats,\n", + "5. include 2–3 sentences explaining the possible outputs.\n", + "\n", + "---\n", + "\n", + "## 4. Grading Plan\n", + "\n", + "Point values can be decided separately. For now, the work to check is:\n", + "- classwork correctly identifies possible outputs,\n", + "- the incorrect random range is fixed,\n", + "- the homework uses randomness in a meaningful way,\n", + "- the student can explain why repeats are valid.\n", + "\n", + "---\n", + "\n", + "## 5. Lesson Revisions & Feedback Evidence\n", + "\n", + "- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n", + "- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack.\n", + "- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n", + "- Feedback from a practice run can be added here with the specific change that was made because of it." ] } ], @@ -268,4 +282,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file From 70a4dec10296dfb46cb9c135bd6f0e608211d7ca Mon Sep 17 00:00:00 2001 From: ruhaanb622 Date: Wed, 16 Sep 2026 21:27:56 -0700 Subject: [PATCH 34/43] Add point values to Python lesson grading plans --- ...09-15-boolean_scratchers_py_hw_IPYNB_2_.md | 11 +- ...2026-09-15-random_py_sprinters_IPYNB_2_.md | 11 +- .../2026-09-15-boolean_scratchers_py_hw.ipynb | 355 +----------------- .../2026-09-15-random_py_sprinters.ipynb | 286 +------------- 4 files changed, 12 insertions(+), 651 deletions(-) diff --git a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md index 91c83deb6f..eebfb03b68 100644 --- a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md +++ b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md @@ -194,13 +194,12 @@ Test at least four cases, including one where the room is closed and one where t --- -## 4. Grading Plan +## 4. Grading Plan (1 Point Total) -Point values can be decided separately. For now, the work to check is: -- classwork predictions include an explanation, -- the incorrect Boolean condition is fixed and tested, -- the homework uses the required conditions, -- the student can explain the final expression in normal English. +- **0.2 points — Classwork 1:** Correctly predict each Boolean result and include a short explanation. +- **0.2 points — Classwork 2:** Fix the Boolean logic and test at least three combinations. +- **0.2 points — Classwork 3:** Correctly translate the Boolean expression into JavaScript and College Board pseudocode. +- **0.4 points — Homework:** Build the study-room Boolean expression using all required conditions, test at least four cases, and explain the final expression in 2–3 sentences. --- diff --git a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md index b293518a10..9b3abf7a36 100644 --- a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md +++ b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md @@ -161,13 +161,12 @@ Your program must: --- -## 4. Grading Plan +## 4. Grading Plan (1 Point Total) -Point values can be decided separately. For now, the work to check is: -- classwork correctly identifies possible outputs, -- the incorrect random range is fixed, -- the homework uses randomness in a meaningful way, -- the student can explain why repeats are valid. +- **0.2 points — Classwork 1:** Correctly identify the smallest, largest, and all possible values in the random range. +- **0.2 points — Classwork 2:** Use `random.choice()` correctly, modify the list, and explain why repeats are possible. +- **0.2 points — Classwork 3:** Fix the six-sided die range and correctly write the equivalent JavaScript and College Board pseudocode. +- **0.4 points — Homework:** Build a working random program with at least three possible outcomes, use the random result in a meaningful decision or action, handle repeats, and explain the possible outputs. --- diff --git a/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb b/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb index 5a4d00c8e4..96ab49145d 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb @@ -1,354 +1 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "frontmatter", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Python, Boolean-Expressions]\n", - "lesson_language: Python\n", - "lesson_topic: Boolean-Expressions\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "toc: false\n", - "comments: false\n", - "title: 3.5 Boolean Expressions (PY)\n", - "description: Learn Boolean expressions in Python using the five-part LxD lesson format.\n", - "permalink: /python/boolean/py\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "md1", - "metadata": {}, - "source": [ - "# 3.5 Boolean Expressions in Python\n", - "\n", - "A **Boolean expression** is a question that evaluates to only `True` or `False`. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n", - "\n", - "## 1. LxD Cycle Process\n", - "\n", - "**Empathize:** Boolean expressions can look simple, but it is easy to mix up `and` and `or`, forget a boundary such as `>=`, or write a condition that does not match the rule in normal English.\n", - "\n", - "**Define:**\n", - "- **POV:** CSP students need a clear way to turn real-world rules into Boolean expressions so their programs make the correct decisions.\n", - "- **Learning Goal:** Students will be able to evaluate, write, test, and explain Boolean expressions in Python.\n", - "\n", - "**Ideate:**\n", - "- **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program?\n", - "- **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker.\n", - "\n", - "**Prototype & Test:** Use the classwork below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule.\n", - "\n", - "---\n", - "\n", - "## 2. Lesson Plan\n", - "\n", - "**Learning Objective:** By the end of this lesson, you will be able to use comparisons, `and`, `or`, and `not` to create Boolean expressions and use them in Python decisions.\n", - "\n", - "**Success Criteria:** You can predict whether an expression is `True` or `False`, write a condition from a rule in normal English, and test the condition with more than one set of values.\n", - "\n", - "### Part 1: Comparisons Create Booleans\n", - "\n", - "Python comparison operators return `True` or `False`.\n", - "\n", - "| Python | Meaning | Example |\n", - "| --- | --- | --- |\n", - "| `==` | equal to | `score == 90` |\n", - "| `!=` | not equal to | `score != 0` |\n", - "| `>` | greater than | `score > 70` |\n", - "| `<` | less than | `age < 18` |\n", - "| `>=` | greater than or equal to | `score >= 70` |\n", - "| `<=` | less than or equal to | `age <= 18` |" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code2", - "metadata": {}, - "outputs": [], - "source": [ - "score = 82\n", - "\n", - "print(score >= 70)\n", - "print(score == 100)\n", - "print(score != 0)" - ] - }, - { - "cell_type": "markdown", - "id": "md3", - "metadata": {}, - "source": [ - "Remember:\n", - "- `score = 90` assigns a value.\n", - "- `score == 90` compares two values.\n", - "\n", - "### Part 2: `and`, `or`, and `not`\n", - "\n", - "Sometimes one comparison is not enough.\n", - "\n", - "| Idea | Python | JavaScript | College Board pseudocode |\n", - "| --- | --- | --- | --- |\n", - "| both must be true | `and` | `&&` | `AND` |\n", - "| at least one is true | `or` | `||` | `OR` |\n", - "| reverse true/false | `not` | `!` | `NOT` |" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code4", - "metadata": {}, - "outputs": [], - "source": [ - "has_id = True\n", - "has_ticket = False\n", - "\n", - "print(has_id and has_ticket)\n", - "print(has_id or has_ticket)\n", - "print(not has_ticket)" - ] - }, - { - "cell_type": "markdown", - "id": "md5", - "metadata": {}, - "source": [ - "A longer expression can be read one part at a time:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code6", - "metadata": {}, - "outputs": [], - "source": [ - "age = 16\n", - "is_teenager = age >= 13 and age <= 19\n", - "print(is_teenager)" - ] - }, - { - "cell_type": "markdown", - "id": "md7", - "metadata": {}, - "source": [ - "### Part 3: Booleans Control `if` Statements\n", - "\n", - "An `if` statement runs when its condition is true." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code8", - "metadata": {}, - "outputs": [], - "source": [ - "temperature = 72\n", - "\n", - "if temperature >= 70:\n", - " print(\"It is warm outside.\")\n", - "else:\n", - " print(\"It is not warm outside.\")" - ] - }, - { - "cell_type": "markdown", - "id": "md9", - "metadata": {}, - "source": [ - "The same basic decision in College Board pseudocode is:" - ] - }, - { - "cell_type": "markdown", - "id": "md10", - "metadata": {}, - "source": [ - "```text\n", - "IF(temperature ≥ 70)\n", - "{\n", - " DISPLAY(\"It is warm outside.\")\n", - "}\n", - "ELSE\n", - "{\n", - " DISPLAY(\"It is not warm outside.\")\n", - "}\n", - "```" - ] - }, - { - "cell_type": "markdown", - "id": "md11", - "metadata": {}, - "source": [ - "---\n", - "\n", - "## 3. Classwork & Practice Tasks\n", - "\n", - "### Classwork 1: Predict Before You Run\n", - "\n", - "Predict each result first. Then run the code and compare." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code12", - "metadata": {}, - "outputs": [], - "source": [ - "print(8 > 5)\n", - "print(4 == 7)\n", - "print(\"cat\" != \"dog\")\n", - "print(10 <= 10)" - ] - }, - { - "cell_type": "markdown", - "id": "md13", - "metadata": {}, - "source": [ - "For each line, write `True` or `False` and one short reason.\n", - "\n", - "### Classwork 2: Fix the Logic\n", - "\n", - "A level should unlock only when the player has **at least 10 coins AND has found the key**." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code14", - "metadata": {}, - "outputs": [], - "source": [ - "coins = 12\n", - "has_key = False\n", - "\n", - "# Fix the condition so both requirements are needed.\n", - "can_unlock = coins >= 10 or has_key\n", - "\n", - "if can_unlock:\n", - " print(\"Level unlocked\")\n", - "else:\n", - " print(\"Keep looking\")" - ] - }, - { - "cell_type": "markdown", - "id": "md15", - "metadata": {}, - "source": [ - "Do these four things:\n", - "1. Predict what the current code prints.\n", - "2. Fix the Boolean expression.\n", - "3. Test at least three combinations of `coins` and `has_key`.\n", - "4. Explain why the rule needs `and` or `or`.\n", - "\n", - "### Classwork 3: Translate the Logic\n", - "\n", - "Start with this Python expression:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code16", - "metadata": {}, - "outputs": [], - "source": [ - "has_ticket or on_guest_list" - ] - }, - { - "cell_type": "markdown", - "id": "md17", - "metadata": {}, - "source": [ - "Write the same Boolean expression in JavaScript and College Board pseudocode. Then explain what word in **\"ticket or guest list\"** tells you which operator to use.\n", - "\n", - "### Homework: Boolean Decision Checker\n", - "\n", - "A student can use a study room when:\n", - "- they are logged in,\n", - "- they reserved the room **or** a teacher gave permission,\n", - "- and the room is **not** closed." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code18", - "metadata": {}, - "outputs": [], - "source": [ - "logged_in = True\n", - "reserved_room = False\n", - "teacher_permission = True\n", - "room_closed = False\n", - "\n", - "# Replace False with one Boolean expression.\n", - "can_use_room = False\n", - "\n", - "if can_use_room:\n", - " print(\"Study room access approved\")\n", - "else:\n", - " print(\"Study room access denied\")" - ] - }, - { - "cell_type": "markdown", - "id": "md19", - "metadata": {}, - "source": [ - "Test at least four cases, including one where the room is closed and one where the student is not logged in. Then explain your Boolean expression in 2–3 sentences.\n", - "\n", - "---\n", - "\n", - "## 4. Grading Plan\n", - "\n", - "Point values can be decided separately. For now, the work to check is:\n", - "- classwork predictions include an explanation,\n", - "- the incorrect Boolean condition is fixed and tested,\n", - "- the homework uses the required conditions,\n", - "- the student can explain the final expression in normal English.\n", - "\n", - "---\n", - "\n", - "## 5. Lesson Revisions & Feedback Evidence\n", - "\n", - "- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n", - "- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack.\n", - "- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n", - "- Feedback from a practice run can be added here with the specific change that was made because of it." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "name": "python", - "version": "3" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} \ No newline at end of file +{"cells":[{"cell_type":"raw","id":"frontmatter","metadata":{"vscode":{"languageId":"raw"}},"source":["---\n","layout: post\n","categories: [Python, Boolean-Expressions]\n","lesson_language: Python\n","lesson_topic: Boolean-Expressions\n","lesson_part: interactive\n","lesson_type: lesson\n","codemirror: true\n","microblog: true\n","toc: false\n","comments: false\n","title: 3.5 Boolean Expressions (PY)\n","description: Learn Boolean expressions in Python using the five-part LxD lesson format.\n","permalink: /python/boolean/py\n","---"]},{"cell_type":"markdown","id":"md1","metadata":{},"source":["# 3.5 Boolean Expressions in Python\n","\n","A **Boolean expression** is a question that evaluates to only `True` or `False`. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n","\n","## 1. LxD Cycle Process\n","\n","**Empathize:** Boolean expressions can look simple, but it is easy to mix up `and` and `or`, forget a boundary such as `>=`, or write a condition that does not match the rule in normal English.\n","\n","**Define:**\n","- **POV:** CSP students need a clear way to turn real-world rules into Boolean expressions so their programs make the correct decisions.\n","- **Learning Goal:** Students will be able to evaluate, write, test, and explain Boolean expressions in Python.\n","\n","**Ideate:**\n","- **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program?\n","- **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker.\n","\n","**Prototype & Test:** Use the classwork below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule.\n","\n","---\n","\n","## 2. Lesson Plan\n","\n","**Learning Objective:** By the end of this lesson, you will be able to use comparisons, `and`, `or`, and `not` to create Boolean expressions and use them in Python decisions.\n","\n","**Success Criteria:** You can predict whether an expression is `True` or `False`, write a condition from a rule in normal English, and test the condition with more than one set of values.\n","\n","### Part 1: Comparisons Create Booleans\n","\n","Python comparison operators return `True` or `False`.\n","\n","| Python | Meaning | Example |\n","| --- | --- | --- |\n","| `==` | equal to | `score == 90` |\n","| `!=` | not equal to | `score != 0` |\n","| `>` | greater than | `score > 70` |\n","| `<` | less than | `age < 18` |\n","| `>=` | greater than or equal to | `score >= 70` |\n","| `<=` | less than or equal to | `age <= 18` |"]},{"cell_type":"code","execution_count":null,"id":"code2","metadata":{},"outputs":[],"source":["score = 82\n","\n","print(score >= 70)\n","print(score == 100)\n","print(score != 0)"]},{"cell_type":"markdown","id":"md3","metadata":{},"source":["Remember:\n","- `score = 90` assigns a value.\n","- `score == 90` compares two values.\n","\n","### Part 2: `and`, `or`, and `not`\n","\n","Sometimes one comparison is not enough.\n","\n","| Idea | Python | JavaScript | College Board pseudocode |\n","| --- | --- | --- | --- |\n","| both must be true | `and` | `&&` | `AND` |\n","| at least one is true | `or` | `||` | `OR` |\n","| reverse true/false | `not` | `!` | `NOT` |"]},{"cell_type":"code","execution_count":null,"id":"code4","metadata":{},"outputs":[],"source":["has_id = True\n","has_ticket = False\n","\n","print(has_id and has_ticket)\n","print(has_id or has_ticket)\n","print(not has_ticket)"]},{"cell_type":"markdown","id":"md5","metadata":{},"source":["A longer expression can be read one part at a time:"]},{"cell_type":"code","execution_count":null,"id":"code6","metadata":{},"outputs":[],"source":["age = 16\n","is_teenager = age >= 13 and age <= 19\n","print(is_teenager)"]},{"cell_type":"markdown","id":"md7","metadata":{},"source":["### Part 3: Booleans Control `if` Statements\n","\n","An `if` statement runs when its condition is true."]},{"cell_type":"code","execution_count":null,"id":"code8","metadata":{},"outputs":[],"source":["temperature = 72\n","\n","if temperature >= 70:\n"," print(\"It is warm outside.\")\n","else:\n"," print(\"It is not warm outside.\")"]},{"cell_type":"markdown","id":"md9","metadata":{},"source":["The same basic decision in College Board pseudocode is:\n","\n","```text\n","IF(temperature ≥ 70)\n","{\n"," DISPLAY(\"It is warm outside.\")\n","}\n","ELSE\n","{\n"," DISPLAY(\"It is not warm outside.\")\n","}\n","```\n","\n","---\n","\n","## 3. Classwork & Practice Tasks\n","\n","### Classwork 1: Predict Before You Run\n","\n","Predict each result first. Then run the code and compare."]},{"cell_type":"code","execution_count":null,"id":"code10","metadata":{},"outputs":[],"source":["print(8 > 5)\n","print(4 == 7)\n","print(\"cat\" != \"dog\")\n","print(10 <= 10)"]},{"cell_type":"markdown","id":"md11","metadata":{},"source":["For each line, write `True` or `False` and one short reason.\n","\n","### Classwork 2: Fix the Logic\n","\n","A level should unlock only when the player has **at least 10 coins AND has found the key**."]},{"cell_type":"code","execution_count":null,"id":"code12","metadata":{},"outputs":[],"source":["coins = 12\n","has_key = False\n","\n","# Fix the condition so both requirements are needed.\n","can_unlock = coins >= 10 or has_key\n","\n","if can_unlock:\n"," print(\"Level unlocked\")\n","else:\n"," print(\"Keep looking\")"]},{"cell_type":"markdown","id":"md13","metadata":{},"source":["Do these four things:\n","1. Predict what the current code prints.\n","2. Fix the Boolean expression.\n","3. Test at least three combinations of `coins` and `has_key`.\n","4. Explain why the rule needs `and` or `or`.\n","\n","### Classwork 3: Translate the Logic\n","\n","Start with this Python expression:"]},{"cell_type":"code","execution_count":null,"id":"code14","metadata":{},"outputs":[],"source":["has_ticket or on_guest_list"]},{"cell_type":"markdown","id":"md15","metadata":{},"source":["Write the same Boolean expression in JavaScript and College Board pseudocode. Then explain what word in **\"ticket or guest list\"** tells you which operator to use.\n","\n","### Homework: Boolean Decision Checker\n","\n","A student can use a study room when:\n","- they are logged in,\n","- they reserved the room **or** a teacher gave permission,\n","- and the room is **not** closed."]},{"cell_type":"code","execution_count":null,"id":"code16","metadata":{},"outputs":[],"source":["logged_in = True\n","reserved_room = False\n","teacher_permission = True\n","room_closed = False\n","\n","# Replace False with one Boolean expression.\n","can_use_room = False\n","\n","if can_use_room:\n"," print(\"Study room access approved\")\n","else:\n"," print(\"Study room access denied\")"]},{"cell_type":"markdown","id":"md17","metadata":{},"source":["Test at least four cases, including one where the room is closed and one where the student is not logged in. Then explain your Boolean expression in 2–3 sentences.\n","\n","---\n","\n","## 4. Grading Plan (1 Point Total)\n","\n","- **0.2 points — Classwork 1:** Correctly predict each Boolean result and include a short explanation.\n","- **0.2 points — Classwork 2:** Fix the Boolean logic and test at least three combinations.\n","- **0.2 points — Classwork 3:** Correctly translate the Boolean expression into JavaScript and College Board pseudocode.\n","- **0.4 points — Homework:** Build the study-room Boolean expression using all required conditions, test at least four cases, and explain the final expression in 2–3 sentences.\n","\n","---\n","\n","## 5. Lesson Revisions & Feedback Evidence\n","\n","- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n","- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack.\n","- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n","- Feedback from a practice run can be added here with the specific change that was made because of it."]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3"}},"nbformat":4,"nbformat_minor":5} \ No newline at end of file diff --git a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb index e83c1abbc2..5cdd938533 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb @@ -1,285 +1 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "frontmatter", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Python, Random-Values]\n", - "lesson_language: Python\n", - "lesson_topic: Random-Values\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "toc: false\n", - "comments: false\n", - "title: 3.15 Random Values (PY)\n", - "description: Learn random values in Python using the five-part LxD lesson format.\n", - "permalink: /csp/big-idea-3/RandomPY/p3/Lesson\n", - "authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "md1", - "metadata": {}, - "source": [ - "# 3.15 Random Values in Python\n", - "\n", - "A **random value** is selected from a set or range of possible values. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n", - "\n", - "## 1. LxD Cycle Process\n", - "\n", - "**Empathize:** Random code can be confusing because students may expect every result to appear once before a repeat, forget that `randint` includes both endpoints, or choose a range with the wrong values.\n", - "\n", - "**Define:**\n", - "- **POV:** CSP students need a simple way to connect familiar random events, such as dice rolls, to the code that creates random values.\n", - "- **Learning Goal:** Students will be able to generate, test, and explain random values in Python.\n", - "\n", - "**Ideate:**\n", - "- **HMW Question:** How might we show randomness in a way that students can predict the possible outputs even though they cannot predict the exact next result?\n", - "- **Activity:** Predict ranges, use `random.choice`, fix a wrong range, and build a small dice game.\n", - "\n", - "**Prototype & Test:** Use the classwork below to check whether students can list possible outputs, recognize valid ranges, and use a random result inside a decision.\n", - "\n", - "---\n", - "\n", - "## 2. Lesson Plan\n", - "\n", - "**Learning Objective:** By the end of this lesson, you will be able to use Python's `random` module to generate random integers, choose random list items, and use random results in a program.\n", - "\n", - "**Success Criteria:** You can identify every possible output of a random expression, choose the correct range, and explain why repeated results are allowed.\n", - "\n", - "### Part 1: Random Integers\n", - "\n", - "Python's built-in `random` module gives us tools for random values." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code2", - "metadata": {}, - "outputs": [], - "source": [ - "import random\n", - "\n", - "die_roll = random.randint(1, 6)\n", - "print(\"Die roll:\", die_roll)" - ] - }, - { - "cell_type": "markdown", - "id": "md3", - "metadata": {}, - "source": [ - "`random.randint(a, b)` can return any whole number from `a` through `b`, including both endpoints.\n", - "\n", - "For a normal die, the possible results are `1`, `2`, `3`, `4`, `5`, and `6`.\n", - "\n", - "### Part 2: Random Choices\n", - "\n", - "Python can choose directly from a list." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code4", - "metadata": {}, - "outputs": [], - "source": [ - "import random\n", - "\n", - "activities = [\"study\", \"stretch\", \"walk\", \"get water\"]\n", - "pick = random.choice(activities)\n", - "\n", - "print(\"Random activity:\", pick)" - ] - }, - { - "cell_type": "markdown", - "id": "md5", - "metadata": {}, - "source": [ - "The result must be one item from the list.\n", - "\n", - "The same random-integer idea looks like this in the three forms:\n", - "\n", - "| Form | Random integer from 1 through 6 |\n", - "| --- | --- |\n", - "| Python | `random.randint(1, 6)` |\n", - "| JavaScript | `Math.floor(Math.random() * 6) + 1` |\n", - "| College Board pseudocode | `RANDOM(1, 6)` |\n", - "\n", - "### Part 3: Use Random Values in Decisions\n", - "\n", - "A program can generate a random value and then use that result in an `if` statement." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code6", - "metadata": {}, - "outputs": [], - "source": [ - "import random\n", - "\n", - "flip = random.randint(1, 2)\n", - "\n", - "if flip == 1:\n", - " print(\"Heads\")\n", - "else:\n", - " print(\"Tails\")" - ] - }, - { - "cell_type": "markdown", - "id": "md7", - "metadata": {}, - "source": [ - "Random does **not** mean every possible result appears once before a repeat. Repeats are normal.\n", - "\n", - "---\n", - "\n", - "## 3. Classwork & Practice Tasks\n", - "\n", - "### Classwork 1: Predict the Range\n", - "\n", - "Before running this expression:" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code8", - "metadata": {}, - "outputs": [], - "source": [ - "random.randint(3, 7)" - ] - }, - { - "cell_type": "markdown", - "id": "md9", - "metadata": {}, - "source": [ - "answer:\n", - "1. What is the smallest possible result?\n", - "2. What is the largest possible result?\n", - "3. List every possible integer.\n", - "4. Could it return `2`?\n", - "5. Could it return `7`?\n", - "\n", - "Then test it several times.\n", - "\n", - "### Classwork 2: Random Choice" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code10", - "metadata": {}, - "outputs": [], - "source": [ - "import random\n", - "\n", - "snacks = [\"chips\", \"fruit\", \"cookies\", \"popcorn\"]\n", - "snack = random.choice(snacks)\n", - "\n", - "print(\"Selected snack:\", snack)" - ] - }, - { - "cell_type": "markdown", - "id": "md11", - "metadata": {}, - "source": [ - "Do these five things:\n", - "1. List every value that can be printed.\n", - "2. Add one new snack.\n", - "3. Run the code at least five times.\n", - "4. Explain why the same snack can appear more than once.\n", - "5. Replace the list with your own category.\n", - "\n", - "### Classwork 3: Fix the Range\n", - "\n", - "This is supposed to simulate a six-sided die, but the range is wrong." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "code12", - "metadata": {}, - "outputs": [], - "source": [ - "import random\n", - "\n", - "die = random.randint(0, 5)\n", - "print(die)" - ] - }, - { - "cell_type": "markdown", - "id": "md13", - "metadata": {}, - "source": [ - "List the current possible results, fix the range so it returns `1` through `6`, and write the corrected random expression in JavaScript and College Board pseudocode.\n", - "\n", - "### Homework: Random Game Challenge\n", - "\n", - "Build a small Python program using randomness. You can make a dice game, random prize, activity picker, opponent move, or another simple idea.\n", - "\n", - "Your program must:\n", - "1. use `random.randint(...)` or `random.choice(...)`,\n", - "2. have at least three possible random results,\n", - "3. use the random result in an `if` / `elif` / `else` or another meaningful action,\n", - "4. still work when a value repeats,\n", - "5. include 2–3 sentences explaining the possible outputs.\n", - "\n", - "---\n", - "\n", - "## 4. Grading Plan\n", - "\n", - "Point values can be decided separately. For now, the work to check is:\n", - "- classwork correctly identifies possible outputs,\n", - "- the incorrect random range is fixed,\n", - "- the homework uses randomness in a meaningful way,\n", - "- the student can explain why repeats are valid.\n", - "\n", - "---\n", - "\n", - "## 5. Lesson Revisions & Feedback Evidence\n", - "\n", - "- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n", - "- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack.\n", - "- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n", - "- Feedback from a practice run can be added here with the specific change that was made because of it." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "name": "python", - "version": "3" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} \ No newline at end of file +{"cells":[{"cell_type":"raw","id":"frontmatter","metadata":{"vscode":{"languageId":"raw"}},"source":["---\n","layout: post\n","categories: [Python, Random-Values]\n","lesson_language: Python\n","lesson_topic: Random-Values\n","lesson_part: interactive\n","lesson_type: lesson\n","codemirror: true\n","microblog: true\n","toc: false\n","comments: false\n","title: 3.15 Random Values (PY)\n","description: Learn random values in Python using the five-part LxD lesson format.\n","permalink: /csp/big-idea-3/RandomPY/p3/Lesson\n","authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n","---"]},{"cell_type":"markdown","id":"md1","metadata":{},"source":["# 3.15 Random Values in Python\n","\n","A **random value** is selected from a set or range of possible values. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n","\n","## 1. LxD Cycle Process\n","\n","**Empathize:** Random code can be confusing because students may expect every result to appear once before a repeat, forget that `randint` includes both endpoints, or choose a range with the wrong values.\n","\n","**Define:**\n","- **POV:** CSP students need a simple way to connect familiar random events, such as dice rolls, to the code that creates random values.\n","- **Learning Goal:** Students will be able to generate, test, and explain random values in Python.\n","\n","**Ideate:**\n","- **HMW Question:** How might we show randomness in a way that students can predict the possible outputs even though they cannot predict the exact next result?\n","- **Activity:** Predict ranges, use `random.choice`, fix a wrong range, and build a small dice game.\n","\n","**Prototype & Test:** Use the classwork below to check whether students can list possible outputs, recognize valid ranges, and use a random result inside a decision.\n","\n","---\n","\n","## 2. Lesson Plan\n","\n","**Learning Objective:** By the end of this lesson, you will be able to use Python's `random` module to generate random integers, choose random list items, and use random results in a program.\n","\n","**Success Criteria:** You can identify every possible output of a random expression, choose the correct range, and explain why repeated results are allowed.\n","\n","### Part 1: Random Integers\n","\n","Python's built-in `random` module gives us tools for random values."]},{"cell_type":"code","execution_count":null,"id":"code2","metadata":{},"outputs":[],"source":["import random\n","\n","die_roll = random.randint(1, 6)\n","print(\"Die roll:\", die_roll)"]},{"cell_type":"markdown","id":"md3","metadata":{},"source":["`random.randint(a, b)` can return any whole number from `a` through `b`, including both endpoints.\n","\n","For a normal die, the possible results are `1`, `2`, `3`, `4`, `5`, and `6`.\n","\n","### Part 2: Random Choices\n","\n","Python can choose directly from a list."]},{"cell_type":"code","execution_count":null,"id":"code4","metadata":{},"outputs":[],"source":["import random\n","\n","activities = [\"study\", \"stretch\", \"walk\", \"get water\"]\n","pick = random.choice(activities)\n","\n","print(\"Random activity:\", pick)"]},{"cell_type":"markdown","id":"md5","metadata":{},"source":["The result must be one item from the list.\n","\n","The same random-integer idea looks like this in the three forms:\n","\n","| Form | Random integer from 1 through 6 |\n","| --- | --- |\n","| Python | `random.randint(1, 6)` |\n","| JavaScript | `Math.floor(Math.random() * 6) + 1` |\n","| College Board pseudocode | `RANDOM(1, 6)` |\n","\n","### Part 3: Use Random Values in Decisions\n","\n","A program can generate a random value and then use that result in an `if` statement."]},{"cell_type":"code","execution_count":null,"id":"code6","metadata":{},"outputs":[],"source":["import random\n","\n","flip = random.randint(1, 2)\n","\n","if flip == 1:\n"," print(\"Heads\")\n","else:\n"," print(\"Tails\")"]},{"cell_type":"markdown","id":"md7","metadata":{},"source":["Random does **not** mean every possible result appears once before a repeat. Repeats are normal.\n","\n","---\n","\n","## 3. Classwork & Practice Tasks\n","\n","### Classwork 1: Predict the Range\n","\n","Before running this expression:"]},{"cell_type":"code","execution_count":null,"id":"code8","metadata":{},"outputs":[],"source":["random.randint(3, 7)"]},{"cell_type":"markdown","id":"md9","metadata":{},"source":["answer:\n","1. What is the smallest possible result?\n","2. What is the largest possible result?\n","3. List every possible integer.\n","4. Could it return `2`?\n","5. Could it return `7`?\n","\n","Then test it several times.\n","\n","### Classwork 2: Random Choice"]},{"cell_type":"code","execution_count":null,"id":"code10","metadata":{},"outputs":[],"source":["import random\n","\n","snacks = [\"chips\", \"fruit\", \"cookies\", \"popcorn\"]\n","snack = random.choice(snacks)\n","\n","print(\"Selected snack:\", snack)"]},{"cell_type":"markdown","id":"md11","metadata":{},"source":["Do these five things:\n","1. List every value that can be printed.\n","2. Add one new snack.\n","3. Run the code at least five times.\n","4. Explain why the same snack can appear more than once.\n","5. Replace the list with your own category.\n","\n","### Classwork 3: Fix the Range\n","\n","This is supposed to simulate a six-sided die, but the range is wrong."]},{"cell_type":"code","execution_count":null,"id":"code12","metadata":{},"outputs":[],"source":["import random\n","\n","die = random.randint(0, 5)\n","print(die)"]},{"cell_type":"markdown","id":"md13","metadata":{},"source":["List the current possible results, fix the range so it returns `1` through `6`, and write the corrected random expression in JavaScript and College Board pseudocode.\n","\n","### Homework: Random Game Challenge\n","\n","Build a small Python program using randomness. You can make a dice game, random prize, activity picker, opponent move, or another simple idea.\n","\n","Your program must:\n","1. use `random.randint(...)` or `random.choice(...)`,\n","2. have at least three possible random results,\n","3. use the random result in an `if` / `elif` / `else` or another meaningful action,\n","4. still work when a value repeats,\n","5. include 2–3 sentences explaining the possible outputs.\n","\n","---\n","\n","## 4. Grading Plan (1 Point Total)\n","\n","- **0.2 points — Classwork 1:** Correctly identify the smallest, largest, and all possible values in the random range.\n","- **0.2 points — Classwork 2:** Use `random.choice()` correctly, modify the list, and explain why repeats are possible.\n","- **0.2 points — Classwork 3:** Fix the six-sided die range and correctly write the equivalent JavaScript and College Board pseudocode.\n","- **0.4 points — Homework:** Build a working random program with at least three possible outcomes, use the random result in a meaningful decision or action, handle repeats, and explain the possible outputs.\n","\n","---\n","\n","## 5. Lesson Revisions & Feedback Evidence\n","\n","- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n","- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack.\n","- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n","- Feedback from a practice run can be added here with the specific change that was made because of it."]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3"}},"nbformat":4,"nbformat_minor":5} \ No newline at end of file From 9e38e73efa0a1484d210d81e9798ed5ab948f003 Mon Sep 17 00:00:00 2001 From: ruhaanb622 Date: Wed, 16 Sep 2026 21:38:59 -0700 Subject: [PATCH 35/43] Rename lesson activities and format grading tables --- ...09-15-boolean_scratchers_py_hw_IPYNB_2_.md | 31 ++++++++++--------- ...2026-09-15-random_py_sprinters_IPYNB_2_.md | 31 ++++++++++--------- .../2026-09-15-boolean_scratchers_py_hw.ipynb | 2 +- .../2026-09-15-random_py_sprinters.ipynb | 2 +- 4 files changed, 36 insertions(+), 30 deletions(-) diff --git a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md index eebfb03b68..e29154ad7e 100644 --- a/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md +++ b/_notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md @@ -30,7 +30,7 @@ A **Boolean expression** is a question that evaluates to only `True` or `False`. - **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program? - **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker. -**Prototype & Test:** Use the classwork below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule. +**Prototype & Test:** Use the Popcorn Hacks below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule. --- @@ -40,7 +40,7 @@ A **Boolean expression** is a question that evaluates to only `True` or `False`. **Success Criteria:** You can predict whether an expression is `True` or `False`, write a condition from a rule in normal English, and test the condition with more than one set of values. -### Part 1: Comparisons Create Booleans +### Tech Talk 1: Comparisons Create Booleans Python comparison operators return `True` or `False`. @@ -65,7 +65,7 @@ Remember: - `score = 90` assigns a value. - `score == 90` compares two values. -### Part 2: `and`, `or`, and `not` +### Tech Talk 2: `and`, `or`, and `not` Sometimes one comparison is not enough. @@ -92,7 +92,7 @@ is_teenager = age >= 13 and age <= 19 print(is_teenager) ``` -### Part 3: Booleans Control `if` Statements +### Tech Talk 3: Booleans Control `if` Statements An `if` statement runs when its condition is true. @@ -120,9 +120,9 @@ ELSE --- -## 3. Classwork & Practice Tasks +## 3. Popcorn Hacks & Practice Tasks -### Classwork 1: Predict Before You Run +### Popcorn Hack 1: Predict Before You Run Predict each result first. Then run the code and compare. @@ -135,7 +135,7 @@ print(10 <= 10) For each line, write `True` or `False` and one short reason. -### Classwork 2: Fix the Logic +### Popcorn Hack 2: Fix the Logic A level should unlock only when the player has **at least 10 coins AND has found the key**. @@ -158,7 +158,7 @@ Do these four things: 3. Test at least three combinations of `coins` and `has_key`. 4. Explain why the rule needs `and` or `or`. -### Classwork 3: Translate the Logic +### Popcorn Hack 3: Translate the Logic Start with this Python expression: @@ -168,7 +168,7 @@ has_ticket or on_guest_list Write the same Boolean expression in JavaScript and College Board pseudocode. Then explain what word in **"ticket or guest list"** tells you which operator to use. -### Homework: Boolean Decision Checker +### Popcorn Hack 4: Boolean Decision Checker A student can use a study room when: - they are logged in, @@ -196,16 +196,19 @@ Test at least four cases, including one where the room is closed and one where t ## 4. Grading Plan (1 Point Total) -- **0.2 points — Classwork 1:** Correctly predict each Boolean result and include a short explanation. -- **0.2 points — Classwork 2:** Fix the Boolean logic and test at least three combinations. -- **0.2 points — Classwork 3:** Correctly translate the Boolean expression into JavaScript and College Board pseudocode. -- **0.4 points — Homework:** Build the study-room Boolean expression using all required conditions, test at least four cases, and explain the final expression in 2–3 sentences. +| Activity | Points | What earns the points | +| --- | ---: | --- | +| Popcorn Hack 1 | 0.2 | Correctly predict each Boolean result and include a short explanation. | +| Popcorn Hack 2 | 0.2 | Fix the Boolean logic and test at least three combinations. | +| Popcorn Hack 3 | 0.2 | Correctly translate the Boolean expression into JavaScript and College Board pseudocode. | +| Popcorn Hack 4 | 0.4 | Build the study-room Boolean expression using all required conditions, test at least four cases, and explain the final expression in 2–3 sentences. | +| **Total** | **1.0** | | --- ## 5. Lesson Revisions & Feedback Evidence - The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson. -- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack. +- Activity names use **Tech Talk** for instruction and **Popcorn Hack** for practice tasks. - Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids. - Feedback from a practice run can be added here with the specific change that was made because of it. diff --git a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md index 9b3abf7a36..9ca4d2ff3f 100644 --- a/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md +++ b/_notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md @@ -31,7 +31,7 @@ A **random value** is selected from a set or range of possible values. Python is - **HMW Question:** How might we show randomness in a way that students can predict the possible outputs even though they cannot predict the exact next result? - **Activity:** Predict ranges, use `random.choice`, fix a wrong range, and build a small dice game. -**Prototype & Test:** Use the classwork below to check whether students can list possible outputs, recognize valid ranges, and use a random result inside a decision. +**Prototype & Test:** Use the Popcorn Hacks below to check whether students can list possible outputs, recognize valid ranges, and use a random result inside a decision. --- @@ -41,7 +41,7 @@ A **random value** is selected from a set or range of possible values. Python is **Success Criteria:** You can identify every possible output of a random expression, choose the correct range, and explain why repeated results are allowed. -### Part 1: Random Integers +### Tech Talk 1: Random Integers Python's built-in `random` module gives us tools for random values. @@ -56,7 +56,7 @@ print("Die roll:", die_roll) For a normal die, the possible results are `1`, `2`, `3`, `4`, `5`, and `6`. -### Part 2: Random Choices +### Tech Talk 2: Random Choices Python can choose directly from a list. @@ -79,7 +79,7 @@ The same random-integer idea looks like this in the three forms: | JavaScript | `Math.floor(Math.random() * 6) + 1` | | College Board pseudocode | `RANDOM(1, 6)` | -### Part 3: Use Random Values in Decisions +### Tech Talk 3: Use Random Values in Decisions A program can generate a random value and then use that result in an `if` statement. @@ -98,9 +98,9 @@ Random does **not** mean every possible result appears once before a repeat. Rep --- -## 3. Classwork & Practice Tasks +## 3. Popcorn Hacks & Practice Tasks -### Classwork 1: Predict the Range +### Popcorn Hack 1: Predict the Range Before running this expression: @@ -117,7 +117,7 @@ answer: Then test it several times. -### Classwork 2: Random Choice +### Popcorn Hack 2: Random Choice ```python import random @@ -135,7 +135,7 @@ Do these five things: 4. Explain why the same snack can appear more than once. 5. Replace the list with your own category. -### Classwork 3: Fix the Range +### Popcorn Hack 3: Fix the Range This is supposed to simulate a six-sided die, but the range is wrong. @@ -148,7 +148,7 @@ print(die) List the current possible results, fix the range so it returns `1` through `6`, and write the corrected random expression in JavaScript and College Board pseudocode. -### Homework: Random Game Challenge +### Popcorn Hack 4: Random Game Challenge Build a small Python program using randomness. You can make a dice game, random prize, activity picker, opponent move, or another simple idea. @@ -163,16 +163,19 @@ Your program must: ## 4. Grading Plan (1 Point Total) -- **0.2 points — Classwork 1:** Correctly identify the smallest, largest, and all possible values in the random range. -- **0.2 points — Classwork 2:** Use `random.choice()` correctly, modify the list, and explain why repeats are possible. -- **0.2 points — Classwork 3:** Fix the six-sided die range and correctly write the equivalent JavaScript and College Board pseudocode. -- **0.4 points — Homework:** Build a working random program with at least three possible outcomes, use the random result in a meaningful decision or action, handle repeats, and explain the possible outputs. +| Activity | Points | What earns the points | +| --- | ---: | --- | +| Popcorn Hack 1 | 0.2 | Correctly identify the smallest, largest, and all possible values in the random range. | +| Popcorn Hack 2 | 0.2 | Use `random.choice()` correctly, modify the list, and explain why repeats are possible. | +| Popcorn Hack 3 | 0.2 | Fix the six-sided die range and correctly write the equivalent JavaScript and College Board pseudocode. | +| Popcorn Hack 4 | 0.4 | Build a working random program with at least three possible outcomes, use the random result in a meaningful decision or action, handle repeats, and explain the possible outputs. | +| **Total** | **1.0** | | --- ## 5. Lesson Revisions & Feedback Evidence - The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson. -- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack. +- Activity names use **Tech Talk** for instruction and **Popcorn Hack** for practice tasks. - Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids. - Feedback from a practice run can be added here with the specific change that was made because of it. diff --git a/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb b/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb index 96ab49145d..d3d5925364 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-boolean_scratchers_py_hw.ipynb @@ -1 +1 @@ -{"cells":[{"cell_type":"raw","id":"frontmatter","metadata":{"vscode":{"languageId":"raw"}},"source":["---\n","layout: post\n","categories: [Python, Boolean-Expressions]\n","lesson_language: Python\n","lesson_topic: Boolean-Expressions\n","lesson_part: interactive\n","lesson_type: lesson\n","codemirror: true\n","microblog: true\n","toc: false\n","comments: false\n","title: 3.5 Boolean Expressions (PY)\n","description: Learn Boolean expressions in Python using the five-part LxD lesson format.\n","permalink: /python/boolean/py\n","---"]},{"cell_type":"markdown","id":"md1","metadata":{},"source":["# 3.5 Boolean Expressions in Python\n","\n","A **Boolean expression** is a question that evaluates to only `True` or `False`. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n","\n","## 1. LxD Cycle Process\n","\n","**Empathize:** Boolean expressions can look simple, but it is easy to mix up `and` and `or`, forget a boundary such as `>=`, or write a condition that does not match the rule in normal English.\n","\n","**Define:**\n","- **POV:** CSP students need a clear way to turn real-world rules into Boolean expressions so their programs make the correct decisions.\n","- **Learning Goal:** Students will be able to evaluate, write, test, and explain Boolean expressions in Python.\n","\n","**Ideate:**\n","- **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program?\n","- **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker.\n","\n","**Prototype & Test:** Use the classwork below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule.\n","\n","---\n","\n","## 2. Lesson Plan\n","\n","**Learning Objective:** By the end of this lesson, you will be able to use comparisons, `and`, `or`, and `not` to create Boolean expressions and use them in Python decisions.\n","\n","**Success Criteria:** You can predict whether an expression is `True` or `False`, write a condition from a rule in normal English, and test the condition with more than one set of values.\n","\n","### Part 1: Comparisons Create Booleans\n","\n","Python comparison operators return `True` or `False`.\n","\n","| Python | Meaning | Example |\n","| --- | --- | --- |\n","| `==` | equal to | `score == 90` |\n","| `!=` | not equal to | `score != 0` |\n","| `>` | greater than | `score > 70` |\n","| `<` | less than | `age < 18` |\n","| `>=` | greater than or equal to | `score >= 70` |\n","| `<=` | less than or equal to | `age <= 18` |"]},{"cell_type":"code","execution_count":null,"id":"code2","metadata":{},"outputs":[],"source":["score = 82\n","\n","print(score >= 70)\n","print(score == 100)\n","print(score != 0)"]},{"cell_type":"markdown","id":"md3","metadata":{},"source":["Remember:\n","- `score = 90` assigns a value.\n","- `score == 90` compares two values.\n","\n","### Part 2: `and`, `or`, and `not`\n","\n","Sometimes one comparison is not enough.\n","\n","| Idea | Python | JavaScript | College Board pseudocode |\n","| --- | --- | --- | --- |\n","| both must be true | `and` | `&&` | `AND` |\n","| at least one is true | `or` | `||` | `OR` |\n","| reverse true/false | `not` | `!` | `NOT` |"]},{"cell_type":"code","execution_count":null,"id":"code4","metadata":{},"outputs":[],"source":["has_id = True\n","has_ticket = False\n","\n","print(has_id and has_ticket)\n","print(has_id or has_ticket)\n","print(not has_ticket)"]},{"cell_type":"markdown","id":"md5","metadata":{},"source":["A longer expression can be read one part at a time:"]},{"cell_type":"code","execution_count":null,"id":"code6","metadata":{},"outputs":[],"source":["age = 16\n","is_teenager = age >= 13 and age <= 19\n","print(is_teenager)"]},{"cell_type":"markdown","id":"md7","metadata":{},"source":["### Part 3: Booleans Control `if` Statements\n","\n","An `if` statement runs when its condition is true."]},{"cell_type":"code","execution_count":null,"id":"code8","metadata":{},"outputs":[],"source":["temperature = 72\n","\n","if temperature >= 70:\n"," print(\"It is warm outside.\")\n","else:\n"," print(\"It is not warm outside.\")"]},{"cell_type":"markdown","id":"md9","metadata":{},"source":["The same basic decision in College Board pseudocode is:\n","\n","```text\n","IF(temperature ≥ 70)\n","{\n"," DISPLAY(\"It is warm outside.\")\n","}\n","ELSE\n","{\n"," DISPLAY(\"It is not warm outside.\")\n","}\n","```\n","\n","---\n","\n","## 3. Classwork & Practice Tasks\n","\n","### Classwork 1: Predict Before You Run\n","\n","Predict each result first. Then run the code and compare."]},{"cell_type":"code","execution_count":null,"id":"code10","metadata":{},"outputs":[],"source":["print(8 > 5)\n","print(4 == 7)\n","print(\"cat\" != \"dog\")\n","print(10 <= 10)"]},{"cell_type":"markdown","id":"md11","metadata":{},"source":["For each line, write `True` or `False` and one short reason.\n","\n","### Classwork 2: Fix the Logic\n","\n","A level should unlock only when the player has **at least 10 coins AND has found the key**."]},{"cell_type":"code","execution_count":null,"id":"code12","metadata":{},"outputs":[],"source":["coins = 12\n","has_key = False\n","\n","# Fix the condition so both requirements are needed.\n","can_unlock = coins >= 10 or has_key\n","\n","if can_unlock:\n"," print(\"Level unlocked\")\n","else:\n"," print(\"Keep looking\")"]},{"cell_type":"markdown","id":"md13","metadata":{},"source":["Do these four things:\n","1. Predict what the current code prints.\n","2. Fix the Boolean expression.\n","3. Test at least three combinations of `coins` and `has_key`.\n","4. Explain why the rule needs `and` or `or`.\n","\n","### Classwork 3: Translate the Logic\n","\n","Start with this Python expression:"]},{"cell_type":"code","execution_count":null,"id":"code14","metadata":{},"outputs":[],"source":["has_ticket or on_guest_list"]},{"cell_type":"markdown","id":"md15","metadata":{},"source":["Write the same Boolean expression in JavaScript and College Board pseudocode. Then explain what word in **\"ticket or guest list\"** tells you which operator to use.\n","\n","### Homework: Boolean Decision Checker\n","\n","A student can use a study room when:\n","- they are logged in,\n","- they reserved the room **or** a teacher gave permission,\n","- and the room is **not** closed."]},{"cell_type":"code","execution_count":null,"id":"code16","metadata":{},"outputs":[],"source":["logged_in = True\n","reserved_room = False\n","teacher_permission = True\n","room_closed = False\n","\n","# Replace False with one Boolean expression.\n","can_use_room = False\n","\n","if can_use_room:\n"," print(\"Study room access approved\")\n","else:\n"," print(\"Study room access denied\")"]},{"cell_type":"markdown","id":"md17","metadata":{},"source":["Test at least four cases, including one where the room is closed and one where the student is not logged in. Then explain your Boolean expression in 2–3 sentences.\n","\n","---\n","\n","## 4. Grading Plan (1 Point Total)\n","\n","- **0.2 points — Classwork 1:** Correctly predict each Boolean result and include a short explanation.\n","- **0.2 points — Classwork 2:** Fix the Boolean logic and test at least three combinations.\n","- **0.2 points — Classwork 3:** Correctly translate the Boolean expression into JavaScript and College Board pseudocode.\n","- **0.4 points — Homework:** Build the study-room Boolean expression using all required conditions, test at least four cases, and explain the final expression in 2–3 sentences.\n","\n","---\n","\n","## 5. Lesson Revisions & Feedback Evidence\n","\n","- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n","- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack.\n","- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n","- Feedback from a practice run can be added here with the specific change that was made because of it."]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3"}},"nbformat":4,"nbformat_minor":5} \ No newline at end of file +{"cells":[{"cell_type":"raw","id":"frontmatter","metadata":{"vscode":{"languageId":"raw"}},"source":["---\n","layout: post\n","categories: [Python, Boolean-Expressions]\n","lesson_language: Python\n","lesson_topic: Boolean-Expressions\n","lesson_part: interactive\n","lesson_type: lesson\n","codemirror: true\n","microblog: true\n","toc: false\n","comments: false\n","title: 3.5 Boolean Expressions (PY)\n","description: Learn Boolean expressions in Python using the five-part LxD lesson format.\n","permalink: /python/boolean/py\n","---"]},{"cell_type":"markdown","id":"md1","metadata":{},"source":["# 3.5 Boolean Expressions in Python\n","\n","A **Boolean expression** is a question that evaluates to only `True` or `False`. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n","\n","## 1. LxD Cycle Process\n","\n","**Empathize:** Boolean expressions can look simple, but it is easy to mix up `and` and `or`, forget a boundary such as `>=`, or write a condition that does not match the rule in normal English.\n","\n","**Define:**\n","- **POV:** CSP students need a clear way to turn real-world rules into Boolean expressions so their programs make the correct decisions.\n","- **Learning Goal:** Students will be able to evaluate, write, test, and explain Boolean expressions in Python.\n","\n","**Ideate:**\n","- **HMW Question:** How might we make Boolean logic easier to understand before students have to write a full program?\n","- **Activity:** Predict Boolean results, fix an incorrect condition, and then build one complete decision checker.\n","\n","**Prototype & Test:** Use the Popcorn Hacks below to check whether students can predict results before running code, choose the correct Boolean operator, and explain why their expression matches the rule.\n","\n","---\n","\n","## 2. Lesson Plan\n","\n","**Learning Objective:** By the end of this lesson, you will be able to use comparisons, `and`, `or`, and `not` to create Boolean expressions and use them in Python decisions.\n","\n","**Success Criteria:** You can predict whether an expression is `True` or `False`, write a condition from a rule in normal English, and test the condition with more than one set of values.\n","\n","### Tech Talk 1: Comparisons Create Booleans\n","\n","Python comparison operators return `True` or `False`.\n","\n","| Python | Meaning | Example |\n","| --- | --- | --- |\n","| `==` | equal to | `score == 90` |\n","| `!=` | not equal to | `score != 0` |\n","| `>` | greater than | `score > 70` |\n","| `<` | less than | `age < 18` |\n","| `>=` | greater than or equal to | `score >= 70` |\n","| `<=` | less than or equal to | `age <= 18` |"]},{"cell_type":"code","execution_count":null,"id":"code2","metadata":{},"outputs":[],"source":["score = 82\n","\n","print(score >= 70)\n","print(score == 100)\n","print(score != 0)"]},{"cell_type":"markdown","id":"md3","metadata":{},"source":["Remember:\n","- `score = 90` assigns a value.\n","- `score == 90` compares two values.\n","\n","### Tech Talk 2: `and`, `or`, and `not`\n","\n","Sometimes one comparison is not enough.\n","\n","| Idea | Python | JavaScript | College Board pseudocode |\n","| --- | --- | --- | --- |\n","| both must be true | `and` | `&&` | `AND` |\n","| at least one is true | `or` | `||` | `OR` |\n","| reverse true/false | `not` | `!` | `NOT` |"]},{"cell_type":"code","execution_count":null,"id":"code4","metadata":{},"outputs":[],"source":["has_id = True\n","has_ticket = False\n","\n","print(has_id and has_ticket)\n","print(has_id or has_ticket)\n","print(not has_ticket)"]},{"cell_type":"markdown","id":"md5","metadata":{},"source":["A longer expression can be read one part at a time:"]},{"cell_type":"code","execution_count":null,"id":"code6","metadata":{},"outputs":[],"source":["age = 16\n","is_teenager = age >= 13 and age <= 19\n","print(is_teenager)"]},{"cell_type":"markdown","id":"md7","metadata":{},"source":["### Tech Talk 3: Booleans Control `if` Statements\n","\n","An `if` statement runs when its condition is true."]},{"cell_type":"code","execution_count":null,"id":"code8","metadata":{},"outputs":[],"source":["temperature = 72\n","\n","if temperature >= 70:\n"," print(\"It is warm outside.\")\n","else:\n"," print(\"It is not warm outside.\")"]},{"cell_type":"markdown","id":"md9","metadata":{},"source":["The same basic decision in College Board pseudocode is:\n","\n","```text\n","IF(temperature ≥ 70)\n","{\n"," DISPLAY(\"It is warm outside.\")\n","}\n","ELSE\n","{\n"," DISPLAY(\"It is not warm outside.\")\n","}\n","```\n","\n","---\n","\n","## 3. Popcorn Hacks & Practice Tasks\n","\n","### Popcorn Hack 1: Predict Before You Run\n","\n","Predict each result first. Then run the code and compare."]},{"cell_type":"code","execution_count":null,"id":"code10","metadata":{},"outputs":[],"source":["print(8 > 5)\n","print(4 == 7)\n","print(\"cat\" != \"dog\")\n","print(10 <= 10)"]},{"cell_type":"markdown","id":"md11","metadata":{},"source":["For each line, write `True` or `False` and one short reason.\n","\n","### Popcorn Hack 2: Fix the Logic\n","\n","A level should unlock only when the player has **at least 10 coins AND has found the key**."]},{"cell_type":"code","execution_count":null,"id":"code12","metadata":{},"outputs":[],"source":["coins = 12\n","has_key = False\n","\n","# Fix the condition so both requirements are needed.\n","can_unlock = coins >= 10 or has_key\n","\n","if can_unlock:\n"," print(\"Level unlocked\")\n","else:\n"," print(\"Keep looking\")"]},{"cell_type":"markdown","id":"md13","metadata":{},"source":["Do these four things:\n","1. Predict what the current code prints.\n","2. Fix the Boolean expression.\n","3. Test at least three combinations of `coins` and `has_key`.\n","4. Explain why the rule needs `and` or `or`.\n","\n","### Popcorn Hack 3: Translate the Logic\n","\n","Start with this Python expression:"]},{"cell_type":"code","execution_count":null,"id":"code14","metadata":{},"outputs":[],"source":["has_ticket or on_guest_list"]},{"cell_type":"markdown","id":"md15","metadata":{},"source":["Write the same Boolean expression in JavaScript and College Board pseudocode. Then explain what word in **\"ticket or guest list\"** tells you which operator to use.\n","\n","### Popcorn Hack 4: Boolean Decision Checker\n","\n","A student can use a study room when:\n","- they are logged in,\n","- they reserved the room **or** a teacher gave permission,\n","- and the room is **not** closed."]},{"cell_type":"code","execution_count":null,"id":"code16","metadata":{},"outputs":[],"source":["logged_in = True\n","reserved_room = False\n","teacher_permission = True\n","room_closed = False\n","\n","# Replace False with one Boolean expression.\n","can_use_room = False\n","\n","if can_use_room:\n"," print(\"Study room access approved\")\n","else:\n"," print(\"Study room access denied\")"]},{"cell_type":"markdown","id":"md17","metadata":{},"source":["Test at least four cases, including one where the room is closed and one where the student is not logged in. Then explain your Boolean expression in 2–3 sentences.\n","\n","---\n","\n","## 4. Grading Plan (1 Point Total)\n","\n","| Activity | Points | What earns the points |\n","| --- | ---: | --- |\n","| Popcorn Hack 1 | 0.2 | Correctly predict each Boolean result and include a short explanation. |\n","| Popcorn Hack 2 | 0.2 | Fix the Boolean logic and test at least three combinations. |\n","| Popcorn Hack 3 | 0.2 | Correctly translate the Boolean expression into JavaScript and College Board pseudocode. |\n","| Popcorn Hack 4 | 0.4 | Build the study-room Boolean expression using all required conditions, test at least four cases, and explain the final expression in 2–3 sentences. |\n","| **Total** | **1.0** | |\n","\n","---\n","\n","## 5. Lesson Revisions & Feedback Evidence\n","\n","- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n","- Activity names use **Tech Talk** for instruction and **Popcorn Hack** for practice tasks.\n","- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n","- Feedback from a practice run can be added here with the specific change that was made because of it."]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3"}},"nbformat":4,"nbformat_minor":5} \ No newline at end of file diff --git a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb index 5cdd938533..3ec0a6fd46 100644 --- a/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-15-random_py_sprinters.ipynb @@ -1 +1 @@ -{"cells":[{"cell_type":"raw","id":"frontmatter","metadata":{"vscode":{"languageId":"raw"}},"source":["---\n","layout: post\n","categories: [Python, Random-Values]\n","lesson_language: Python\n","lesson_topic: Random-Values\n","lesson_part: interactive\n","lesson_type: lesson\n","codemirror: true\n","microblog: true\n","toc: false\n","comments: false\n","title: 3.15 Random Values (PY)\n","description: Learn random values in Python using the five-part LxD lesson format.\n","permalink: /csp/big-idea-3/RandomPY/p3/Lesson\n","authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n","---"]},{"cell_type":"markdown","id":"md1","metadata":{},"source":["# 3.15 Random Values in Python\n","\n","A **random value** is selected from a set or range of possible values. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n","\n","## 1. LxD Cycle Process\n","\n","**Empathize:** Random code can be confusing because students may expect every result to appear once before a repeat, forget that `randint` includes both endpoints, or choose a range with the wrong values.\n","\n","**Define:**\n","- **POV:** CSP students need a simple way to connect familiar random events, such as dice rolls, to the code that creates random values.\n","- **Learning Goal:** Students will be able to generate, test, and explain random values in Python.\n","\n","**Ideate:**\n","- **HMW Question:** How might we show randomness in a way that students can predict the possible outputs even though they cannot predict the exact next result?\n","- **Activity:** Predict ranges, use `random.choice`, fix a wrong range, and build a small dice game.\n","\n","**Prototype & Test:** Use the classwork below to check whether students can list possible outputs, recognize valid ranges, and use a random result inside a decision.\n","\n","---\n","\n","## 2. Lesson Plan\n","\n","**Learning Objective:** By the end of this lesson, you will be able to use Python's `random` module to generate random integers, choose random list items, and use random results in a program.\n","\n","**Success Criteria:** You can identify every possible output of a random expression, choose the correct range, and explain why repeated results are allowed.\n","\n","### Part 1: Random Integers\n","\n","Python's built-in `random` module gives us tools for random values."]},{"cell_type":"code","execution_count":null,"id":"code2","metadata":{},"outputs":[],"source":["import random\n","\n","die_roll = random.randint(1, 6)\n","print(\"Die roll:\", die_roll)"]},{"cell_type":"markdown","id":"md3","metadata":{},"source":["`random.randint(a, b)` can return any whole number from `a` through `b`, including both endpoints.\n","\n","For a normal die, the possible results are `1`, `2`, `3`, `4`, `5`, and `6`.\n","\n","### Part 2: Random Choices\n","\n","Python can choose directly from a list."]},{"cell_type":"code","execution_count":null,"id":"code4","metadata":{},"outputs":[],"source":["import random\n","\n","activities = [\"study\", \"stretch\", \"walk\", \"get water\"]\n","pick = random.choice(activities)\n","\n","print(\"Random activity:\", pick)"]},{"cell_type":"markdown","id":"md5","metadata":{},"source":["The result must be one item from the list.\n","\n","The same random-integer idea looks like this in the three forms:\n","\n","| Form | Random integer from 1 through 6 |\n","| --- | --- |\n","| Python | `random.randint(1, 6)` |\n","| JavaScript | `Math.floor(Math.random() * 6) + 1` |\n","| College Board pseudocode | `RANDOM(1, 6)` |\n","\n","### Part 3: Use Random Values in Decisions\n","\n","A program can generate a random value and then use that result in an `if` statement."]},{"cell_type":"code","execution_count":null,"id":"code6","metadata":{},"outputs":[],"source":["import random\n","\n","flip = random.randint(1, 2)\n","\n","if flip == 1:\n"," print(\"Heads\")\n","else:\n"," print(\"Tails\")"]},{"cell_type":"markdown","id":"md7","metadata":{},"source":["Random does **not** mean every possible result appears once before a repeat. Repeats are normal.\n","\n","---\n","\n","## 3. Classwork & Practice Tasks\n","\n","### Classwork 1: Predict the Range\n","\n","Before running this expression:"]},{"cell_type":"code","execution_count":null,"id":"code8","metadata":{},"outputs":[],"source":["random.randint(3, 7)"]},{"cell_type":"markdown","id":"md9","metadata":{},"source":["answer:\n","1. What is the smallest possible result?\n","2. What is the largest possible result?\n","3. List every possible integer.\n","4. Could it return `2`?\n","5. Could it return `7`?\n","\n","Then test it several times.\n","\n","### Classwork 2: Random Choice"]},{"cell_type":"code","execution_count":null,"id":"code10","metadata":{},"outputs":[],"source":["import random\n","\n","snacks = [\"chips\", \"fruit\", \"cookies\", \"popcorn\"]\n","snack = random.choice(snacks)\n","\n","print(\"Selected snack:\", snack)"]},{"cell_type":"markdown","id":"md11","metadata":{},"source":["Do these five things:\n","1. List every value that can be printed.\n","2. Add one new snack.\n","3. Run the code at least five times.\n","4. Explain why the same snack can appear more than once.\n","5. Replace the list with your own category.\n","\n","### Classwork 3: Fix the Range\n","\n","This is supposed to simulate a six-sided die, but the range is wrong."]},{"cell_type":"code","execution_count":null,"id":"code12","metadata":{},"outputs":[],"source":["import random\n","\n","die = random.randint(0, 5)\n","print(die)"]},{"cell_type":"markdown","id":"md13","metadata":{},"source":["List the current possible results, fix the range so it returns `1` through `6`, and write the corrected random expression in JavaScript and College Board pseudocode.\n","\n","### Homework: Random Game Challenge\n","\n","Build a small Python program using randomness. You can make a dice game, random prize, activity picker, opponent move, or another simple idea.\n","\n","Your program must:\n","1. use `random.randint(...)` or `random.choice(...)`,\n","2. have at least three possible random results,\n","3. use the random result in an `if` / `elif` / `else` or another meaningful action,\n","4. still work when a value repeats,\n","5. include 2–3 sentences explaining the possible outputs.\n","\n","---\n","\n","## 4. Grading Plan (1 Point Total)\n","\n","- **0.2 points — Classwork 1:** Correctly identify the smallest, largest, and all possible values in the random range.\n","- **0.2 points — Classwork 2:** Use `random.choice()` correctly, modify the list, and explain why repeats are possible.\n","- **0.2 points — Classwork 3:** Fix the six-sided die range and correctly write the equivalent JavaScript and College Board pseudocode.\n","- **0.4 points — Homework:** Build a working random program with at least three possible outcomes, use the random result in a meaningful decision or action, handle repeats, and explain the possible outputs.\n","\n","---\n","\n","## 5. Lesson Revisions & Feedback Evidence\n","\n","- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n","- Activity names use **Part**, **Classwork**, and **Homework** instead of labels such as Tech Talk or Popcorn Hack.\n","- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n","- Feedback from a practice run can be added here with the specific change that was made because of it."]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3"}},"nbformat":4,"nbformat_minor":5} \ No newline at end of file +{"cells":[{"cell_type":"raw","id":"frontmatter","metadata":{"vscode":{"languageId":"raw"}},"source":["---\n","layout: post\n","categories: [Python, Random-Values]\n","lesson_language: Python\n","lesson_topic: Random-Values\n","lesson_part: interactive\n","lesson_type: lesson\n","codemirror: true\n","microblog: true\n","toc: false\n","comments: false\n","title: 3.15 Random Values (PY)\n","description: Learn random values in Python using the five-part LxD lesson format.\n","permalink: /csp/big-idea-3/RandomPY/p3/Lesson\n","authors: Ruhaan Bansal, Deyar Raissadat, Arya Taghavi Zargar\n","---"]},{"cell_type":"markdown","id":"md1","metadata":{},"source":["# 3.15 Random Values in Python\n","\n","A **random value** is selected from a set or range of possible values. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n","\n","## 1. LxD Cycle Process\n","\n","**Empathize:** Random code can be confusing because students may expect every result to appear once before a repeat, forget that `randint` includes both endpoints, or choose a range with the wrong values.\n","\n","**Define:**\n","- **POV:** CSP students need a simple way to connect familiar random events, such as dice rolls, to the code that creates random values.\n","- **Learning Goal:** Students will be able to generate, test, and explain random values in Python.\n","\n","**Ideate:**\n","- **HMW Question:** How might we show randomness in a way that students can predict the possible outputs even though they cannot predict the exact next result?\n","- **Activity:** Predict ranges, use `random.choice`, fix a wrong range, and build a small dice game.\n","\n","**Prototype & Test:** Use the Popcorn Hacks below to check whether students can list possible outputs, recognize valid ranges, and use a random result inside a decision.\n","\n","---\n","\n","## 2. Lesson Plan\n","\n","**Learning Objective:** By the end of this lesson, you will be able to use Python's `random` module to generate random integers, choose random list items, and use random results in a program.\n","\n","**Success Criteria:** You can identify every possible output of a random expression, choose the correct range, and explain why repeated results are allowed.\n","\n","### Tech Talk 1: Random Integers\n","\n","Python's built-in `random` module gives us tools for random values."]},{"cell_type":"code","execution_count":null,"id":"code2","metadata":{},"outputs":[],"source":["import random\n","\n","die_roll = random.randint(1, 6)\n","print(\"Die roll:\", die_roll)"]},{"cell_type":"markdown","id":"md3","metadata":{},"source":["`random.randint(a, b)` can return any whole number from `a` through `b`, including both endpoints.\n","\n","For a normal die, the possible results are `1`, `2`, `3`, `4`, `5`, and `6`.\n","\n","### Tech Talk 2: Random Choices\n","\n","Python can choose directly from a list."]},{"cell_type":"code","execution_count":null,"id":"code4","metadata":{},"outputs":[],"source":["import random\n","\n","activities = [\"study\", \"stretch\", \"walk\", \"get water\"]\n","pick = random.choice(activities)\n","\n","print(\"Random activity:\", pick)"]},{"cell_type":"markdown","id":"md5","metadata":{},"source":["The result must be one item from the list.\n","\n","The same random-integer idea looks like this in the three forms:\n","\n","| Form | Random integer from 1 through 6 |\n","| --- | --- |\n","| Python | `random.randint(1, 6)` |\n","| JavaScript | `Math.floor(Math.random() * 6) + 1` |\n","| College Board pseudocode | `RANDOM(1, 6)` |\n","\n","### Tech Talk 3: Use Random Values in Decisions\n","\n","A program can generate a random value and then use that result in an `if` statement."]},{"cell_type":"code","execution_count":null,"id":"code6","metadata":{},"outputs":[],"source":["import random\n","\n","flip = random.randint(1, 2)\n","\n","if flip == 1:\n"," print(\"Heads\")\n","else:\n"," print(\"Tails\")"]},{"cell_type":"markdown","id":"md7","metadata":{},"source":["Random does **not** mean every possible result appears once before a repeat. Repeats are normal.\n","\n","---\n","\n","## 3. Popcorn Hacks & Practice Tasks\n","\n","### Popcorn Hack 1: Predict the Range\n","\n","Before running this expression:"]},{"cell_type":"code","execution_count":null,"id":"code8","metadata":{},"outputs":[],"source":["random.randint(3, 7)"]},{"cell_type":"markdown","id":"md9","metadata":{},"source":["answer:\n","1. What is the smallest possible result?\n","2. What is the largest possible result?\n","3. List every possible integer.\n","4. Could it return `2`?\n","5. Could it return `7`?\n","\n","Then test it several times.\n","\n","### Popcorn Hack 2: Random Choice"]},{"cell_type":"code","execution_count":null,"id":"code10","metadata":{},"outputs":[],"source":["import random\n","\n","snacks = [\"chips\", \"fruit\", \"cookies\", \"popcorn\"]\n","snack = random.choice(snacks)\n","\n","print(\"Selected snack:\", snack)"]},{"cell_type":"markdown","id":"md11","metadata":{},"source":["Do these five things:\n","1. List every value that can be printed.\n","2. Add one new snack.\n","3. Run the code at least five times.\n","4. Explain why the same snack can appear more than once.\n","5. Replace the list with your own category.\n","\n","### Popcorn Hack 3: Fix the Range\n","\n","This is supposed to simulate a six-sided die, but the range is wrong."]},{"cell_type":"code","execution_count":null,"id":"code12","metadata":{},"outputs":[],"source":["import random\n","\n","die = random.randint(0, 5)\n","print(die)"]},{"cell_type":"markdown","id":"md13","metadata":{},"source":["List the current possible results, fix the range so it returns `1` through `6`, and write the corrected random expression in JavaScript and College Board pseudocode.\n","\n","### Popcorn Hack 4: Random Game Challenge\n","\n","Build a small Python program using randomness. You can make a dice game, random prize, activity picker, opponent move, or another simple idea.\n","\n","Your program must:\n","1. use `random.randint(...)` or `random.choice(...)`,\n","2. have at least three possible random results,\n","3. use the random result in an `if` / `elif` / `else` or another meaningful action,\n","4. still work when a value repeats,\n","5. include 2–3 sentences explaining the possible outputs.\n","\n","---\n","\n","## 4. Grading Plan (1 Point Total)\n","\n","| Activity | Points | What earns the points |\n","| --- | ---: | --- |\n","| Popcorn Hack 1 | 0.2 | Correctly identify the smallest, largest, and all possible values in the random range. |\n","| Popcorn Hack 2 | 0.2 | Use `random.choice()` correctly, modify the list, and explain why repeats are possible. |\n","| Popcorn Hack 3 | 0.2 | Fix the six-sided die range and correctly write the equivalent JavaScript and College Board pseudocode. |\n","| Popcorn Hack 4 | 0.4 | Build a working random program with at least three possible outcomes, use the random result in a meaningful decision or action, handle repeats, and explain the possible outputs. |\n","| **Total** | **1.0** | |\n","\n","---\n","\n","## 5. Lesson Revisions & Feedback Evidence\n","\n","- The lesson is organized into the same numbered `1` through `5` structure used by the reference lesson.\n","- Activity names use **Tech Talk** for instruction and **Popcorn Hack** for practice tasks.\n","- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n","- Feedback from a practice run can be added here with the specific change that was made because of it."]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3"}},"nbformat":4,"nbformat_minor":5} \ No newline at end of file From 19a98924812e865b13b58d83d361edd5fe18ee93 Mon Sep 17 00:00:00 2001 From: jm1021 Date: Thu, 17 Sep 2026 04:38:32 -0700 Subject: [PATCH 36/43] organize remnants of CSP notebooks --- _includes/tailwind/simulations.html | 1524 ---------------- .../2026-05-12-AP_CSP_Comprehensive.ipynb | 0 ...026-04-07-identifying_and_correcting.ipynb | 0 ...-04-26-identifying-correcting-errors.ipynb | 0 .../2026-04-26-3.2_Undecidable_Problems.ipynb | 0 .../2026-04-27-3.16_Simulation.ipynb | 0 .../2026-05-12-AP-CSP_Pseudocode_runner.ipynb | 0 ...-04-22-bandwidthbitratelatencylesson.ipynb | 0 .../2026-03-04-phishinglesson.ipynb | 0 .../2026-04-24-computing_bias.ipynb | 0 .../big-idea-5/2026-04-27-simulations.ipynb | 1560 +++++++++++++++++ .../2026-05-01-beneficial-harmful.ipynb | 0 .../2026-05-01-legalethical.ipynb | 0 .../microblog/2025-10-28-microblog_api.ipynb | 0 .../2025-10-29-decentralization.ipynb | 0 .../microblog/2025-11-2-threat-modeling.ipynb | 0 .../Wi-Fighters/2026-04-27-simulations.ipynb | 37 - 17 files changed, 1560 insertions(+), 1561 deletions(-) delete mode 100644 _includes/tailwind/simulations.html rename _notebooks/CSP/{AP-prep => big-ideas}/2026-05-12-AP_CSP_Comprehensive.ipynb (100%) rename _notebooks/CSP/big-ideas/{big-idea-2 => big-idea-1}/2026-04-07-identifying_and_correcting.ipynb (100%) rename _notebooks/CSP/{lessons/Wi-Fighters => big-ideas/big-idea-1}/2026-04-26-identifying-correcting-errors.ipynb (100%) rename _notebooks/CSP/{AP-prep => big-ideas/big-idea-3}/2026-04-26-3.2_Undecidable_Problems.ipynb (100%) rename _notebooks/CSP/{AP-prep => big-ideas/big-idea-3}/2026-04-27-3.16_Simulation.ipynb (100%) rename _notebooks/CSP/{AP-prep => big-ideas/big-idea-3}/2026-05-12-AP-CSP_Pseudocode_runner.ipynb (100%) rename _notebooks/CSP/{AP-prep => big-ideas/big-idea-4}/2026-04-22-bandwidthbitratelatencylesson.ipynb (100%) rename _notebooks/CSP/{AP-prep => big-ideas/big-idea-5}/2026-03-04-phishinglesson.ipynb (100%) rename _notebooks/CSP/big-ideas/big-idea-5/{5-03-computing-bias => }/2026-04-24-computing_bias.ipynb (100%) create mode 100644 _notebooks/CSP/big-ideas/big-idea-5/2026-04-27-simulations.ipynb rename _notebooks/CSP/big-ideas/big-idea-5/{5-03-computing-bias => }/2026-05-01-beneficial-harmful.ipynb (100%) rename _notebooks/CSP/big-ideas/big-idea-5/{5-03-computing-bias => }/2026-05-01-legalethical.ipynb (100%) rename _notebooks/CSP/{digital-famine => flask}/microblog/2025-10-28-microblog_api.ipynb (100%) rename _notebooks/CSP/{digital-famine => flask}/microblog/2025-10-29-decentralization.ipynb (100%) rename _notebooks/CSP/{digital-famine => flask}/microblog/2025-11-2-threat-modeling.ipynb (100%) delete mode 100644 _notebooks/CSP/lessons/Wi-Fighters/2026-04-27-simulations.ipynb diff --git a/_includes/tailwind/simulations.html b/_includes/tailwind/simulations.html deleted file mode 100644 index 25f2cf88a9..0000000000 --- a/_includes/tailwind/simulations.html +++ /dev/null @@ -1,1524 +0,0 @@ - - -
- - -
-
-

AP CSP · Big Idea: Algorithms and Programming

-

Interactive Simulations Lab

-

Explore how simulations use inputs, randomness, repeated trials, and models to predict possible outcomes.

-
- 🎲 Randomness - ✈️ Real-world models - 📊 Data tables - 🧠 CSP reasoning -
- -
-
- - - - - -
-
- 🧪 -

What is a simulation?

-

A simulation imitates a real-world process using a model, inputs, rules, and outputs.

-
-
- 🎯 -

Why use simulations?

-

When real testing would be expensive, dangerous, slow, or impossible to repeat.

-
-
- 🌦️ -

What affects accuracy?

-

Missing variables, weak assumptions, or bad data make simulation results less reliable.

-
-
- 📈 -

What to observe?

-

Look for patterns over many trials. One result can be random — many reveal a trend.

-
-
- - -
-

AP CSP Simulation Vocabulary

-
- - - - - - - -
-
Click a vocabulary word to see a quick AP CSP definition.
-
- - -
-
-
-

Simulation 1

-

Dice Probability Simulator

-

Roll a die repeatedly and watch experimental probability move closer to theoretical probability.

-
-
- - -
-
- -
-

How this is a simulation

-

The die roll uses a random number generator. Each roll is one trial. The program stores results, calculates frequencies, and displays the output in a table.

-
- -
-
-
-
?
-
-
✦
-
✧
-
✦
-
-

Last roll

- No rolls yet -
-
-
- - - - - -
-
Total Rolls0
-
Most CommonN/A
-
Least CommonN/A
-
-
-
- -
-
-

Live Frequency Chart

-

Theoretical probability per side ≈ 16.7%

-
-
-
- -
-
-

Recorded Results

- -
- - - - - - - -
Dice ValueFrequencyExp. ProbabilityDiff from 16.7%Bar
-
- -
-

Quick Discussion Prompt

-

Why do the results usually become more balanced after more trials?

- -
-
- - -
-
-
-

Simulation 2

-

Flight Risk Simulator

-

Change the input variables and run a flight model that calculates risk using rules plus randomness.

-
-
- - -
-
- -
-

How this is a simulation

-

The flight model uses selected conditions as inputs. The algorithm converts them into a safety score (the likelihood of success). An uncertainty factor — a random number simulating unpredictable real-world variables like bird strikes, turbulence, or equipment glitches — is then compared to that score. If the uncertainty exceeds the safety margin, the flight fails.

-
- -
-
-
Environment
- - - -
Plane
- - - -
People
- - - - - -
- -
-
-
☀️
-
-
-
-
-
✈️
-
-
💥
-
-
-
-
-
-
-
-
-
Safety Score--%
-
Uncertainty Factor--
-
OutcomeWaiting
-
-
Choose inputs and run the flight simulation.
-
-
- -
-
-

Risk Factor Breakdown

-

These deductions show how the model makes decisions.

-
-
-
- -
-

Quick Discussion Prompt

-

Which input seems to affect the simulation the most, and why?

- -
-
- - -
-
-

Lesson Wrap-Up

-

Both simulations show that results depend on the model, assumptions, data, and number of trials — not just randomness alone.

-
-
-

Dice Simulator

-

Best for showing randomness, repeated trials, probability, and data collection.

-
-
-

Flight Simulator

-

Best for showing input variables, weighted conditions, assumptions, and limits of a model.

-
-
-
-
- - ↑ -
- - \ No newline at end of file diff --git a/_notebooks/CSP/AP-prep/2026-05-12-AP_CSP_Comprehensive.ipynb b/_notebooks/CSP/big-ideas/2026-05-12-AP_CSP_Comprehensive.ipynb similarity index 100% rename from _notebooks/CSP/AP-prep/2026-05-12-AP_CSP_Comprehensive.ipynb rename to _notebooks/CSP/big-ideas/2026-05-12-AP_CSP_Comprehensive.ipynb diff --git a/_notebooks/CSP/big-ideas/big-idea-2/2026-04-07-identifying_and_correcting.ipynb b/_notebooks/CSP/big-ideas/big-idea-1/2026-04-07-identifying_and_correcting.ipynb similarity index 100% rename from _notebooks/CSP/big-ideas/big-idea-2/2026-04-07-identifying_and_correcting.ipynb rename to _notebooks/CSP/big-ideas/big-idea-1/2026-04-07-identifying_and_correcting.ipynb diff --git a/_notebooks/CSP/lessons/Wi-Fighters/2026-04-26-identifying-correcting-errors.ipynb b/_notebooks/CSP/big-ideas/big-idea-1/2026-04-26-identifying-correcting-errors.ipynb similarity index 100% rename from _notebooks/CSP/lessons/Wi-Fighters/2026-04-26-identifying-correcting-errors.ipynb rename to _notebooks/CSP/big-ideas/big-idea-1/2026-04-26-identifying-correcting-errors.ipynb diff --git a/_notebooks/CSP/AP-prep/2026-04-26-3.2_Undecidable_Problems.ipynb b/_notebooks/CSP/big-ideas/big-idea-3/2026-04-26-3.2_Undecidable_Problems.ipynb similarity index 100% rename from _notebooks/CSP/AP-prep/2026-04-26-3.2_Undecidable_Problems.ipynb rename to _notebooks/CSP/big-ideas/big-idea-3/2026-04-26-3.2_Undecidable_Problems.ipynb diff --git a/_notebooks/CSP/AP-prep/2026-04-27-3.16_Simulation.ipynb b/_notebooks/CSP/big-ideas/big-idea-3/2026-04-27-3.16_Simulation.ipynb similarity index 100% rename from _notebooks/CSP/AP-prep/2026-04-27-3.16_Simulation.ipynb rename to _notebooks/CSP/big-ideas/big-idea-3/2026-04-27-3.16_Simulation.ipynb diff --git a/_notebooks/CSP/AP-prep/2026-05-12-AP-CSP_Pseudocode_runner.ipynb b/_notebooks/CSP/big-ideas/big-idea-3/2026-05-12-AP-CSP_Pseudocode_runner.ipynb similarity index 100% rename from _notebooks/CSP/AP-prep/2026-05-12-AP-CSP_Pseudocode_runner.ipynb rename to _notebooks/CSP/big-ideas/big-idea-3/2026-05-12-AP-CSP_Pseudocode_runner.ipynb diff --git a/_notebooks/CSP/AP-prep/2026-04-22-bandwidthbitratelatencylesson.ipynb b/_notebooks/CSP/big-ideas/big-idea-4/2026-04-22-bandwidthbitratelatencylesson.ipynb similarity index 100% rename from _notebooks/CSP/AP-prep/2026-04-22-bandwidthbitratelatencylesson.ipynb rename to _notebooks/CSP/big-ideas/big-idea-4/2026-04-22-bandwidthbitratelatencylesson.ipynb diff --git a/_notebooks/CSP/AP-prep/2026-03-04-phishinglesson.ipynb b/_notebooks/CSP/big-ideas/big-idea-5/2026-03-04-phishinglesson.ipynb similarity index 100% rename from _notebooks/CSP/AP-prep/2026-03-04-phishinglesson.ipynb rename to _notebooks/CSP/big-ideas/big-idea-5/2026-03-04-phishinglesson.ipynb diff --git a/_notebooks/CSP/big-ideas/big-idea-5/5-03-computing-bias/2026-04-24-computing_bias.ipynb b/_notebooks/CSP/big-ideas/big-idea-5/2026-04-24-computing_bias.ipynb similarity index 100% rename from _notebooks/CSP/big-ideas/big-idea-5/5-03-computing-bias/2026-04-24-computing_bias.ipynb rename to _notebooks/CSP/big-ideas/big-idea-5/2026-04-24-computing_bias.ipynb diff --git a/_notebooks/CSP/big-ideas/big-idea-5/2026-04-27-simulations.ipynb b/_notebooks/CSP/big-ideas/big-idea-5/2026-04-27-simulations.ipynb new file mode 100644 index 0000000000..bcb07b2b9a --- /dev/null +++ b/_notebooks/CSP/big-ideas/big-idea-5/2026-04-27-simulations.ipynb @@ -0,0 +1,1560 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "0a31bc83", + "metadata": {}, + "source": [ + "---\n", + "layout: tailwindPost\n", + "infoGraph: simulations\n", + "title: Interactive Simulations (Wi-Fighters)\n", + "description: Interactive CSP lesson on simulations with live predictions and coding.\n", + "microblog: true\n", + "permalink: /csp/simulations/p3/lesson/\n", + "Author: Laya Balaji, Meryl Chen\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "93182044", + "metadata": {}, + "source": [ + "## 🎲 Lesson provided by Wi-Fighters\n", + "\n", + "\n", + "\n", + "
\n", + "\n", + " \n", + "
\n", + "
\n", + "

AP CSP · Big Idea: Algorithms and Programming

\n", + "

Interactive Simulations Lab

\n", + "

Explore how simulations use inputs, randomness, repeated trials, and models to predict possible outcomes.

\n", + "
\n", + " 🎲 Randomness\n", + " ✈️ Real-world models\n", + " 📊 Data tables\n", + " 🧠 CSP reasoning\n", + "
\n", + "
\n", + " Start Dice Lab\n", + " Start Flight Lab\n", + "
\n", + "
\n", + "
\n", + "\n", + " \n", + " \n", + "\n", + " \n", + "
\n", + "
\n", + " 🧪\n", + "

What is a simulation?

\n", + "

A simulation imitates a real-world process using a model, inputs, rules, and outputs.

\n", + "
\n", + "
\n", + " 🎯\n", + "

Why use simulations?

\n", + "

When real testing would be expensive, dangerous, slow, or impossible to repeat.

\n", + "
\n", + "
\n", + " 🌦️\n", + "

What affects accuracy?

\n", + "

Missing variables, weak assumptions, or bad data make simulation results less reliable.

\n", + "
\n", + "
\n", + " 📈\n", + "

What to observe?

\n", + "

Look for patterns over many trials. One result can be random — many reveal a trend.

\n", + "
\n", + "
\n", + "\n", + " \n", + "
\n", + "

AP CSP Simulation Vocabulary

\n", + "
\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
\n", + "
Click a vocabulary word to see a quick AP CSP definition.
\n", + "
\n", + "\n", + " \n", + "
\n", + "
\n", + "
\n", + "

Simulation 1

\n", + "

Dice Probability Simulator

\n", + "

Roll a die repeatedly and watch experimental probability move closer to theoretical probability.

\n", + "
\n", + "
\n", + " \n", + " \n", + "
\n", + "
\n", + "\n", + "
\n", + "

How this is a simulation

\n", + "

The die roll uses a random number generator. Each roll is one trial. The program stores results, calculates frequencies, and displays the output in a table.

\n", + "
\n", + "\n", + "
\n", + "
\n", + "
\n", + "
?
\n", + "
\n", + "
✦
\n", + "
✧
\n", + "
✦
\n", + "
\n", + "

Last roll

\n", + " No rolls yet\n", + "
\n", + "
\n", + "
\n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
\n", + "
Total Rolls0
\n", + "
Most CommonN/A
\n", + "
Least CommonN/A
\n", + "
\n", + "
\n", + "
\n", + "\n", + "
\n", + "
\n", + "

Live Frequency Chart

\n", + "

Theoretical probability per side ≈ 16.7%

\n", + "
\n", + "
\n", + "
\n", + "\n", + "
\n", + "
\n", + "

Recorded Results

\n", + " \n", + "
\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
Dice ValueFrequencyExp. ProbabilityDiff from 16.7%Bar
\n", + "
\n", + "\n", + "
\n", + "

Quick Discussion Prompt

\n", + "

Why do the results usually become more balanced after more trials?

\n", + " \n", + "
\n", + "
\n", + "\n", + " \n", + "
\n", + "
\n", + "
\n", + "

Simulation 2

\n", + "

Flight Risk Simulator

\n", + "

Change the input variables and run a flight model that calculates risk using rules plus randomness.

\n", + "
\n", + "
\n", + " \n", + " \n", + "
\n", + "
\n", + "\n", + "
\n", + "

How this is a simulation

\n", + "

The flight model uses selected conditions as inputs. The algorithm converts them into a safety score (the likelihood of success). An uncertainty factor — a random number simulating unpredictable real-world variables like bird strikes, turbulence, or equipment glitches — is then compared to that score. If the uncertainty exceeds the safety margin, the flight fails.

\n", + "
\n", + "\n", + "
\n", + "
\n", + "
Environment
\n", + " \n", + " \n", + " \n", + "
Plane
\n", + " \n", + " \n", + " \n", + "
People
\n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
\n", + "\n", + "
\n", + "
\n", + "
☀️
\n", + "
\n", + "
\n", + "
\n", + "
\n", + "
✈️
\n", + "
\n", + "
💥
\n", + "
\n", + "
\n", + "
\n", + "
\n", + "
\n", + "
\n", + "
\n", + "
\n", + "
Safety Score--%
\n", + "
Uncertainty Factor--
\n", + "
OutcomeWaiting
\n", + "
\n", + "
Choose inputs and run the flight simulation.
\n", + "
\n", + "
\n", + "\n", + "
\n", + "
\n", + "

Risk Factor Breakdown

\n", + "

These deductions show how the model makes decisions.

\n", + "
\n", + "
\n", + "
\n", + "\n", + "
\n", + "

Quick Discussion Prompt

\n", + "

Which input seems to affect the simulation the most, and why?

\n", + " \n", + "
\n", + "
\n", + "\n", + " \n", + "
\n", + "
\n", + "

Lesson Wrap-Up

\n", + "

Both simulations show that results depend on the model, assumptions, data, and number of trials — not just randomness alone.

\n", + "
\n", + "
\n", + "

Dice Simulator

\n", + "

Best for showing randomness, repeated trials, probability, and data collection.

\n", + "
\n", + "
\n", + "

Flight Simulator

\n", + "

Best for showing input variables, weighted conditions, assumptions, and limits of a model.

\n", + "
\n", + "
\n", + "
\n", + "
\n", + "\n", + " ↑\n", + "
\n", + "\n", + "" + ] + } + ], + "metadata": { + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/_notebooks/CSP/big-ideas/big-idea-5/5-03-computing-bias/2026-05-01-beneficial-harmful.ipynb b/_notebooks/CSP/big-ideas/big-idea-5/2026-05-01-beneficial-harmful.ipynb similarity index 100% rename from _notebooks/CSP/big-ideas/big-idea-5/5-03-computing-bias/2026-05-01-beneficial-harmful.ipynb rename to _notebooks/CSP/big-ideas/big-idea-5/2026-05-01-beneficial-harmful.ipynb diff --git a/_notebooks/CSP/big-ideas/big-idea-5/5-03-computing-bias/2026-05-01-legalethical.ipynb b/_notebooks/CSP/big-ideas/big-idea-5/2026-05-01-legalethical.ipynb similarity index 100% rename from _notebooks/CSP/big-ideas/big-idea-5/5-03-computing-bias/2026-05-01-legalethical.ipynb rename to _notebooks/CSP/big-ideas/big-idea-5/2026-05-01-legalethical.ipynb diff --git a/_notebooks/CSP/digital-famine/microblog/2025-10-28-microblog_api.ipynb b/_notebooks/CSP/flask/microblog/2025-10-28-microblog_api.ipynb similarity index 100% rename from _notebooks/CSP/digital-famine/microblog/2025-10-28-microblog_api.ipynb rename to _notebooks/CSP/flask/microblog/2025-10-28-microblog_api.ipynb diff --git a/_notebooks/CSP/digital-famine/microblog/2025-10-29-decentralization.ipynb b/_notebooks/CSP/flask/microblog/2025-10-29-decentralization.ipynb similarity index 100% rename from _notebooks/CSP/digital-famine/microblog/2025-10-29-decentralization.ipynb rename to _notebooks/CSP/flask/microblog/2025-10-29-decentralization.ipynb diff --git a/_notebooks/CSP/digital-famine/microblog/2025-11-2-threat-modeling.ipynb b/_notebooks/CSP/flask/microblog/2025-11-2-threat-modeling.ipynb similarity index 100% rename from _notebooks/CSP/digital-famine/microblog/2025-11-2-threat-modeling.ipynb rename to _notebooks/CSP/flask/microblog/2025-11-2-threat-modeling.ipynb diff --git a/_notebooks/CSP/lessons/Wi-Fighters/2026-04-27-simulations.ipynb b/_notebooks/CSP/lessons/Wi-Fighters/2026-04-27-simulations.ipynb deleted file mode 100644 index 20c4577b7b..0000000000 --- a/_notebooks/CSP/lessons/Wi-Fighters/2026-04-27-simulations.ipynb +++ /dev/null @@ -1,37 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "0a31bc83", - "metadata": {}, - "source": [ - "---\n", - "layout: tailwindPost\n", - "infoGraph: simulations\n", - "title: Interactive Simulations (Wi-Fighters)\n", - "description: Interactive CSP lesson on simulations with live predictions and coding.\n", - "microblog: true\n", - "permalink: /csp/simulations/p3/lesson/\n", - "Author: Laya Balaji, Meryl Chen\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "93182044", - "metadata": {}, - "source": [ - "# 🎲 Lesson provided by Wi-Fighters\n", - "\n", - "{% include tailwind/simulations.html %}" - ] - } - ], - "metadata": { - "language_info": { - "name": "python" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} From 43cf980f9cf5532fcf742a14b3bdccb5af4af1b5 Mon Sep 17 00:00:00 2001 From: jm1021 Date: Thu, 17 Sep 2026 05:10:59 -0700 Subject: [PATCH 37/43] minor edits --- .../2026-09-16-libraries_python.ipynb | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb b/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb index 54f6ad749f..45257fbf76 100644 --- a/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb @@ -69,12 +69,12 @@ "**Define:**\n", "\n", "* **POV:** CSP students need to know how to find, read, and use libraries because rewriting existing code wastes time and missing packages break shared projects.\n", - "* **Learning Goal:** Students will import standard library modules, read API documentation to use their procedures, and explain how `requirements.txt` lists the external libraries a project needs.\n", + "* **Learning Goal:** Students will import standard library modules, read API documentation to use their procedures, and explain how `requirements.txt` lists the external libraries a Python project needs.\n", "\n", "**Ideate:**\n", "\n", - "* **HMW Question:** How might we show students that the libraries they use in class are the same ones that power Open Coding Society?\n", - "* **Activity:** Three short cycles of a tech talk followed by a code runner exercise, ending with a homework challenge that combines several libraries.\n", + "* **HMW Question:** How might we show students that the libraries they use in classroom work are the same ones that power Open Coding Society?\n", + "* **Activity:** Three short cycles of a tech talk followed by a code runner exercise. Follwed by an ending with a homework challenge that combines several libraries.\n", "\n", "**Prototype & Test:** _Add notes from your trial run with your project team here._\n", "\n", @@ -96,7 +96,7 @@ "| --- | --- | --- |\n", "| 1 | What is a library? APIs and documentation | Read the docs and use `math` and `random` |\n", "| 2 | Libraries in Open Coding Society | Read a notebook with `json`, like the OCS converter |\n", - "| 3 | `pip` and `requirements.txt` | Check a `requirements.txt` file |\n", + "| 3 | `pip install` and a projects `requirements.txt` | Check a `requirements.txt` file |\n", "| Homework | | Build a Study Session Report |\n", "\n", "---" @@ -141,8 +141,10 @@ }, { "cell_type": "code", + "execution_count": null, "id": "3f0655c0", "metadata": {}, + "outputs": [], "source": [ "# CODE_RUNNER: Popcorn Hack 1 - Read the API documentation, then finish the TODOs using math and random\n", "\n", @@ -171,9 +173,7 @@ "average = sum(scores) / len(scores)\n", "rounded_up = average\n", "print(\"Average:\", average, \"-> rounded up:\", rounded_up)" - ], - "execution_count": null, - "outputs": [] + ] }, { "cell_type": "markdown", @@ -219,8 +219,10 @@ }, { "cell_type": "code", + "execution_count": null, "id": "7dd45399", "metadata": {}, + "outputs": [], "source": [ "# CODE_RUNNER: Popcorn Hack 2 - Use the json library to read a notebook the way the OCS converter does\n", "\n", @@ -253,9 +255,7 @@ "print(\"Title:\", title)\n", "\n", "# TODO 3: Use json.dumps with indent=2 to print the last cell as formatted JSON" - ], - "execution_count": null, - "outputs": [] + ] }, { "cell_type": "markdown", @@ -321,8 +321,10 @@ }, { "cell_type": "code", + "execution_count": null, "id": "4749e167", "metadata": {}, + "outputs": [], "source": [ "# CODE_RUNNER: Popcorn Hack 3 - Finish the requirements.txt checker using importlib\n", "\n", @@ -373,9 +375,7 @@ " print(f\"{package!r:20} missing -> pip install {package}\")\n", "\n", "# TODO 3: Print is_installed(\"json\"). Why is json installed even though it is not in requirements.txt?" - ], - "execution_count": null, - "outputs": [] + ] }, { "cell_type": "markdown", @@ -438,8 +438,10 @@ }, { "cell_type": "code", + "execution_count": null, "id": "63eee878", "metadata": {}, + "outputs": [], "source": [ "# CODE_RUNNER: Homework - Build a Study Session Report using at least 3 libraries\n", "\n", @@ -475,9 +477,7 @@ "'''\n", "print(\"requirements.txt:\")\n", "print(requirements_txt)" - ], - "execution_count": null, - "outputs": [] + ] }, { "cell_type": "markdown", From 7dafa0453cc6576446f1747295fe72256e921318 Mon Sep 17 00:00:00 2001 From: jm1021 Date: Thu, 17 Sep 2026 05:11:15 -0700 Subject: [PATCH 38/43] relocate --- .../2026-04-24-compression_lesson.ipynb | 0 .../2026-05-12-AP-CSP_Pseudocode_runner.ipynb | 255 +++++++++++++++++- 2 files changed, 251 insertions(+), 4 deletions(-) rename _notebooks/CSP/big-ideas/big-idea-2/{2.2 compression => }/2026-04-24-compression_lesson.ipynb (100%) diff --git a/_notebooks/CSP/big-ideas/big-idea-2/2.2 compression/2026-04-24-compression_lesson.ipynb b/_notebooks/CSP/big-ideas/big-idea-2/2026-04-24-compression_lesson.ipynb similarity index 100% rename from _notebooks/CSP/big-ideas/big-idea-2/2.2 compression/2026-04-24-compression_lesson.ipynb rename to _notebooks/CSP/big-ideas/big-idea-2/2026-04-24-compression_lesson.ipynb diff --git a/_notebooks/CSP/big-ideas/big-idea-3/2026-05-12-AP-CSP_Pseudocode_runner.ipynb b/_notebooks/CSP/big-ideas/big-idea-3/2026-05-12-AP-CSP_Pseudocode_runner.ipynb index 10d02b8f04..1d6c86996e 100644 --- a/_notebooks/CSP/big-ideas/big-idea-3/2026-05-12-AP-CSP_Pseudocode_runner.ipynb +++ b/_notebooks/CSP/big-ideas/big-idea-3/2026-05-12-AP-CSP_Pseudocode_runner.ipynb @@ -1,7 +1,7 @@ { "cells": [ { - "cell_type": "markdown", + "cell_type": "raw", "id": "9d9630e1", "metadata": {}, "source": [ @@ -33,13 +33,260 @@ "cell_type": "markdown", "id": "f63ef927", "metadata": {}, - "source": "
\nPseudocode Keyword Reference (click to expand)\n\nAll keywords are **case-sensitive and must be written in ALL CAPS**. Type `<--` for `\u2190`, `!=` for `\u2260`, `>=` for `\u2265`, `<=` for `\u2264`.\n\n
\nVariables & Assignment\n\nUse `\u2190` to assign a value. Variables are created on first assignment. Variable names are case-sensitive.\n\n```\nx \u2190 5\nname \u2190 \"Alice\"\nflag \u2190 TRUE\n```\n\n> Types: numbers, strings (`\"double quotes\"`), `TRUE` / `FALSE`\n\n
\n\n
\nDISPLAY & INPUT\n\n| Command | What it does |\n|---|---|\n| `DISPLAY(value)` | Prints a value to the output box |\n| `INPUT(\"prompt\")` | Prompts the user; auto-converts to number/boolean if possible |\n\n```\nDISPLAY(\"Hello!\")\nage \u2190 INPUT(\"Enter your age: \")\nDISPLAY(age)\n```\n\n
\n\n
\nOperators\n\n**Arithmetic:** `+` `-` `*` `/` `MOD`\n> `+` also concatenates strings\n\n**Comparison:** `=` `\u2260` `<` `>` `\u2264` `\u2265`\n\n**Logical:** `AND` `OR` `NOT`\n\n```\nDISPLAY(10 MOD 3) // 1\nDISPLAY(5 = 5) // TRUE\nDISPLAY(TRUE AND FALSE) // FALSE\nDISPLAY(NOT FALSE) // TRUE\n```\n\n
\n\n
\nIF / ELSE\n\n```\nIF (condition) {\n // runs if TRUE\n} ELSE {\n // runs if FALSE (ELSE block is optional)\n}\n```\n\n```\nx \u2190 7\nIF (x > 5) {\n DISPLAY(\"big\")\n} ELSE {\n DISPLAY(\"small\")\n}\n```\n\n
\n\n
\nLoops\n\n**REPEAT n TIMES**\n```\nREPEAT 5 TIMES {\n DISPLAY(\"hello\")\n}\n```\n\n**REPEAT UNTIL** \u2014 loops until condition is `TRUE`\n```\nx \u2190 0\nREPEAT UNTIL (x = 5) {\n x \u2190 x + 1\n}\n```\n\n**FOR EACH IN** \u2014 iterates over a list\n```\nFOR EACH n IN [1, 2, 3] {\n DISPLAY(n * 2)\n}\n```\n\n
\n\n
\nLists\n\n**1-based indexing** \u2014 first element is at index `1`.\n\n| Command | What it does |\n|---|---|\n| `list[i]` | Get element at index `i` |\n| `list[i] \u2190 value` | Set element at index `i` |\n| `APPEND(list, value)` | Add to end |\n| `INSERT(list, i, value)` | Insert at index `i` |\n| `REMOVE(list, i)` | Remove at index `i` |\n| `LENGTH(list)` | Number of elements |\n\n```\nnums \u2190 [10, 20, 30]\nAPPEND(nums, 40)\nDISPLAY(LENGTH(nums)) // 4\nDISPLAY(nums[1]) // 10\n```\n\n
\n\n
\nPROCEDURE & RETURN\n\n```\nPROCEDURE add(a, b) {\n RETURN a + b\n}\nDISPLAY(add(3, 4)) // 7\n```\n\nProcedures without `RETURN` can still be called for side effects:\n```\nPROCEDURE greet(name) {\n DISPLAY(\"Hello, \" + name)\n}\ngreet(\"Alice\")\n```\n\n
\n\n
\nRobot / Grid Commands\n\nThese activate the visual 7x7 grid. Write setup lines first, then movement logic below.\n\n**Setup** (stripped before execution)\n\n| Command | What it does |\n|---|---|\n| `FROM TILEMAPS IMPORT N` | Load preset map N (1-25) |\n| `SPAWN CHARACTER AT (col, row)` | Place robot at col, row (1-based), facing up |\n| `SPAWN GOAL AT (col, row)` | Place a goal star |\n\n**Movement** (called at runtime)\n\n| Command | What it does |\n|---|---|\n| `MOVE_FORWARD()` | Move one cell forward |\n| `ROTATE_LEFT()` | Turn 90 degrees counter-clockwise |\n| `ROTATE_RIGHT()` | Turn 90 degrees clockwise |\n| `CAN_MOVE(\"direction\")` | TRUE if passable - \"forward\" \"backward\" \"left\" \"right\" |\n\n```\nFROM TILEMAPS IMPORT 12\nSPAWN CHARACTER AT (1,1)\nSPAWN GOAL AT (7,7)\n\nREPEAT UNTIL (CAN_MOVE(\"forward\") = FALSE) {\n MOVE_FORWARD()\n}\nROTATE_RIGHT()\nMOVE_FORWARD()\n```\n\n
\n\n
\nCustom Tilemaps (RENDER)\n\nInstead of loading a preset with `FROM TILEMAPS IMPORT`, define your own 7x7 grid as a variable and pass it to `RENDER()`.\n\n**Rules:**\n- The matrix must be a **list of 7 lists**, each with exactly **7 values**\n- `0` = open cell, `1` = wall\n- The entire assignment must be on **one line**\n- Call `RENDER(variable)` before any movement commands\n\n```\nmyMap \u2190 [[0,0,0,0,0,0,0],[0,1,1,0,0,1,0],[0,0,1,0,0,0,0],[0,0,0,0,1,0,0],[0,1,0,0,1,0,0],[0,1,0,0,0,0,0],[0,0,0,0,0,0,0]]\n\nSPAWN CHARACTER AT (1,1)\nSPAWN GOAL AT (7,7)\n\nRENDER(myMap)\nMOVE_FORWARD()\nROTATE_RIGHT()\nMOVE_FORWARD()\n```\n\n> You can combine both: use `FROM TILEMAPS IMPORT N` to load a preset, then call `RENDER(newMap)` later to swap the grid mid-execution.\n\n
\n\n
" + "source": [ + "
\n", + "Pseudocode Keyword Reference (click to expand)\n", + "\n", + "All keywords are **case-sensitive and must be written in ALL CAPS**. Type `<--` for `←`, `!=` for `≠`, `>=` for `≥`, `<=` for `≤`.\n", + "\n", + "
\n", + "Variables & Assignment\n", + "\n", + "Use `←` to assign a value. Variables are created on first assignment. Variable names are case-sensitive.\n", + "\n", + "```\n", + "x ← 5\n", + "name ← \"Alice\"\n", + "flag ← TRUE\n", + "```\n", + "\n", + "> Types: numbers, strings (`\"double quotes\"`), `TRUE` / `FALSE`\n", + "\n", + "
\n", + "\n", + "
\n", + "DISPLAY & INPUT\n", + "\n", + "| Command | What it does |\n", + "|---|---|\n", + "| `DISPLAY(value)` | Prints a value to the output box |\n", + "| `INPUT(\"prompt\")` | Prompts the user; auto-converts to number/boolean if possible |\n", + "\n", + "```\n", + "DISPLAY(\"Hello!\")\n", + "age ← INPUT(\"Enter your age: \")\n", + "DISPLAY(age)\n", + "```\n", + "\n", + "
\n", + "\n", + "
\n", + "Operators\n", + "\n", + "**Arithmetic:** `+` `-` `*` `/` `MOD`\n", + "> `+` also concatenates strings\n", + "\n", + "**Comparison:** `=` `≠` `<` `>` `≤` `≥`\n", + "\n", + "**Logical:** `AND` `OR` `NOT`\n", + "\n", + "```\n", + "DISPLAY(10 MOD 3) // 1\n", + "DISPLAY(5 = 5) // TRUE\n", + "DISPLAY(TRUE AND FALSE) // FALSE\n", + "DISPLAY(NOT FALSE) // TRUE\n", + "```\n", + "\n", + "
\n", + "\n", + "
\n", + "IF / ELSE\n", + "\n", + "```\n", + "IF (condition) {\n", + " // runs if TRUE\n", + "} ELSE {\n", + " // runs if FALSE (ELSE block is optional)\n", + "}\n", + "```\n", + "\n", + "```\n", + "x ← 7\n", + "IF (x > 5) {\n", + " DISPLAY(\"big\")\n", + "} ELSE {\n", + " DISPLAY(\"small\")\n", + "}\n", + "```\n", + "\n", + "
\n", + "\n", + "
\n", + "Loops\n", + "\n", + "**REPEAT n TIMES**\n", + "```\n", + "REPEAT 5 TIMES {\n", + " DISPLAY(\"hello\")\n", + "}\n", + "```\n", + "\n", + "**REPEAT UNTIL** — loops until condition is `TRUE`\n", + "```\n", + "x ← 0\n", + "REPEAT UNTIL (x = 5) {\n", + " x ← x + 1\n", + "}\n", + "```\n", + "\n", + "**FOR EACH IN** — iterates over a list\n", + "```\n", + "FOR EACH n IN [1, 2, 3] {\n", + " DISPLAY(n * 2)\n", + "}\n", + "```\n", + "\n", + "
\n", + "\n", + "
\n", + "Lists\n", + "\n", + "**1-based indexing** — first element is at index `1`.\n", + "\n", + "| Command | What it does |\n", + "|---|---|\n", + "| `list[i]` | Get element at index `i` |\n", + "| `list[i] ← value` | Set element at index `i` |\n", + "| `APPEND(list, value)` | Add to end |\n", + "| `INSERT(list, i, value)` | Insert at index `i` |\n", + "| `REMOVE(list, i)` | Remove at index `i` |\n", + "| `LENGTH(list)` | Number of elements |\n", + "\n", + "```\n", + "nums ← [10, 20, 30]\n", + "APPEND(nums, 40)\n", + "DISPLAY(LENGTH(nums)) // 4\n", + "DISPLAY(nums[1]) // 10\n", + "```\n", + "\n", + "
\n", + "\n", + "
\n", + "PROCEDURE & RETURN\n", + "\n", + "```\n", + "PROCEDURE add(a, b) {\n", + " RETURN a + b\n", + "}\n", + "DISPLAY(add(3, 4)) // 7\n", + "```\n", + "\n", + "Procedures without `RETURN` can still be called for side effects:\n", + "```\n", + "PROCEDURE greet(name) {\n", + " DISPLAY(\"Hello, \" + name)\n", + "}\n", + "greet(\"Alice\")\n", + "```\n", + "\n", + "
\n", + "\n", + "
\n", + "Robot / Grid Commands\n", + "\n", + "These activate the visual 7x7 grid. Write setup lines first, then movement logic below.\n", + "\n", + "**Setup** (stripped before execution)\n", + "\n", + "| Command | What it does |\n", + "|---|---|\n", + "| `FROM TILEMAPS IMPORT N` | Load preset map N (1-25) |\n", + "| `SPAWN CHARACTER AT (col, row)` | Place robot at col, row (1-based), facing up |\n", + "| `SPAWN GOAL AT (col, row)` | Place a goal star |\n", + "\n", + "**Movement** (called at runtime)\n", + "\n", + "| Command | What it does |\n", + "|---|---|\n", + "| `MOVE_FORWARD()` | Move one cell forward |\n", + "| `ROTATE_LEFT()` | Turn 90 degrees counter-clockwise |\n", + "| `ROTATE_RIGHT()` | Turn 90 degrees clockwise |\n", + "| `CAN_MOVE(\"direction\")` | TRUE if passable - \"forward\" \"backward\" \"left\" \"right\" |\n", + "\n", + "```\n", + "FROM TILEMAPS IMPORT 12\n", + "SPAWN CHARACTER AT (1,1)\n", + "SPAWN GOAL AT (7,7)\n", + "\n", + "REPEAT UNTIL (CAN_MOVE(\"forward\") = FALSE) {\n", + " MOVE_FORWARD()\n", + "}\n", + "ROTATE_RIGHT()\n", + "MOVE_FORWARD()\n", + "```\n", + "\n", + "
\n", + "\n", + "
\n", + "Custom Tilemaps (RENDER)\n", + "\n", + "Instead of loading a preset with `FROM TILEMAPS IMPORT`, define your own 7x7 grid as a variable and pass it to `RENDER()`.\n", + "\n", + "**Rules:**\n", + "- The matrix must be a **list of 7 lists**, each with exactly **7 values**\n", + "- `0` = open cell, `1` = wall\n", + "- The entire assignment must be on **one line**\n", + "- Call `RENDER(variable)` before any movement commands\n", + "\n", + "```\n", + "myMap ← [[0,0,0,0,0,0,0],[0,1,1,0,0,1,0],[0,0,1,0,0,0,0],[0,0,0,0,1,0,0],[0,1,0,0,1,0,0],[0,1,0,0,0,0,0],[0,0,0,0,0,0,0]]\n", + "\n", + "SPAWN CHARACTER AT (1,1)\n", + "SPAWN GOAL AT (7,7)\n", + "\n", + "RENDER(myMap)\n", + "MOVE_FORWARD()\n", + "ROTATE_RIGHT()\n", + "MOVE_FORWARD()\n", + "```\n", + "\n", + "> You can combine both: use `FROM TILEMAPS IMPORT N` to load a preset, then call `RENDER(newMap)` later to swap the grid mid-execution.\n", + "\n", + "
\n", + "\n", + "
" + ] }, { "cell_type": "markdown", "id": "513a92fa", "metadata": {}, - "source": "
\nTilemap Directory \u2014 IDs 1\u201325 (click to expand)\n\nUse these IDs with `from tilemaps import N`. All maps are 7\u00d77, 0 = open, 1 = wall.\n\n| ID | Name | Description |\n|---|---|---|\n| 1 | Scattered walls | Open grid with a few wall clusters \u2014 good starter map |\n| 2 | Column gaps | Vertical wall pairs with clear corridors between them |\n| 3 | Double gate | Two horizontal barriers each with a single opening in the centre |\n| 4 | Staggered columns | Alternating column walls; open row in the middle connects them |\n| 5 | Ring | Solid 5\u00d75 wall ring with an open interior and outer path |\n| 6 | Diamond obstacles | Symmetric diagonal obstacles around a centre wall |\n| 7 | Cross barrier | Plus-sign wall with a single gap on each axis |\n| 8 | Dot grid | Regular 2\u00d72 wall dots across the grid \u2014 many equal paths |\n| 9 | S-curve | Single-width path: left \u2192 down \u2192 right \u2192 down |\n| 10 | T-junction | Open top row splits into two shafts that merge to a single exit |\n| 11 | Two rooms | Wall divides the grid; one corridor connects the rooms at row 4 |\n| 12 | Zigzag slalom | Barriers alternate sides \u2014 forces full end-to-end traversal |\n| 13 | Diagonal obstacles | Diagonal line of single-cell walls; open space on both sides |\n| 14 | Slalom barriers | Two staggered barriers each with one opening \u2014 weave through |\n| 15 | Winding river | Narrow single-width path snaking from top-left to bottom-right |\n| 16 | Cross open | Plus-sign open area in the centre; corners are walled off |\n| 17 | Perimeter loop | Outer ring is fully open; solid 5\u00d75 block in the interior |\n| 18 | Grid maze | Open intersections with wall segments \u2014 multiple valid routes |\n| 19 | Columns | Tall wall columns with one open row in the middle |\n| 20 | Honeycomb | Staggered single-cell obstacles; lots of routing options |\n| 21 | Staircase | 2-wide diagonal path from top-left to bottom-right |\n| 22 | Scattered obstacles | Mostly open with light random single-cell walls |\n| 23 | L-corridor | Left column + bottom row form an L-shaped path |\n| 24 | Double loop | Four 2\u00d72 wall blocks leave open rings and a centre cross |\n| 25 | Funnel | Wide open top narrows to a single-column corridor at the bottom |\n\n
" + "source": [ + "
\n", + "Tilemap Directory — IDs 1–25 (click to expand)\n", + "\n", + "Use these IDs with `from tilemaps import N`. All maps are 7×7, 0 = open, 1 = wall.\n", + "\n", + "| ID | Name | Description |\n", + "|---|---|---|\n", + "| 1 | Scattered walls | Open grid with a few wall clusters — good starter map |\n", + "| 2 | Column gaps | Vertical wall pairs with clear corridors between them |\n", + "| 3 | Double gate | Two horizontal barriers each with a single opening in the centre |\n", + "| 4 | Staggered columns | Alternating column walls; open row in the middle connects them |\n", + "| 5 | Ring | Solid 5×5 wall ring with an open interior and outer path |\n", + "| 6 | Diamond obstacles | Symmetric diagonal obstacles around a centre wall |\n", + "| 7 | Cross barrier | Plus-sign wall with a single gap on each axis |\n", + "| 8 | Dot grid | Regular 2×2 wall dots across the grid — many equal paths |\n", + "| 9 | S-curve | Single-width path: left → down → right → down |\n", + "| 10 | T-junction | Open top row splits into two shafts that merge to a single exit |\n", + "| 11 | Two rooms | Wall divides the grid; one corridor connects the rooms at row 4 |\n", + "| 12 | Zigzag slalom | Barriers alternate sides — forces full end-to-end traversal |\n", + "| 13 | Diagonal obstacles | Diagonal line of single-cell walls; open space on both sides |\n", + "| 14 | Slalom barriers | Two staggered barriers each with one opening — weave through |\n", + "| 15 | Winding river | Narrow single-width path snaking from top-left to bottom-right |\n", + "| 16 | Cross open | Plus-sign open area in the centre; corners are walled off |\n", + "| 17 | Perimeter loop | Outer ring is fully open; solid 5×5 block in the interior |\n", + "| 18 | Grid maze | Open intersections with wall segments — multiple valid routes |\n", + "| 19 | Columns | Tall wall columns with one open row in the middle |\n", + "| 20 | Honeycomb | Staggered single-cell obstacles; lots of routing options |\n", + "| 21 | Staircase | 2-wide diagonal path from top-left to bottom-right |\n", + "| 22 | Scattered obstacles | Mostly open with light random single-cell walls |\n", + "| 23 | L-corridor | Left column + bottom row form an L-shaped path |\n", + "| 24 | Double loop | Four 2×2 wall blocks leave open rings and a centre cross |\n", + "| 25 | Funnel | Wide open top narrows to a single-column corridor at the bottom |\n", + "\n", + "
" + ] }, { "cell_type": "markdown", @@ -58,4 +305,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} \ No newline at end of file +} From e16220904ba188a8d00100cb5076ab16446a6d0c Mon Sep 17 00:00:00 2001 From: samanviy17-crypto Date: Thu, 17 Sep 2026 12:22:35 -0700 Subject: [PATCH 39/43] Revert Makefile --- Makefile | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 862b40724b..e7aefd2a0c 100644 --- a/Makefile +++ b/Makefile @@ -25,7 +25,6 @@ DEV_PROJECTS := $(shell grep -v '^\#' $(PROJECT_FILE) 2>/dev/null | grep -v '^$$ # Known top-level targets (add to this if needed) KNOWN_TARGETS := \ default dev serve build clean stop reload refresh help \ - serve-current build-current \ serve-minima serve-cayman serve-yat serve-so-simple serve-hydejack \ build-minima build-cayman build-yat build-so-simple \ convert convert-docx convert-docx-config convert-single convert-registered-notebooks \ @@ -275,11 +274,11 @@ build: build-current # Multi-course file splitting split-courses: @echo " ------ Splitting multi-course files... -------" - @$(PYTHON) scripts/split_multi_course_files.py + @python3 scripts/split_multi_course_files.py clean-courses: @echo "🧹Cleaning course-specific files..." - @$(PYTHON) scripts/split_multi_course_files.py clean + @python3 scripts/split_multi_course_files.py clean # Notebook and DOCX conversion convert: $(MARKDOWN_FILES) convert-docx From fc0867051764d4068e3f2ad2416c7bda48558080 Mon Sep 17 00:00:00 2001 From: Nathan Trieu Date: Thu, 17 Sep 2026 13:29:29 -0700 Subject: [PATCH 40/43] Add Python nested conditionals lesson --- ...ers_nested_conditionals_lesson_IPYNB_2_.md | 225 ----------- ...-17-nested-conditionals-python_IPYNB_2_.md | 200 ++++++++++ ...demaxxers_nested_conditionals_lesson.ipynb | 353 ------------------ ...026-09-17-nested-conditionals-python.ipynb | 288 ++++++++++++++ 4 files changed, 488 insertions(+), 578 deletions(-) delete mode 100644 _notebooks/2025-09-26-codemaxxers_nested_conditionals_lesson_IPYNB_2_.md create mode 100644 _notebooks/2026-09-17-nested-conditionals-python_IPYNB_2_.md delete mode 100644 _projects/lessons/python/notebooks/2025-09-26-codemaxxers_nested_conditionals_lesson.ipynb create mode 100644 _projects/lessons/python/notebooks/2026-09-17-nested-conditionals-python.ipynb diff --git a/_notebooks/2025-09-26-codemaxxers_nested_conditionals_lesson_IPYNB_2_.md b/_notebooks/2025-09-26-codemaxxers_nested_conditionals_lesson_IPYNB_2_.md deleted file mode 100644 index 65f9d6eba5..0000000000 --- a/_notebooks/2025-09-26-codemaxxers_nested_conditionals_lesson_IPYNB_2_.md +++ /dev/null @@ -1,225 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Nested-Conditionals'] -lesson_language: Python -lesson_topic: Nested-Conditionals -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.7 Nested Conditionals -description: Explore how to use nested conditionals in JavaScript and Python to make complex, hierarchical decisions in code. -permalink: /csp/codemaxxers/nested-conditionals-lesson ---- - -# Nested Conditionals Lesson - -## What are Nested Conditionals? - -Nested conditionals are **conditionals within conditionals**. They allow us to check multiple conditions in a hierarchical way, where the result of one condition determines which other conditions we check next. - -## Pseudocode Structure - -Here's the basic structure of nested conditionals: - -``` -if (condition) { - if (condition) { - // code - } else { - // code - } -} else { - if (condition) { - // code - } else { - // code - } -} -``` - -In this structure, we check an initial condition. Depending on whether it's true or false, we move to one segment of code and check another conditional. **Going down one path means you do not go down another.** - -## Example 1: Game Level Completion - -Let's look at a real-world example. Imagine we're playing a game that checks if we've completed a level by satisfying two requirements: -- **TIME** is less than 3 seconds -- **SCORE** is greater than 1000 - -If both conditions are met, we add 3 lives and increase the level. - - -```javascript -%%js -// Initial game state -let score = 1200; -let time = 2.5; -let level = 2; -let lives = 3; - -console.log(`Starting state: Score=${score}, Time=${time}, Level=${level}, Lives=${lives}`); - -// Simple condition (not complete yet) -if (time < 3 && score > 1000) { - lives = lives + 3; - level = level + 1; - console.log("Both conditions met! +3 lives, +1 level"); -} - -console.log(`Final state: Score=${score}, Time=${time}, Level=${level}, Lives=${lives}`); -``` - -### Problem: What if the conditions aren't met? - -The above code doesn't tell the game what to do if: -- Only one condition is met -- Neither condition is met - -Let's fix this with **nested conditionals**! - -## Complete Nested Conditional Example - - -```javascript -%%js -// Initial game state -let score = 1200; -let time = 4.2; -let level = 2; -let lives = 3; - -console.log(`Starting state: Score=${score}, Time=${time}, Level=${level}, Lives=${lives}`); - -// Complete nested conditional -if (time < 3 && score > 1000) { - // Both conditions met - lives = lives + 3; - level = level + 1; - console.log("Both conditions met! +3 lives, +1 level"); -} else { - // At least one condition was NOT met - if (time < 3 || score > 1000) { - // At least one condition is met - lives = lives + 1; - console.log("One condition met! +1 life"); - } else { - // Neither condition is met - lives = lives - 1; - console.log("No conditions met! -1 life"); - } -} - -console.log(`Final state: Score=${score}, Time=${time}, Level=${level}, Lives=${lives}`); -``` - -### 🤔 Prediction Exercise - -Before you ran the code above, what did you predict would happen? - -**Answer:** Since `time = 4.2` (NOT less than 3) and `score = 1200` (IS greater than 1000), only ONE condition is met. So we take the `else` branch, then the inner `if` branch is true, giving us +1 life. The player ends with 4 lives and stays at level 2. - -## Example 2: Temperature and Weather Advisory System - -Let's look at another real-world application: a weather advisory system that gives recommendations based on temperature and whether it's raining. - - -```javascript -%%js -let temperature = 85; -let isRaining = false; - -console.log(`Current conditions: ${temperature}°F, Raining: ${isRaining}`); -console.log("\nWeather Advisory:"); - -if (temperature > 80) { - // It's hot - if (isRaining) { - console.log("It's hot and rainy - stay hydrated and bring an umbrella!"); - } else { - console.log("It's hot and sunny - wear sunscreen and stay hydrated!"); - } -} else { - // It's not hot - if (isRaining) { - console.log("It's cool and rainy - bring a jacket and umbrella!"); - } else { - console.log("It's cool and clear - perfect weather for outdoor activities!"); - } -} -``` - -## Try It Yourself! - -Modify the temperature and `isRaining` values in the cell above and run it again to see different advisories. - -## Example 3: Student Grade Calculator - -Here's a more complex example that determines a student's grade and eligibility for honors based on their test score and homework completion. - - -```javascript -%%js -let testScore = 88; -let homeworkCompleted = 0.95; // 95% of homework completed - -console.log(`Test Score: ${testScore}`); -console.log(`Homework Completion: ${homeworkCompleted * 100}%`); -console.log("\nGrade Evaluation:"); - -if (testScore >= 90) { - // A grade territory - if (homeworkCompleted >= 0.9) { - console.log("Grade: A"); - console.log("Status: Honors eligible! Excellent work!"); - } else { - console.log("Grade: A"); - console.log("Status: Great test score, but complete more homework for honors."); - } -} else { - // Below A grade - if (testScore >= 80) { - // B grade territory - if (homeworkCompleted >= 0.9) { - console.log("Grade: B+"); - console.log("Status: Good work! A little more effort on tests for honors."); - } else { - console.log("Grade: B"); - console.log("Status: Solid performance. Focus on homework completion."); - } - } else { - // Below B grade - console.log("Grade: C or below"); - console.log("Status: Let's meet to discuss how to improve your grade."); - } -} -``` - -## 🎯 Quick Check: Test Your Understanding - -What would happen in the grade calculator if: -1. `testScore = 92` and `homeworkCompleted = 0.85`? -2. `testScore = 85` and `homeworkCompleted = 0.95`? -3. `testScore = 75` and `homeworkCompleted = 0.80`? - -Try changing the values above and running the code to check your predictions! - -## Real-World Applications - -Nested conditionals are used everywhere in programming: - -1. **Video Games**: Checking player state, inventory, and abilities -2. **E-commerce**: Determining shipping costs, discounts, and eligibility -3. **Social Media**: Filtering content based on user preferences and privacy settings -4. **Banking Apps**: Validating transactions based on balance, limits, and security checks -5. **Fitness Apps**: Providing workout recommendations based on fitness level and goals - -The key is that nested conditionals let you make **hierarchical decisions** where one choice determines what other choices you need to make next. - -## Summary - -- **Nested conditionals** are conditionals inside other conditionals -- They allow us to create complex decision-making logic -- Each path through the nested structure is exclusive - you only go down one path -- Use nested conditionals when the conditions you need to check depend on previous conditions -- Remember to handle all possible cases (including edge cases!) diff --git a/_notebooks/2026-09-17-nested-conditionals-python_IPYNB_2_.md b/_notebooks/2026-09-17-nested-conditionals-python_IPYNB_2_.md new file mode 100644 index 0000000000..0529ec46e2 --- /dev/null +++ b/_notebooks/2026-09-17-nested-conditionals-python_IPYNB_2_.md @@ -0,0 +1,200 @@ +--- +layout: post +categories: [Python, Nested-Conditionals] +lesson_language: Python +lesson_topic: Nested-Conditionals +lesson_part: interactive +lesson_type: lesson +codemirror: true +microblog: true +toc: false +comments: false +title: 3.7 Nested Conditionals (PY) +description: Learn nested conditionals in Python using the five-part LxD lesson format. +permalink: /python/nested-conditionals/py +--- + +# 3.7 Nested Conditionals in Python + +A **nested conditional** is an `if` statement inside another `if`, `elif`, or `else` block. The outer decision chooses a path first, and the inner decision checks a more specific condition inside that path. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms. + +## 1. LxD Cycle Process + +**Empathize:** Nested conditionals can be confusing because indentation changes which decision owns an inner branch, and students may check a detail before confirming that the larger condition applies. + +**Define:** +- **POV:** CSP students need a clear way to trace decisions from the outside in so they can build programs with multiple levels of rules. +- **Learning Goal:** Students will be able to trace, write, test, and explain nested conditionals in Python. + +**Ideate:** +- **HMW Question:** How might we make each path through a nested conditional visible before students write a larger program? +- **Activity:** Trace an outer and inner decision, fix incorrect indentation, translate nested logic, and build a two-level decision checker. + +**Prototype & Test:** Use the Popcorn Hacks below to check whether students can identify the path a program follows, place an inner condition in the correct block, and test every meaningful outcome. + +--- + +## 2. Lesson Plan + +**Learning Objective:** By the end of this lesson, you will be able to use nested `if` statements in Python when a second decision should happen only after a first condition selects a path. + +**Success Criteria:** You can trace a nested conditional, explain how indentation controls its branches, write a two-level decision, and test all of its possible paths. + +### Tech Talk 1: Decisions Inside Decisions + +The outer condition is checked first. The inner condition is reached only when execution enters the block that contains it. + +```python +has_account = True +password_correct = False + +if has_account: + if password_correct: + print("Login approved") + else: + print("Incorrect password") +else: + print("Create an account first") +``` + +Python checks `has_account` before it checks `password_correct`. If `has_account` is `False`, the password condition is skipped because it belongs inside the first branch. + +### Tech Talk 2: Indentation Shows the Structure + +Python uses indentation to show which statements belong together. Each nested level is indented one additional level. + +```python +assignment_submitted = True +submitted_on_time = True + +if assignment_submitted: + if submitted_on_time: + print("Submitted on time") + else: + print("Submitted late") +else: + print("Assignment missing") +``` + +This example has three possible paths, but only one message prints during a run. Moving the inner `else` to the wrong indentation level would change which `if` statement it belongs to. + +### Tech Talk 3: Nested and Compound Conditions Are Different + +A compound condition checks multiple Boolean expressions at the same time. A nested conditional makes the second check depend on the first path. + +| Purpose | Python example | +| --- | --- | +| Both rules must be true for one result | `if has_ticket and has_id:` | +| Check a detail only after entering a path | `if has_ticket:` then nested `if has_id:` | + +The same nested structure appears in three forms: + +| Form | Outer and inner decision | +| --- | --- | +| Python | `if condition_a:` then indented `if condition_b:` | +| JavaScript | `if (conditionA) { if (conditionB) { ... } }` | +| College Board pseudocode | `IF(conditionA) { IF(conditionB) { ... } }` | + +--- + +## 3. Popcorn Hacks & Practice Tasks + +### Popcorn Hack 1: Trace the Path + +Predict the output before running the code. + +```python +is_weekday = True +homework_finished = False + +if is_weekday: + if homework_finished: + print("Free time") + else: + print("Finish homework") +else: + print("Weekend plan") +``` + +Do these three things: +1. Write the message that will print. +2. Name the outer branch and inner branch the program follows. +3. Change the values to reach each of the other two outcomes. + +### Popcorn Hack 2: Fix the Indentation + +The program should check `has_permission` only when the user is logged in, but the inner decision is not indented correctly. + +```python +logged_in = True +has_permission = False + +if logged_in: + print("Account found") +if has_permission: + print("Page opened") +else: + print("Permission needed") +``` + +Do these four things: +1. Explain why the current code is not nested. +2. Move the permission check inside the logged-in branch. +3. Add an outer `else` that prints `Log in first`. +4. Test all three possible messages. + +### Popcorn Hack 3: Translate the Structure + +Start with this Python nested conditional: + +```python +if club_member: + if meeting_today: + print("Go to the meeting") + else: + print("Check the next meeting date") +else: + print("Join the club first") +``` + +Write the same structure in JavaScript and College Board pseudocode. Then explain which condition is checked first and when `meeting_today` is skipped. + +### Popcorn Hack 4: Two-Level Event Checker + +Build a Python program for a school event. First check whether registration is complete. Only registered students should then be checked for a digital or printed pass. + +Your program must: +1. use one outer `if` / `else`, +2. place an inner `if` / `else` inside the registered branch, +3. produce at least three distinct outcomes, +4. test one input for every outcome, +5. include 2–3 sentences explaining why the second check is nested. + +```python +registered = True +has_pass = False + +# Replace this comment with your nested conditional. +``` + +--- + +## 4. Grading Plan (1 Point Total) + +| Activity | Points | What earns the points | +| --- | ---: | --- | +| Popcorn Hack 1 | 0.2 | Correctly predict the path and change the values to reach all outcomes. | +| Popcorn Hack 2 | 0.2 | Correctly nest the permission check, add the outer `else`, and test all outcomes. | +| Popcorn Hack 3 | 0.2 | Correctly translate the structure into JavaScript and College Board pseudocode and explain the execution order. | +| Popcorn Hack 4 | 0.4 | Build a working two-level event checker, test every outcome, and explain why the inner decision depends on the outer branch. | +| **Total** | **1.0** | | + +--- + +## 5. Lesson Revisions & Feedback Evidence + +- The lesson is organized into the same numbered `1` through `5` structure used by the Boolean Expressions and Random Values lessons. +- Activity names use **Tech Talk** for instruction and **Popcorn Hack** for practice tasks. +- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids. +- The examples progress from tracing one path to building and testing a complete two-level decision. +- Feedback from a practice run can be added here with the specific change that was made because of it. diff --git a/_projects/lessons/python/notebooks/2025-09-26-codemaxxers_nested_conditionals_lesson.ipynb b/_projects/lessons/python/notebooks/2025-09-26-codemaxxers_nested_conditionals_lesson.ipynb deleted file mode 100644 index 8b12a0dfa4..0000000000 --- a/_projects/lessons/python/notebooks/2025-09-26-codemaxxers_nested_conditionals_lesson.ipynb +++ /dev/null @@ -1,353 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": { - "vscode": { - "languageId": "raw" - } - }, - "source": [ - "---\n", - "layout: post\n", - "categories: [Python, Nested-Conditionals]\n", - "lesson_language: Python\n", - "lesson_topic: Nested-Conditionals\n", - "lesson_part: interactive\n", - "lesson_type: lesson\n", - "codemirror: true\n", - "microblog: true\n", - "toc: false\n", - "comments: false\n", - "title: \"3.7 Nested Conditionals\"\n", - "description: \"Explore how to use nested conditionals in JavaScript and Python to make complex, hierarchical decisions in code.\"\n", - "permalink: /csp/codemaxxers/nested-conditionals-lesson\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# Nested Conditionals Lesson\n", - "\n", - "## What are Nested Conditionals?\n", - "\n", - "Nested conditionals are **conditionals within conditionals**. They allow us to check multiple conditions in a hierarchical way, where the result of one condition determines which other conditions we check next." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Pseudocode Structure\n", - "\n", - "Here's the basic structure of nested conditionals:\n", - "\n", - "```\n", - "if (condition) {\n", - " if (condition) {\n", - " // code\n", - " } else {\n", - " // code\n", - " }\n", - "} else {\n", - " if (condition) {\n", - " // code\n", - " } else {\n", - " // code\n", - " }\n", - "}\n", - "```\n", - "\n", - "In this structure, we check an initial condition. Depending on whether it's true or false, we move to one segment of code and check another conditional. **Going down one path means you do not go down another.**" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Example 1: Game Level Completion\n", - "\n", - "Let's look at a real-world example. Imagine we're playing a game that checks if we've completed a level by satisfying two requirements:\n", - "- **TIME** is less than 3 seconds\n", - "- **SCORE** is greater than 1000\n", - "\n", - "If both conditions are met, we add 3 lives and increase the level." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "// Initial game state\n", - "let score = 1200;\n", - "let time = 2.5;\n", - "let level = 2;\n", - "let lives = 3;\n", - "\n", - "console.log(`Starting state: Score=${score}, Time=${time}, Level=${level}, Lives=${lives}`);\n", - "\n", - "// Simple condition (not complete yet)\n", - "if (time < 3 && score > 1000) {\n", - " lives = lives + 3;\n", - " level = level + 1;\n", - " console.log(\"Both conditions met! +3 lives, +1 level\");\n", - "}\n", - "\n", - "console.log(`Final state: Score=${score}, Time=${time}, Level=${level}, Lives=${lives}`);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Problem: What if the conditions aren't met?\n", - "\n", - "The above code doesn't tell the game what to do if:\n", - "- Only one condition is met\n", - "- Neither condition is met\n", - "\n", - "Let's fix this with **nested conditionals**!" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Complete Nested Conditional Example" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "// Initial game state\n", - "let score = 1200;\n", - "let time = 4.2;\n", - "let level = 2;\n", - "let lives = 3;\n", - "\n", - "console.log(`Starting state: Score=${score}, Time=${time}, Level=${level}, Lives=${lives}`);\n", - "\n", - "// Complete nested conditional\n", - "if (time < 3 && score > 1000) {\n", - " // Both conditions met\n", - " lives = lives + 3;\n", - " level = level + 1;\n", - " console.log(\"Both conditions met! +3 lives, +1 level\");\n", - "} else {\n", - " // At least one condition was NOT met\n", - " if (time < 3 || score > 1000) {\n", - " // At least one condition is met\n", - " lives = lives + 1;\n", - " console.log(\"One condition met! +1 life\");\n", - " } else {\n", - " // Neither condition is met\n", - " lives = lives - 1;\n", - " console.log(\"No conditions met! -1 life\");\n", - " }\n", - "}\n", - "\n", - "console.log(`Final state: Score=${score}, Time=${time}, Level=${level}, Lives=${lives}`);" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### 🤔 Prediction Exercise\n", - "\n", - "Before you ran the code above, what did you predict would happen?\n", - "\n", - "**Answer:** Since `time = 4.2` (NOT less than 3) and `score = 1200` (IS greater than 1000), only ONE condition is met. So we take the `else` branch, then the inner `if` branch is true, giving us +1 life. The player ends with 4 lives and stays at level 2." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Example 2: Temperature and Weather Advisory System\n", - "\n", - "Let's look at another real-world application: a weather advisory system that gives recommendations based on temperature and whether it's raining." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "let temperature = 85;\n", - "let isRaining = false;\n", - "\n", - "console.log(`Current conditions: ${temperature}°F, Raining: ${isRaining}`);\n", - "console.log(\"\\nWeather Advisory:\");\n", - "\n", - "if (temperature > 80) {\n", - " // It's hot\n", - " if (isRaining) {\n", - " console.log(\"It's hot and rainy - stay hydrated and bring an umbrella!\");\n", - " } else {\n", - " console.log(\"It's hot and sunny - wear sunscreen and stay hydrated!\");\n", - " }\n", - "} else {\n", - " // It's not hot\n", - " if (isRaining) {\n", - " console.log(\"It's cool and rainy - bring a jacket and umbrella!\");\n", - " } else {\n", - " console.log(\"It's cool and clear - perfect weather for outdoor activities!\");\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Try It Yourself!\n", - "\n", - "Modify the temperature and `isRaining` values in the cell above and run it again to see different advisories." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Example 3: Student Grade Calculator\n", - "\n", - "Here's a more complex example that determines a student's grade and eligibility for honors based on their test score and homework completion." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "vscode": { - "languageId": "javascript" - } - }, - "outputs": [], - "source": [ - "%%js\n", - "let testScore = 88;\n", - "let homeworkCompleted = 0.95; // 95% of homework completed\n", - "\n", - "console.log(`Test Score: ${testScore}`);\n", - "console.log(`Homework Completion: ${homeworkCompleted * 100}%`);\n", - "console.log(\"\\nGrade Evaluation:\");\n", - "\n", - "if (testScore >= 90) {\n", - " // A grade territory\n", - " if (homeworkCompleted >= 0.9) {\n", - " console.log(\"Grade: A\");\n", - " console.log(\"Status: Honors eligible! Excellent work!\");\n", - " } else {\n", - " console.log(\"Grade: A\");\n", - " console.log(\"Status: Great test score, but complete more homework for honors.\");\n", - " }\n", - "} else {\n", - " // Below A grade\n", - " if (testScore >= 80) {\n", - " // B grade territory\n", - " if (homeworkCompleted >= 0.9) {\n", - " console.log(\"Grade: B+\");\n", - " console.log(\"Status: Good work! A little more effort on tests for honors.\");\n", - " } else {\n", - " console.log(\"Grade: B\");\n", - " console.log(\"Status: Solid performance. Focus on homework completion.\");\n", - " }\n", - " } else {\n", - " // Below B grade\n", - " console.log(\"Grade: C or below\");\n", - " console.log(\"Status: Let's meet to discuss how to improve your grade.\");\n", - " }\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 🎯 Quick Check: Test Your Understanding\n", - "\n", - "What would happen in the grade calculator if:\n", - "1. `testScore = 92` and `homeworkCompleted = 0.85`?\n", - "2. `testScore = 85` and `homeworkCompleted = 0.95`?\n", - "3. `testScore = 75` and `homeworkCompleted = 0.80`?\n", - "\n", - "Try changing the values above and running the code to check your predictions!" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Real-World Applications\n", - "\n", - "Nested conditionals are used everywhere in programming:\n", - "\n", - "1. **Video Games**: Checking player state, inventory, and abilities\n", - "2. **E-commerce**: Determining shipping costs, discounts, and eligibility\n", - "3. **Social Media**: Filtering content based on user preferences and privacy settings\n", - "4. **Banking Apps**: Validating transactions based on balance, limits, and security checks\n", - "5. **Fitness Apps**: Providing workout recommendations based on fitness level and goals\n", - "\n", - "The key is that nested conditionals let you make **hierarchical decisions** where one choice determines what other choices you need to make next." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Summary\n", - "\n", - "- **Nested conditionals** are conditionals inside other conditionals\n", - "- They allow us to create complex decision-making logic\n", - "- Each path through the nested structure is exclusive - you only go down one path\n", - "- Use nested conditionals when the conditions you need to check depend on previous conditions\n", - "- Remember to handle all possible cases (including edge cases!)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.8.0" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/_projects/lessons/python/notebooks/2026-09-17-nested-conditionals-python.ipynb b/_projects/lessons/python/notebooks/2026-09-17-nested-conditionals-python.ipynb new file mode 100644 index 0000000000..c553a8a263 --- /dev/null +++ b/_projects/lessons/python/notebooks/2026-09-17-nested-conditionals-python.ipynb @@ -0,0 +1,288 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "---\n", + "layout: post\n", + "categories: [Python, Nested-Conditionals]\n", + "lesson_language: Python\n", + "lesson_topic: Nested-Conditionals\n", + "lesson_part: interactive\n", + "lesson_type: lesson\n", + "codemirror: true\n", + "microblog: true\n", + "toc: false\n", + "comments: false\n", + "title: 3.7 Nested Conditionals (PY)\n", + "description: Learn nested conditionals in Python using the five-part LxD lesson format.\n", + "permalink: /python/nested-conditionals/py\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 3.7 Nested Conditionals in Python\n", + "\n", + "A **nested conditional** is an `if` statement inside another `if`, `elif`, or `else` block. The outer decision chooses a path first, and the inner decision checks a more specific condition inside that path. Python is the main language for this lesson. JavaScript and College Board pseudocode are only used to compare the same idea in different forms.\n", + "\n", + "## 1. LxD Cycle Process\n", + "\n", + "**Empathize:** Nested conditionals can be confusing because indentation changes which decision owns an inner branch, and students may check a detail before confirming that the larger condition applies.\n", + "\n", + "**Define:**\n", + "- **POV:** CSP students need a clear way to trace decisions from the outside in so they can build programs with multiple levels of rules.\n", + "- **Learning Goal:** Students will be able to trace, write, test, and explain nested conditionals in Python.\n", + "\n", + "**Ideate:**\n", + "- **HMW Question:** How might we make each path through a nested conditional visible before students write a larger program?\n", + "- **Activity:** Trace an outer and inner decision, fix incorrect indentation, translate nested logic, and build a two-level decision checker.\n", + "\n", + "**Prototype & Test:** Use the Popcorn Hacks below to check whether students can identify the path a program follows, place an inner condition in the correct block, and test every meaningful outcome.\n", + "\n", + "---\n", + "\n", + "## 2. Lesson Plan\n", + "\n", + "**Learning Objective:** By the end of this lesson, you will be able to use nested `if` statements in Python when a second decision should happen only after a first condition selects a path.\n", + "\n", + "**Success Criteria:** You can trace a nested conditional, explain how indentation controls its branches, write a two-level decision, and test all of its possible paths.\n", + "\n", + "### Tech Talk 1: Decisions Inside Decisions\n", + "\n", + "The outer condition is checked first. The inner condition is reached only when execution enters the block that contains it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "has_account = True\n", + "password_correct = False\n", + "\n", + "if has_account:\n", + " if password_correct:\n", + " print(\"Login approved\")\n", + " else:\n", + " print(\"Incorrect password\")\n", + "else:\n", + " print(\"Create an account first\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Python checks `has_account` before it checks `password_correct`. If `has_account` is `False`, the password condition is skipped because it belongs inside the first branch.\n", + "\n", + "### Tech Talk 2: Indentation Shows the Structure\n", + "\n", + "Python uses indentation to show which statements belong together. Each nested level is indented one additional level." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "assignment_submitted = True\n", + "submitted_on_time = True\n", + "\n", + "if assignment_submitted:\n", + " if submitted_on_time:\n", + " print(\"Submitted on time\")\n", + " else:\n", + " print(\"Submitted late\")\n", + "else:\n", + " print(\"Assignment missing\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This example has three possible paths, but only one message prints during a run. Moving the inner `else` to the wrong indentation level would change which `if` statement it belongs to.\n", + "\n", + "### Tech Talk 3: Nested and Compound Conditions Are Different\n", + "\n", + "A compound condition checks multiple Boolean expressions at the same time. A nested conditional makes the second check depend on the first path.\n", + "\n", + "| Purpose | Python example |\n", + "| --- | --- |\n", + "| Both rules must be true for one result | `if has_ticket and has_id:` |\n", + "| Check a detail only after entering a path | `if has_ticket:` then nested `if has_id:` |\n", + "\n", + "The same nested structure appears in three forms:\n", + "\n", + "| Form | Outer and inner decision |\n", + "| --- | --- |\n", + "| Python | `if condition_a:` then indented `if condition_b:` |\n", + "| JavaScript | `if (conditionA) { if (conditionB) { ... } }` |\n", + "| College Board pseudocode | `IF(conditionA) { IF(conditionB) { ... } }` |\n", + "\n", + "---\n", + "\n", + "## 3. Popcorn Hacks & Practice Tasks\n", + "\n", + "### Popcorn Hack 1: Trace the Path\n", + "\n", + "Predict the output before running the code." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "is_weekday = True\n", + "homework_finished = False\n", + "\n", + "if is_weekday:\n", + " if homework_finished:\n", + " print(\"Free time\")\n", + " else:\n", + " print(\"Finish homework\")\n", + "else:\n", + " print(\"Weekend plan\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Do these three things:\n", + "1. Write the message that will print.\n", + "2. Name the outer branch and inner branch the program follows.\n", + "3. Change the values to reach each of the other two outcomes.\n", + "\n", + "### Popcorn Hack 2: Fix the Indentation\n", + "\n", + "The program should check `has_permission` only when the user is logged in, but the inner decision is not indented correctly." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "logged_in = True\n", + "has_permission = False\n", + "\n", + "if logged_in:\n", + " print(\"Account found\")\n", + "if has_permission:\n", + " print(\"Page opened\")\n", + "else:\n", + " print(\"Permission needed\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Do these four things:\n", + "1. Explain why the current code is not nested.\n", + "2. Move the permission check inside the logged-in branch.\n", + "3. Add an outer `else` that prints `Log in first`.\n", + "4. Test all three possible messages.\n", + "\n", + "### Popcorn Hack 3: Translate the Structure\n", + "\n", + "Start with this Python nested conditional:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "if club_member:\n", + " if meeting_today:\n", + " print(\"Go to the meeting\")\n", + " else:\n", + " print(\"Check the next meeting date\")\n", + "else:\n", + " print(\"Join the club first\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Write the same structure in JavaScript and College Board pseudocode. Then explain which condition is checked first and when `meeting_today` is skipped.\n", + "\n", + "### Popcorn Hack 4: Two-Level Event Checker\n", + "\n", + "Build a Python program for a school event. First check whether registration is complete. Only registered students should then be checked for a digital or printed pass.\n", + "\n", + "Your program must:\n", + "1. use one outer `if` / `else`,\n", + "2. place an inner `if` / `else` inside the registered branch,\n", + "3. produce at least three distinct outcomes,\n", + "4. test one input for every outcome,\n", + "5. include 2–3 sentences explaining why the second check is nested." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "registered = True\n", + "has_pass = False\n", + "\n", + "# Replace this comment with your nested conditional." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "---\n", + "\n", + "## 4. Grading Plan (1 Point Total)\n", + "\n", + "| Activity | Points | What earns the points |\n", + "| --- | ---: | --- |\n", + "| Popcorn Hack 1 | 0.2 | Correctly predict the path and change the values to reach all outcomes. |\n", + "| Popcorn Hack 2 | 0.2 | Correctly nest the permission check, add the outer `else`, and test all outcomes. |\n", + "| Popcorn Hack 3 | 0.2 | Correctly translate the structure into JavaScript and College Board pseudocode and explain the execution order. |\n", + "| Popcorn Hack 4 | 0.4 | Build a working two-level event checker, test every outcome, and explain why the inner decision depends on the outer branch. |\n", + "| **Total** | **1.0** | |\n", + "\n", + "---\n", + "\n", + "## 5. Lesson Revisions & Feedback Evidence\n", + "\n", + "- The lesson is organized into the same numbered `1` through `5` structure used by the Boolean Expressions and Random Values lessons.\n", + "- Activity names use **Tech Talk** for instruction and **Popcorn Hack** for practice tasks.\n", + "- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n", + "- The examples progress from tracing one path to building and testing a complete two-level decision.\n", + "- Feedback from a practice run can be added here with the specific change that was made because of it." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3.8.0" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} From 01b8d7ffbc4295d76285479d47ff83eb17861f03 Mon Sep 17 00:00:00 2001 From: Nathan Trieu Date: Thu, 17 Sep 2026 13:40:10 -0700 Subject: [PATCH 41/43] Align nested conditionals lesson with LxD format --- ...-17-nested-conditionals-python_IPYNB_2_.md | 24 ++++++++++--------- ...026-09-17-nested-conditionals-python.ipynb | 24 ++++++++++--------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/_notebooks/2026-09-17-nested-conditionals-python_IPYNB_2_.md b/_notebooks/2026-09-17-nested-conditionals-python_IPYNB_2_.md index 0529ec46e2..9c36b95a0c 100644 --- a/_notebooks/2026-09-17-nested-conditionals-python_IPYNB_2_.md +++ b/_notebooks/2026-09-17-nested-conditionals-python_IPYNB_2_.md @@ -20,17 +20,19 @@ A **nested conditional** is an `if` statement inside another `if`, `elif`, or `e ## 1. LxD Cycle Process -**Empathize:** Nested conditionals can be confusing because indentation changes which decision owns an inner branch, and students may check a detail before confirming that the larger condition applies. +1. **Empathize:** Nested conditionals can be confusing because indentation changes which decision owns an inner branch, and students may check a detail before confirming that the larger condition applies. -**Define:** +2. **Define:** - **POV:** CSP students need a clear way to trace decisions from the outside in so they can build programs with multiple levels of rules. - **Learning Goal:** Students will be able to trace, write, test, and explain nested conditionals in Python. -**Ideate:** +3. **Ideate:** - **HMW Question:** How might we make each path through a nested conditional visible before students write a larger program? - **Activity:** Trace an outer and inner decision, fix incorrect indentation, translate nested logic, and build a two-level decision checker. -**Prototype & Test:** Use the Popcorn Hacks below to check whether students can identify the path a program follows, place an inner condition in the correct block, and test every meaningful outcome. +4. **Prototype:** Build the Tech Talk examples, three Popcorn Hacks, and one Homework Hack. The examples move from tracing a single path to creating a complete two-level decision checker. + +5. **Test:** Teach the draft, check whether students can identify the path a program follows, and collect feedback. Revise any explanation or activity that causes confusion and record the change in Section 5. --- @@ -159,7 +161,7 @@ else: Write the same structure in JavaScript and College Board pseudocode. Then explain which condition is checked first and when `meeting_today` is skipped. -### Popcorn Hack 4: Two-Level Event Checker +### Homework Hack: Two-Level Event Checker Build a Python program for a school event. First check whether registration is complete. Only registered students should then be checked for a digital or printed pass. @@ -183,10 +185,10 @@ has_pass = False | Activity | Points | What earns the points | | --- | ---: | --- | -| Popcorn Hack 1 | 0.2 | Correctly predict the path and change the values to reach all outcomes. | -| Popcorn Hack 2 | 0.2 | Correctly nest the permission check, add the outer `else`, and test all outcomes. | -| Popcorn Hack 3 | 0.2 | Correctly translate the structure into JavaScript and College Board pseudocode and explain the execution order. | -| Popcorn Hack 4 | 0.4 | Build a working two-level event checker, test every outcome, and explain why the inner decision depends on the outer branch. | +| Popcorn Hack 1 | 0.15 | Correctly predict the path and change the values to reach all outcomes. | +| Popcorn Hack 2 | 0.15 | Correctly nest the permission check, add the outer `else`, and test all outcomes. | +| Popcorn Hack 3 | 0.20 | Correctly translate the structure into JavaScript and College Board pseudocode and explain the execution order. | +| Homework Hack | 0.50 | Build a working two-level event checker, test every outcome, and explain why the inner decision depends on the outer branch. | | **Total** | **1.0** | | --- @@ -194,7 +196,7 @@ has_pass = False ## 5. Lesson Revisions & Feedback Evidence - The lesson is organized into the same numbered `1` through `5` structure used by the Boolean Expressions and Random Values lessons. -- Activity names use **Tech Talk** for instruction and **Popcorn Hack** for practice tasks. +- Activity names use **Tech Talk**, **Popcorn Hack**, and **Homework Hack** as required by the Sprint 2 teaching objectives. - Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids. - The examples progress from tracing one path to building and testing a complete two-level decision. -- Feedback from a practice run can be added here with the specific change that was made because of it. +- **Feedback applied:** The LxD process was revised from a combined “Prototype & Test” entry into five explicit, numbered stages, and the final challenge was labeled as a Homework Hack to match the course requirements. diff --git a/_projects/lessons/python/notebooks/2026-09-17-nested-conditionals-python.ipynb b/_projects/lessons/python/notebooks/2026-09-17-nested-conditionals-python.ipynb index c553a8a263..dfe878c251 100644 --- a/_projects/lessons/python/notebooks/2026-09-17-nested-conditionals-python.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-17-nested-conditionals-python.ipynb @@ -31,17 +31,19 @@ "\n", "## 1. LxD Cycle Process\n", "\n", - "**Empathize:** Nested conditionals can be confusing because indentation changes which decision owns an inner branch, and students may check a detail before confirming that the larger condition applies.\n", + "1. **Empathize:** Nested conditionals can be confusing because indentation changes which decision owns an inner branch, and students may check a detail before confirming that the larger condition applies.\n", "\n", - "**Define:**\n", + "2. **Define:**\n", "- **POV:** CSP students need a clear way to trace decisions from the outside in so they can build programs with multiple levels of rules.\n", "- **Learning Goal:** Students will be able to trace, write, test, and explain nested conditionals in Python.\n", "\n", - "**Ideate:**\n", + "3. **Ideate:**\n", "- **HMW Question:** How might we make each path through a nested conditional visible before students write a larger program?\n", "- **Activity:** Trace an outer and inner decision, fix incorrect indentation, translate nested logic, and build a two-level decision checker.\n", "\n", - "**Prototype & Test:** Use the Popcorn Hacks below to check whether students can identify the path a program follows, place an inner condition in the correct block, and test every meaningful outcome.\n", + "4. **Prototype:** Build the Tech Talk examples, three Popcorn Hacks, and one Homework Hack. The examples move from tracing a single path to creating a complete two-level decision checker.\n", + "\n", + "5. **Test:** Teach the draft, check whether students can identify the path a program follows, and collect feedback. Revise any explanation or activity that causes confusion and record the change in Section 5.\n", "\n", "---\n", "\n", @@ -220,7 +222,7 @@ "source": [ "Write the same structure in JavaScript and College Board pseudocode. Then explain which condition is checked first and when `meeting_today` is skipped.\n", "\n", - "### Popcorn Hack 4: Two-Level Event Checker\n", + "### Homework Hack: Two-Level Event Checker\n", "\n", "Build a Python program for a school event. First check whether registration is complete. Only registered students should then be checked for a digital or printed pass.\n", "\n", @@ -254,10 +256,10 @@ "\n", "| Activity | Points | What earns the points |\n", "| --- | ---: | --- |\n", - "| Popcorn Hack 1 | 0.2 | Correctly predict the path and change the values to reach all outcomes. |\n", - "| Popcorn Hack 2 | 0.2 | Correctly nest the permission check, add the outer `else`, and test all outcomes. |\n", - "| Popcorn Hack 3 | 0.2 | Correctly translate the structure into JavaScript and College Board pseudocode and explain the execution order. |\n", - "| Popcorn Hack 4 | 0.4 | Build a working two-level event checker, test every outcome, and explain why the inner decision depends on the outer branch. |\n", + "| Popcorn Hack 1 | 0.15 | Correctly predict the path and change the values to reach all outcomes. |\n", + "| Popcorn Hack 2 | 0.15 | Correctly nest the permission check, add the outer `else`, and test all outcomes. |\n", + "| Popcorn Hack 3 | 0.20 | Correctly translate the structure into JavaScript and College Board pseudocode and explain the execution order. |\n", + "| Homework Hack | 0.50 | Build a working two-level event checker, test every outcome, and explain why the inner decision depends on the outer branch. |\n", "| **Total** | **1.0** | |\n", "\n", "---\n", @@ -265,10 +267,10 @@ "## 5. Lesson Revisions & Feedback Evidence\n", "\n", "- The lesson is organized into the same numbered `1` through `5` structure used by the Boolean Expressions and Random Values lessons.\n", - "- Activity names use **Tech Talk** for instruction and **Popcorn Hack** for practice tasks.\n", + "- Activity names use **Tech Talk**, **Popcorn Hack**, and **Homework Hack** as required by the Sprint 2 teaching objectives.\n", "- Python stays the main coding language, while JavaScript and College Board pseudocode are short comparison aids.\n", "- The examples progress from tracing one path to building and testing a complete two-level decision.\n", - "- Feedback from a practice run can be added here with the specific change that was made because of it." + "- **Feedback applied:** The LxD process was revised from a combined “Prototype & Test” entry into five explicit, numbered stages, and the final challenge was labeled as a Homework Hack to match the course requirements." ] } ], From 2ea5fe5621a85e6216f51f353da225d5bc07be4a Mon Sep 17 00:00:00 2001 From: Rydenb Date: Thu, 17 Sep 2026 14:11:06 -0700 Subject: [PATCH 42/43] update lesson 3.14 --- .../2026-09-16-libraries_python.ipynb | 179 ++++++++++++++---- 1 file changed, 137 insertions(+), 42 deletions(-) diff --git a/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb b/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb index 45257fbf76..a77cc4e39c 100644 --- a/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb +++ b/_projects/lessons/python/notebooks/2026-09-16-libraries_python.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "raw", - "id": "8a7d457b", + "id": "246503bc", "metadata": { "vscode": { "languageId": "raw" @@ -29,7 +29,7 @@ }, { "cell_type": "markdown", - "id": "07efb274", + "id": "d4837e49", "metadata": {}, "source": [ "## The Core Rule\n", @@ -59,7 +59,7 @@ }, { "cell_type": "markdown", - "id": "f96ea615", + "id": "acb56859", "metadata": {}, "source": [ "## 1. LxD Cycle Process\n", @@ -83,7 +83,7 @@ }, { "cell_type": "markdown", - "id": "752231fd", + "id": "ba38f272", "metadata": {}, "source": [ "## 2. Lesson Plan\n", @@ -104,7 +104,7 @@ }, { "cell_type": "markdown", - "id": "2770ac3c", + "id": "9635eb43", "metadata": {}, "source": [ "### Cycle 1 Tech Talk: What is a Library? (2 minutes)\n", @@ -121,17 +121,49 @@ "import statistics as stats # use as stats.mean([1, 2, 3])\n", "~~~\n", "\n", - "**How do you know what a procedure does?** You read its **API**, which tells you the procedure's name, its parameters, and what it returns. You don't need to know how `random.randint` works inside. You only need to know it returns a random integer between `a` and `b`, including both. This is **procedural abstraction**.\n", + "**A library procedure is still a procedure.** You already know how to write one (3.12 Calling Procedures and 3.13 Developing Procedures). Here is an average written by hand:\n", + "\n", + "~~~python\n", + "def calculate_average(scores):\n", + " total = 0\n", + " for score in scores:\n", + " total += score\n", + " return total / len(scores)\n", + "\n", + "print(\"Average:\", calculate_average([90, 85, 78, 92, 88]))\n", + "~~~\n", + "\n", + "Break that procedure into the three parts you have already studied:\n", + "\n", + "| Part | In `calculate_average` | In `statistics.mean` |\n", + "| --- | --- | --- |\n", + "| **Name and parameters** | `calculate_average(scores)` | `mean(data)` |\n", + "| **Algorithm inside** | the loop that adds, then divides | a tested algorithm you never see |\n", + "| **Return value** | `total / len(scores)` | the average of the data |\n", + "\n", + "~~~python\n", + "import statistics\n", + "print(\"Average:\", statistics.mean([90, 85, 78, 92, 88]))\n", + "~~~\n", + "\n", + "Both do the same job. The library version is one line, is already tested, and handles cases your loop does not, such as an empty list.\n", "\n", "* ✅ **Do this:** `average = statistics.mean(scores)`\n", "* ❌ **Don't do this:** write your own loop to add and divide when a tested procedure already exists\n", "\n", - "**Where is the documentation?** Look at [docs.python.org](https://docs.python.org/3/library/), or ask Python directly with `help(math.sqrt)` or `print(math.sqrt.__doc__)`." + "**How do you know what a procedure does?** You read its **API**, which tells you the procedure's name, its parameters, and what it returns. You don't need to know how `random.randint` works inside. You only need to know it returns a random integer between `a` and `b`, including both. That is **abstraction**: the algorithm is hidden, the API is what you use.\n", + "\n", + "**Where is the documentation?** Look at [docs.python.org](https://docs.python.org/3/library/), or ask Python directly:\n", + "\n", + "| Question | Code |\n", + "| --- | --- |\n", + "| What is inside this library? | `dir(math)` |\n", + "| What does this procedure do? | `help(math.sqrt)` or `print(math.sqrt.__doc__)` |" ] }, { "cell_type": "markdown", - "id": "b9f8c025", + "id": "67181891", "metadata": {}, "source": [ "### Popcorn Hack 1: Read the API, Then Use It (5 minutes)\n", @@ -141,10 +173,8 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "3f0655c0", + "id": "c7799d56", "metadata": {}, - "outputs": [], "source": [ "# CODE_RUNNER: Popcorn Hack 1 - Read the API documentation, then finish the TODOs using math and random\n", "\n", @@ -173,11 +203,13 @@ "average = sum(scores) / len(scores)\n", "rounded_up = average\n", "print(\"Average:\", average, \"-> rounded up:\", rounded_up)" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "8da383d5", + "id": "31d26acc", "metadata": {}, "source": [ "---\n", @@ -209,26 +241,42 @@ }, { "cell_type": "markdown", - "id": "8f76e599", + "id": "fc095c58", "metadata": {}, "source": [ "### Popcorn Hack 2: Read a Notebook Like the OCS Converter (5 minutes)\n", "\n", - "**Task:** A tiny `.ipynb` file is stored as JSON text. Use the `json` library to load it, then finish the TODOs to find information the OCS converter needs." + "**First, find out what is in the library.** Step 1 of the code prints every procedure inside `json` with `dir(json)`, then prints the documentation for the two you need.\n", + "\n", + "**API you will use:**\n", + "\n", + "| Procedure | What it does | Returns |\n", + "| --- | --- | --- |\n", + "| `json.loads(text)` | Reads JSON **text** into Python data | A `dict` or `list` |\n", + "| `json.dumps(data, indent=2)` | Turns Python data back into JSON text | A `str`, indented and readable |\n", + "\n", + "Once `json.loads` gives you a dictionary, you use it like any other dictionary: `notebook[\"cells\"]` is a list, and each cell is a dictionary with the keys `\"cell_type\"` and `\"source\"`.\n", + "\n", + "**Task:** Run the code to see the library's procedures and the notebook data. Then finish the three TODOs." ] }, { "cell_type": "code", - "execution_count": null, - "id": "7dd45399", + "id": "804ddbc9", "metadata": {}, - "outputs": [], "source": [ "# CODE_RUNNER: Popcorn Hack 2 - Use the json library to read a notebook the way the OCS converter does\n", "\n", "import json\n", "\n", - "# A tiny .ipynb file is just JSON text\n", + "# Step 1: Find out what is inside the library before you use it\n", + "print(\"Procedures in json:\", [name for name in dir(json) if not name.startswith(\"_\")])\n", + "print()\n", + "print(\"json.loads ->\", json.loads.__doc__.strip().splitlines()[0])\n", + "print(\"json.dumps ->\", json.dumps.__doc__.strip().splitlines()[0])\n", + "print()\n", + "\n", + "# Step 2: A tiny .ipynb file is just JSON text\n", "notebook_text = '''\n", "{\n", " \"cells\": [\n", @@ -240,26 +288,34 @@ "}\n", "'''\n", "\n", - "# json.loads turns JSON text into a Python dictionary\n", + "# Step 3: json.loads turns JSON text into a Python dictionary\n", "notebook = json.loads(notebook_text)\n", "cells = notebook[\"cells\"]\n", "print(\"Number of cells:\", len(cells))\n", + "print(\"First cell:\", cells[0])\n", + "print()\n", "\n", "# TODO 1: Count how many cells have a cell_type of \"code\"\n", + "# Hint: loop over cells and add 1 each time cell[\"cell_type\"] == \"code\"\n", "code_cells = 0\n", "print(\"Code cells:\", code_cells)\n", "\n", - "# TODO 2: Find the line that starts with \"title:\" in the front matter and save only the title text\n", + "# TODO 2: Save only the title text, \"3.14 Libraries\", from the front matter\n", + "# Hint: loop over front_matter.splitlines(), find the line that starts with \"title:\",\n", + "# then use line.split(\":\", 1)[1].strip() to keep only the part after the colon\n", "front_matter = \"\".join(cells[0][\"source\"])\n", "title = \"\"\n", "print(\"Title:\", title)\n", "\n", - "# TODO 3: Use json.dumps with indent=2 to print the last cell as formatted JSON" - ] + "# TODO 3: Print the last cell as formatted JSON\n", + "# Hint: print(json.dumps(cells[-1], indent=2))" + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "cdd1cde7", + "id": "fb5f6824", "metadata": {}, "source": [ "---\n", @@ -311,20 +367,39 @@ }, { "cell_type": "markdown", - "id": "3eeced9f", + "id": "1cb14477", "metadata": {}, "source": [ "### Popcorn Hack 3: Check a requirements.txt (5 minutes)\n", "\n", - "**Task:** Finish `parse_requirements` so it skips blank lines and comments and removes version numbers. The program then uses `importlib` to check which packages are installed on the code runner." + "A `requirements.txt` is just text, so a program can read it. `parse_requirements` turns that text into a clean list of package names, and `is_installed` checks each one.\n", + "\n", + "**API you will use:**\n", + "\n", + "| Procedure | What it does | Returns |\n", + "| --- | --- | --- |\n", + "| `line.strip()` | Removes spaces from both ends of a string | A `str` |\n", + "| `line.startswith(\"#\")` | Checks if the line begins with `#`, which marks a comment | `True` or `False` |\n", + "| `line.split(\"==\")[0]` | Splits at `==` and keeps the part before it | A `str` |\n", + "| `importlib.util.find_spec(name)` | Looks for an installed library by its **import** name | The library's info, or `None` if missing |\n", + "\n", + "**What the parsing needs to do**, line by line:\n", + "\n", + "| Line in the file | Should become |\n", + "| --- | --- |\n", + "| `# Web framework` | skipped, it is a comment |\n", + "| (blank line) | skipped |\n", + "| `requests` | `requests` |\n", + "| `Flask>=3.0` | `Flask` |\n", + "| `pandas==2.2.2` | `pandas` |\n", + "\n", + "**Task:** Finish the three TODOs. Each one has a hint in the code." ] }, { "cell_type": "code", - "execution_count": null, - "id": "4749e167", + "id": "d4ceb6aa", "metadata": {}, - "outputs": [], "source": [ "# CODE_RUNNER: Popcorn Hack 3 - Finish the requirements.txt checker using importlib\n", "\n", @@ -348,20 +423,36 @@ " \"python-dotenv\": \"dotenv\",\n", "}\n", "\n", + "# Symbols that start a version, such as the \">=\" in \"Flask>=3.0\"\n", + "VERSION_SYMBOLS = [\"==\", \">=\", \"<=\", \"~=\", \">\", \"<\"]\n", + "\n", "def parse_requirements(text):\n", - " '''Return a list of package names from requirements.txt text.'''\n", + " '''\n", + " Read requirements.txt text and return a list of package names.\n", + " Parameters: text, the contents of a requirements.txt file as a string\n", + " Returns: a list of package names with no comments, blanks, or versions\n", + " '''\n", " packages = []\n", " for line in text.splitlines():\n", " line = line.strip()\n", - " # TODO 1: Skip blank lines and lines that start with \"#\"\n", "\n", - " # TODO 2: Remove version specifiers such as \"==2.2.2\" or \">=3.0\"\n", + " # TODO 1: Skip blank lines and comment lines\n", + " # Hint: if the line is empty, or line.startswith(\"#\"), use continue\n", + "\n", + " # TODO 2: Remove the version from the end of the name\n", + " # Hint: for symbol in VERSION_SYMBOLS:\n", + " # if symbol in line:\n", + " # line = line.split(symbol)[0]\n", " name = line\n", " packages.append(name)\n", " return packages\n", "\n", "def is_installed(package):\n", - " '''Return True if Python can find the package on this computer.'''\n", + " '''\n", + " Check whether a package is installed on this computer.\n", + " Parameters: package, the name used with pip install\n", + " Returns: True if Python can find it, otherwise False\n", + " '''\n", " import_name = IMPORT_NAMES.get(package, package)\n", " try:\n", " return importlib.util.find_spec(import_name) is not None\n", @@ -374,12 +465,16 @@ " else:\n", " print(f\"{package!r:20} missing -> pip install {package}\")\n", "\n", - "# TODO 3: Print is_installed(\"json\"). Why is json installed even though it is not in requirements.txt?" - ] + "# TODO 3: Check one more package with print(is_installed(\"json\"))\n", + "# Hint: json is a standard library module. Answer in a comment here:\n", + "# why is json already installed even though nobody listed it in requirements.txt?" + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "f667e856", + "id": "b7c2a22b", "metadata": {}, "source": [ "---\n", @@ -422,7 +517,7 @@ }, { "cell_type": "markdown", - "id": "c6a4265c", + "id": "c61e494e", "metadata": {}, "source": [ "### Homework Hack: Study Session Report\n", @@ -438,10 +533,8 @@ }, { "cell_type": "code", - "execution_count": null, - "id": "63eee878", + "id": "860bf676", "metadata": {}, - "outputs": [], "source": [ "# CODE_RUNNER: Homework - Build a Study Session Report using at least 3 libraries\n", "\n", @@ -477,11 +570,13 @@ "'''\n", "print(\"requirements.txt:\")\n", "print(requirements_txt)" - ] + ], + "execution_count": null, + "outputs": [] }, { "cell_type": "markdown", - "id": "5621c480", + "id": "9c7174e4", "metadata": {}, "source": [ "---\n", From 5628838828ce25ea445b3b63a6ef4eaad2931e1a Mon Sep 17 00:00:00 2001 From: jm1021 Date: Thu, 17 Sep 2026 19:40:42 -0700 Subject: [PATCH 43/43] remove olds files, fix permalinks --- ...-26-data_abstractions_remakers_IPYNB_2_.md | 557 ------------ ...6-iterations_scratchers_lesson_IPYNB_2_.md | 518 ----------- ...math-expressions-collaborators_IPYNB_2_.md | 739 --------------- .../2025-09-27-strings_zombies_IPYNB_2_.md | 182 ---- ...-functions_tinkerers_js_lesson_IPYNB_2_.md | 851 ------------------ ...5-09-30-algorithmic-efficiency_IPYNB_2_.md | 83 -- ...-09-30-lists_scratchers_lesson_IPYNB_2_.md | 234 ----- ...lgorithms-Lesson-SyntaxTerrors_IPYNB_2_.md | 21 - ...ditionals_constellators_lesson_IPYNB_2_.md | 193 ---- ...ing_procedures_remakers_lesson_IPYNB_2_.md | 263 ------ ...developing-algorithms_crashers_IPYNB_2_.md | 549 ----------- ...ing_procedures_remakers_lesson_IPYNB_2_.md | 188 ---- _notebooks/2026-01-07-arrays_IPYNB_2_.md | 459 ---------- .../2026-01-09-data_abstraction_IPYNB_2_.md | 441 --------- .../2026-01-13-iterations_lesson_IPYNB_2_.md | 317 ------- _notebooks/2026-01-16-json_lesson_IPYNB_2_.md | 349 ------- .../2026-01-20-booleans-lessons_IPYNB_2_.md | 158 ---- _notebooks/2026-01-20-math-exp_IPYNB_2_.md | 302 ------- _notebooks/2026-01-27-Strings_IPYNB_2_.md | 183 ---- _notebooks/2026-02-19-variables_IPYNB_2_.md | 280 ------ ...21-variables_python_instructor_IPYNB_2_.md | 296 ------ ...09-15-boolean_scratchers_py_hw_IPYNB_2_.md | 214 ----- ...2026-09-15-random_py_sprinters_IPYNB_2_.md | 181 ---- .../2026-1-14-Nested-Conditionals_IPYNB_2_.md | 264 ------ ...-1-27-ClassesAndMethods-Lesson_IPYNB_2_.md | 295 ------ ...025-09-26-data_abstractions_remakers.ipynb | 2 +- ...5-09-26-iterations_scratchers_lesson.ipynb | 2 +- ...09-26-math-expressions-collaborators.ipynb | 2 +- ...025-09-26-nested_conditionals_lesson.ipynb | 353 ++++++++ .../2025-09-27-strings_zombies.ipynb | 2 +- .../2025-09-30-algorithmic-efficiency.ipynb | 2 +- .../2025-09-30-lists_scratchers_lesson.ipynb | 2 +- ...2025-10-02-slgorithms-syntaxterrors.ipynb} | 2 +- ...8-calling_procedures_remakers_lesson.ipynb | 8 +- ...10-09-developing-algorithms_crashers.ipynb | 2 +- ...eveloping_procedures_remakers_lesson.ipynb | 2 +- .../2026-09-15-boolean_scratchers_py_hw.ipynb | 345 ++++++- .../2026-09-15-random_py_sprinters.ipynb | 288 +++++- 38 files changed, 999 insertions(+), 8130 deletions(-) delete mode 100644 _notebooks/2025-09-26-data_abstractions_remakers_IPYNB_2_.md delete mode 100644 _notebooks/2025-09-26-iterations_scratchers_lesson_IPYNB_2_.md delete mode 100644 _notebooks/2025-09-26-math-expressions-collaborators_IPYNB_2_.md delete mode 100644 _notebooks/2025-09-27-strings_zombies_IPYNB_2_.md delete mode 100644 _notebooks/2025-09-29-functions_tinkerers_js_lesson_IPYNB_2_.md delete mode 100644 _notebooks/2025-09-30-algorithmic-efficiency_IPYNB_2_.md delete mode 100644 _notebooks/2025-09-30-lists_scratchers_lesson_IPYNB_2_.md delete mode 100644 _notebooks/2025-10-02-Algorithms-Lesson-SyntaxTerrors_IPYNB_2_.md delete mode 100644 _notebooks/2025-10-02-conditionals_constellators_lesson_IPYNB_2_.md delete mode 100644 _notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md delete mode 100644 _notebooks/2025-10-09-developing-algorithms_crashers_IPYNB_2_.md delete mode 100644 _notebooks/2025-10-09-developing_procedures_remakers_lesson_IPYNB_2_.md delete mode 100644 _notebooks/2026-01-07-arrays_IPYNB_2_.md delete mode 100644 _notebooks/2026-01-09-data_abstraction_IPYNB_2_.md delete mode 100644 _notebooks/2026-01-13-iterations_lesson_IPYNB_2_.md delete mode 100644 _notebooks/2026-01-16-json_lesson_IPYNB_2_.md delete mode 100644 _notebooks/2026-01-20-booleans-lessons_IPYNB_2_.md delete mode 100644 _notebooks/2026-01-20-math-exp_IPYNB_2_.md delete mode 100644 _notebooks/2026-01-27-Strings_IPYNB_2_.md delete mode 100644 _notebooks/2026-02-19-variables_IPYNB_2_.md delete mode 100644 _notebooks/2026-07-21-variables_python_instructor_IPYNB_2_.md delete mode 100644 _notebooks/2026-09-15-boolean_scratchers_py_hw_IPYNB_2_.md delete mode 100644 _notebooks/2026-09-15-random_py_sprinters_IPYNB_2_.md delete mode 100644 _notebooks/2026-1-14-Nested-Conditionals_IPYNB_2_.md delete mode 100644 _notebooks/2026-1-27-ClassesAndMethods-Lesson_IPYNB_2_.md create mode 100644 _projects/lessons/python/notebooks/2025-09-26-nested_conditionals_lesson.ipynb rename _projects/lessons/python/notebooks/{2025-10-02-Algorithms-Lesson-SyntaxTerrors.ipynb => 2025-10-02-slgorithms-syntaxterrors.ipynb} (93%) diff --git a/_notebooks/2025-09-26-data_abstractions_remakers_IPYNB_2_.md b/_notebooks/2025-09-26-data_abstractions_remakers_IPYNB_2_.md deleted file mode 100644 index 86440dad05..0000000000 --- a/_notebooks/2025-09-26-data_abstractions_remakers_IPYNB_2_.md +++ /dev/null @@ -1,557 +0,0 @@ ---- -layout: post -codemirror: True -courses: {'csp': {'week': 1}} -categories: ['Python', 'Data-Abstraction'] -lesson_language: Python -lesson_topic: Data-Abstraction -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.2 Data Abstractions -description: Intro to data abstractions in Python and JavaScript. -permalink: /csp/big-idea-3/data-abstractions/p4/introduction -author: Jaynee Chauhan, Michelle Ji, Lucas Masterson ---- - -## 🎮 Data Abstraction Quest — Gamified Review - -Test your knowledge in an interactive RPG! Explore the world below and talk to 5 NPC teachers — each one quizzes you on a different concept from this lesson. - -| Key | Action | -|-----|--------| -| **WASD** | Move your character | -| **E** | Talk to an NPC (walk into them first) | - -| NPC | Concept | Topic | -|-----|---------|-------| -| List Keeper (wizard) | Lists | Ordered sequences of elements | -| Index Oracle (robot) | Indexing | 0-based access, string indexing | -| Loop Sage (octocat) | Loops + Lists | Computing with iteration | -| Abstraction Architect (penguin) | Why Abstraction? | Managing complexity | -| AP Guardian (nerd) | AP Exam | 1-based indexing, pseudocode | - -Complete all 5 to become **Master of Abstraction!** Watch your score in the top-right HUD. - - - -{% capture challenge0 %} -Explore the Data Kingdom! Walk to each NPC (WASD) and press E to answer quiz questions on Data Abstraction. Score 5/5 to become the Master of Abstraction! -{% endcapture %} - -{% capture code0 %} -// ─── Imports (GameEngine v1 — no engine files modified) ─── -import GameControl from '/assets/js/GameEnginev1/essentials/GameControl.js'; -import GameEnvBackground from '/assets/js/GameEnginev1/essentials/GameEnvBackground.js'; -import Player from '/assets/js/GameEnginev1/essentials/Player.js'; -import Npc from '/assets/js/GameEnginev1/essentials/Npc.js'; - -// ═══════════════════════════════════════════════════════════ -// SRP Module 1: QuizEngine — manages questions & grading -// ═══════════════════════════════════════════════════════════ -var QuizEngine = { - banks: { - 'List Keeper': [ - { q: "What is a list in programming?", choices: ["A single variable","An ordered sequence of elements","A function","A loop"], answer: 1 }, - { q: "In Python, how do you create a list?", choices: ["list = (1,2,3)","list = {1,2,3}","list = [1,2,3]","list = <1,2,3>"], answer: 2 }, - { q: "Lists can contain:", choices: ["Only numbers","Only strings","Only booleans","Different types of elements"], answer: 3 } - ], - 'Index Oracle': [ - { q: "What index is the FIRST element in Python/JS?", choices: ["1","0","-1","None"], answer: 1 }, - { q: "Given word = 'hello', what is word[1]?", choices: ["'h'","'e'","'l'","'o'"], answer: 1 }, - { q: "On the AP exam, lists are:", choices: ["0-indexed","1-indexed","2-indexed","Not indexed"], answer: 1 } - ], - 'Loop Sage': [ - { q: "scores=[85,92,78,90]; What is sum/len?", choices: ["345","85","86.25","90"], answer: 2 }, - { q: "Why use a loop with a list?", choices: ["It is slower but safer","It manages complexity and is reusable","Loops are required by Python","There is no advantage"], answer: 1 }, - { q: "Which keyword iterates over a JS array?", choices: ["for...of","for...at","each...in","loop...over"], answer: 0 } - ], - 'Abstraction Architect': [ - { q: "Data abstraction means:", choices: ["Deleting unused variables","Treating collections as a single unit","Making code longer","Avoiding lists"], answer: 1 }, - { q: "Which is a benefit of data abstraction?", choices: ["Harder to read code","Easier maintenance","More memory usage","Slower programs"], answer: 1 }, - { q: "Abstraction lets you manipulate a group using:", choices: ["Individual memory addresses","A single name like scores","Only print statements","Manual indexing of every element"], answer: 1 } - ], - 'AP Guardian': [ - { q: "On the AP CSP exam, what index is the first list element?", choices: ["0","1","2","-1"], answer: 1 }, - { q: "A string is:", choices: ["An unordered set","An ordered sequence of characters","A number type","A boolean"], answer: 1 }, - { q: "Data abstractions can be created using:", choices: ["Only dictionaries","Only integers","Lists","Only functions"], answer: 2 } - ] - }, - getQuestion: function(npcId) { - var bank = this.banks[npcId]; - if (!bank || bank.length === 0) return null; - return bank[Math.floor(Math.random() * bank.length)]; - }, - check: function(question, choiceIndex) { - return choiceIndex === question.answer; - } -}; - -// ═══════════════════════════════════════════════════════════ -// SRP Module 2: ScoreTracker — tracks which NPCs are beaten -// ═══════════════════════════════════════════════════════════ -var ScoreTracker = { - _done: {}, - total: 5, - mark: function(npcId) { this._done[npcId] = true; }, - isComplete: function(npcId) { return this._done[npcId] === true; }, - score: function() { return Object.keys(this._done).length; }, - allDone: function() { return Object.keys(this._done).length >= this.total; }, - reset: function() { this._done = {}; } -}; - -// ═══════════════════════════════════════════════════════════ -// SRP Module 3: QuizOverlay — renders DOM quiz popup -// ═══════════════════════════════════════════════════════════ -var QuizOverlay = { - active: false, - _escHandler: null, - - show: function(npcId, npcGreeting) { - if (this.active) return; - this.active = true; - - if (ScoreTracker.isComplete(npcId)) { - this._showMessage(npcId, 'You already answered my question correctly! Move on, scholar!', '#4CAF50'); - return; - } - - var question = QuizEngine.getQuestion(npcId); - if (!question) { this.active = false; return; } - var self = this; - - var overlay = document.createElement('div'); - overlay.id = 'quiz-overlay'; - overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;z-index:10000;font-family:Segoe UI,sans-serif;'; - - var card = document.createElement('div'); - card.style.cssText = 'background:linear-gradient(135deg,#1a1a2e,#16213e);color:#fff;border-radius:16px;padding:32px;max-width:520px;width:90%;box-shadow:0 0 40px rgba(100,100,255,0.3);border:2px solid #6c63ff;text-align:center;'; - - var header = document.createElement('h2'); - header.textContent = npcId + ' asks:'; - header.style.cssText = 'color:#6c63ff;margin:0 0 8px 0;font-size:1.3em;'; - card.appendChild(header); - - var flavor = document.createElement('p'); - flavor.textContent = npcGreeting; - flavor.style.cssText = 'color:#aaa;font-style:italic;margin:0 0 16px 0;font-size:0.9em;'; - card.appendChild(flavor); - - var qText = document.createElement('p'); - qText.style.cssText = 'font-size:1.1em;line-height:1.5;margin-bottom:20px;white-space:pre-wrap;'; - qText.textContent = question.q; - card.appendChild(qText); - - var btnBox = document.createElement('div'); - btnBox.style.cssText = 'display:flex;flex-direction:column;gap:10px;'; - question.choices.forEach(function(choice, idx) { - var btn = document.createElement('button'); - btn.textContent = choice; - btn.style.cssText = 'padding:12px 16px;border:2px solid #6c63ff;border-radius:10px;background:transparent;color:#fff;font-size:1em;cursor:pointer;transition:all 0.2s ease;'; - btn.onmouseenter = function() { btn.style.background = '#6c63ff'; btn.style.transform = 'scale(1.03)'; }; - btn.onmouseleave = function() { btn.style.background = 'transparent'; btn.style.transform = 'scale(1)'; }; - btn.onclick = function() { self._handleAnswer(npcId, question, idx, overlay); }; - btnBox.appendChild(btn); - }); - card.appendChild(btnBox); - - var hint = document.createElement('p'); - hint.textContent = 'Press Escape to close without answering'; - hint.style.cssText = 'color:#555;font-size:0.75em;margin-top:16px;'; - card.appendChild(hint); - - overlay.appendChild(card); - document.body.appendChild(overlay); - - this._escHandler = function(e) { if (e.key === 'Escape') self._close(overlay); }; - document.addEventListener('keydown', this._escHandler); - }, - - _handleAnswer: function(npcId, question, choiceIndex, overlay) { - var correct = QuizEngine.check(question, choiceIndex); - if (correct) { - ScoreTracker.mark(npcId); - HUD.update(); - if (ScoreTracker.allDone()) { - this._close(overlay); - this._showVictory(); - return; - } - } - var msg = correct - ? 'Correct! You have mastered this concept!' - : 'Not quite — review the lesson above and try again!'; - var color = correct ? '#4CAF50' : '#f44336'; - this._close(overlay); - this._showMessage(npcId, msg, color); - }, - - _showMessage: function(npcId, text, borderColor) { - var self = this; - var overlay = document.createElement('div'); - overlay.id = 'quiz-overlay'; - overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);display:flex;align-items:center;justify-content:center;z-index:10000;font-family:Segoe UI,sans-serif;'; - - var box = document.createElement('div'); - box.style.cssText = 'background:#1a1a2e;color:#fff;border-radius:16px;padding:32px;max-width:420px;width:85%;text-align:center;border:2px solid ' + borderColor + ';box-shadow:0 0 30px ' + borderColor + '40;'; - - var icon = document.createElement('div'); - icon.style.cssText = 'font-size:3em;margin-bottom:12px;'; - icon.textContent = borderColor === '#4CAF50' ? '\u2705' : '\u274C'; - box.appendChild(icon); - - var p = document.createElement('p'); - p.textContent = text; - p.style.cssText = 'font-size:1.15em;line-height:1.5;margin:0 0 16px 0;'; - box.appendChild(p); - - var btn = document.createElement('button'); - btn.textContent = 'OK'; - btn.style.cssText = 'padding:10px 32px;border:none;border-radius:8px;background:' + borderColor + ';color:#fff;font-size:1em;cursor:pointer;font-weight:bold;'; - btn.onclick = function() { self._close(overlay); }; - box.appendChild(btn); - - overlay.appendChild(box); - document.body.appendChild(overlay); - this._escHandler = function(e) { if (e.key === 'Escape') self._close(overlay); }; - document.addEventListener('keydown', this._escHandler); - }, - - _showVictory: function() { - var overlay = document.createElement('div'); - overlay.id = 'quiz-overlay'; - overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.9);display:flex;align-items:center;justify-content:center;z-index:10000;font-family:Segoe UI,sans-serif;'; - - var box = document.createElement('div'); - box.style.cssText = 'background:linear-gradient(135deg,#0d0d2b,#1a1a4e);color:#fff;border-radius:20px;padding:40px;max-width:500px;width:90%;text-align:center;border:3px solid #ffd700;box-shadow:0 0 60px rgba(255,215,0,0.4);'; - - var trophy = document.createElement('div'); - trophy.style.cssText = 'font-size:4em;margin-bottom:8px;'; - trophy.textContent = '\uD83C\uDFC6'; - box.appendChild(trophy); - - var title = document.createElement('h1'); - title.textContent = 'MASTER OF ABSTRACTION'; - title.style.cssText = 'color:#ffd700;font-size:2em;margin:0 0 10px 0;'; - box.appendChild(title); - - var sub1 = document.createElement('p'); - sub1.textContent = 'You answered all 5 NPC challenges!'; - sub1.style.cssText = 'font-size:1.2em;color:#ccc;margin-bottom:8px;'; - box.appendChild(sub1); - - var sub2 = document.createElement('p'); - sub2.textContent = 'You truly understand Data Abstraction — lists, indexing, loops, complexity management, and AP concepts.'; - sub2.style.cssText = 'font-size:1em;color:#aaa;margin-bottom:20px;'; - box.appendChild(sub2); - - var btn = document.createElement('button'); - btn.textContent = 'Continue Exploring'; - btn.style.cssText = 'padding:12px 40px;border:none;border-radius:10px;background:#ffd700;color:#000;font-size:1.1em;cursor:pointer;font-weight:bold;'; - btn.onclick = function() { overlay.remove(); }; - box.appendChild(btn); - - overlay.appendChild(box); - document.body.appendChild(overlay); - }, - - _close: function(overlay) { - if (overlay && overlay.parentNode) overlay.remove(); - if (this._escHandler) document.removeEventListener('keydown', this._escHandler); - this.active = false; - } -}; - -// ═══════════════════════════════════════════════════════════ -// SRP Module 4: HUD — heads-up display for score -// ═══════════════════════════════════════════════════════════ -var HUD = { - el: null, - - create: function() { - var old = document.getElementById('abstraction-hud'); - if (old) old.remove(); - - this.el = document.createElement('div'); - this.el.id = 'abstraction-hud'; - this.el.style.cssText = 'position:fixed;top:12px;right:12px;z-index:9999;background:linear-gradient(135deg,#1a1a2e,#16213e);border:2px solid #6c63ff;border-radius:12px;padding:10px 18px;color:#fff;font-family:Segoe UI,sans-serif;box-shadow:0 0 20px rgba(100,100,255,0.3);min-width:180px;'; - document.body.appendChild(this.el); - this.update(); - }, - - update: function() { - if (!this.el) return; - var s = ScoreTracker.score(); - var filled = ''; - var empty = ''; - for (var i = 0; i < s; i++) filled += '\u2B50'; - for (var j = 0; j < 5 - s; j++) empty += '\u2606'; - - var titleDiv = document.createElement('div'); - titleDiv.style.cssText = 'font-weight:bold;font-size:1.1em;margin-bottom:4px;'; - titleDiv.textContent = 'Data Quest'; - - var starsDiv = document.createElement('div'); - starsDiv.style.cssText = 'font-size:1.3em;letter-spacing:2px;'; - starsDiv.textContent = filled + empty; - - var countDiv = document.createElement('div'); - countDiv.style.cssText = 'color:#aaa;font-size:0.85em;margin-top:4px;'; - countDiv.textContent = s + '/5 NPCs completed'; - - this.el.innerHTML = ''; - this.el.appendChild(titleDiv); - this.el.appendChild(starsDiv); - this.el.appendChild(countDiv); - }, - - destroy: function() { - if (this.el) { this.el.remove(); this.el = null; } - } -}; - -// ═══════════════════════════════════════════════════════════ -// SRP Module 5: DataAbstractionLevel — composes everything -// ═══════════════════════════════════════════════════════════ -class DataAbstractionLevel { - constructor(gameEnv) { - var path = gameEnv.path; - var width = gameEnv.innerWidth; - var height = gameEnv.innerHeight; - - ScoreTracker.reset(); - HUD.create(); - - var bgData = { - name: 'data_kingdom', - greeting: 'Welcome to the Data Kingdom! Speak to each NPC to prove your abstraction knowledge.', - src: path + '/images/gamify/city.png', - pixels: { height: 654, width: 966 } - }; - - var SCALE = 5; - var playerData = { - id: 'Scholar', - greeting: 'I seek the wisdom of Data Abstraction!', - src: path + '/images/gamify/chillguy.png', - SCALE_FACTOR: SCALE, - STEP_FACTOR: 1000, - ANIMATION_RATE: 50, - INIT_POSITION: { x: width / 2 - 30, y: height - (height / SCALE) }, - pixels: { height: 384, width: 512 }, - orientation: { rows: 3, columns: 4 }, - down: { row: 0, start: 0, columns: 3 }, - downRight: { row: 1, start: 0, columns: 3, rotate: Math.PI / 16 }, - downLeft: { row: 2, start: 0, columns: 3, rotate: -Math.PI / 16 }, - left: { row: 2, start: 0, columns: 3 }, - right: { row: 1, start: 0, columns: 3 }, - up: { row: 3, start: 0, columns: 3 }, - upLeft: { row: 2, start: 0, columns: 3, rotate: Math.PI / 16 }, - upRight: { row: 1, start: 0, columns: 3, rotate: -Math.PI / 16 }, - hitbox: { widthPercentage: 0.45, heightPercentage: 0.2 }, - keypress: { up: 87, left: 65, down: 83, right: 68 } - }; - - function npcData(id, greeting, sprite, px, initPos, scaleFactor, orient, downAnim) { - return { - id: id, - greeting: greeting, - src: path + sprite, - SCALE_FACTOR: scaleFactor, - ANIMATION_RATE: 100, - pixels: px, - INIT_POSITION: initPos, - orientation: orient, - down: downAnim, - hitbox: { widthPercentage: 0.1, heightPercentage: 0.2 }, - reaction: function() { - if (ScoreTracker.isComplete(id)) { - alert(id + ': Already conquered! Move to the next NPC.'); - } else { - alert(greeting); - } - }, - interact: function() { - QuizOverlay.show(id, greeting); - } - }; - } - - var listKeeper = npcData( - 'List Keeper', - 'I am the List Keeper! Lists are ordered sequences of elements. Can you prove you understand them?', - '/images/gamify/wizard.png', - { width: 163, height: 185 }, - { x: width * 0.10, y: height * 0.20 }, - 3, - { rows: 1, columns: 1 }, - { row: 0, start: 0, columns: 1 } - ); - - var indexOracle = npcData( - 'Index Oracle', - 'Beep boop! I am the Index Oracle. Do you know how indexing works in Python and JavaScript?', - '/images/gamify/robot.png', - { width: 627, height: 316 }, - { x: width * 0.80, y: height * 0.15 }, - 8, - { rows: 3, columns: 6 }, - { row: 1, start: 0, columns: 6 } - ); - - var loopSage = npcData( - 'Loop Sage', - 'Meow-code! I am the Loop Sage. Loops and lists together are powerful — let me test you!', - '/images/gamify/octocat.png', - { width: 801, height: 301 }, - { x: width * 0.45, y: height * 0.40 }, - 6, - { rows: 1, columns: 1 }, - { row: 0, start: 0, columns: 1 } - ); - - var abstractArch = npcData( - 'Abstraction Architect', - 'I am the Architect of Abstraction! Treating collections as single units manages complexity. Prove it!', - '/images/gamify/tux.png', - { width: 256, height: 352 }, - { x: width * 0.15, y: height * 0.65 }, - 4, - { rows: 1, columns: 1 }, - { row: 0, start: 0, columns: 1 } - ); - - var apGuardian = npcData( - 'AP Guardian', - 'Greetings, future AP scholar! I guard the AP CSP knowledge. Remember: AP lists are 1-indexed!', - '/images/gamify/nerd.png', - { width: 343, height: 503 }, - { x: width * 0.78, y: height * 0.60 }, - 4, - { rows: 1, columns: 1 }, - { row: 0, start: 0, columns: 1 } - ); - - this.classes = [ - { class: GameEnvBackground, data: bgData }, - { class: Player, data: playerData }, - { class: Npc, data: listKeeper }, - { class: Npc, data: indexOracle }, - { class: Npc, data: loopSage }, - { class: Npc, data: abstractArch }, - { class: Npc, data: apGuardian } - ]; - } -} - -export var gameLevelClasses = [DataAbstractionLevel]; -export { GameControl }; -{% endcapture %} - -{% include runners/game.html - runner_id="csp-big-idea-3-data-abstractions-p4-introduction-0" - challenge=challenge0 - code=code0 -%} - - -## Learning Objectives - -> 3.A Generalize data sources through variables. -> -> 3.B Use abstraction to manage complexity in a program. -> -> 3.C Explain how abstraction manages complexity. - -## Data Abstractions - -Data abstraction means *treating collections of values as a single unit* (like a list, array, or string), so you don’t have to think about all the small details every time you use them. This manages complexity by letting us use a name (like `numbers`) instead of repeatedly referencing each individual element. - -For example, in Python: - -```py -# A list in Python -numbers = [10, 20, 30, 40] - -# Access by index (0-based in Python) -print(numbers[0]) # 10 -print(numbers[2]) # 30 - -# Strings work similarly -word = "hello" -print(word[1]) # 'e' -``` - -or in JavaScript: - -```js -// An array in JavaScript -let numbers = [10, 20, 30, 40]; - -console.log(numbers[0]); // 10 -console.log(numbers[2]); // 30 - -// Strings are also indexable -let word = "hello"; -console.log(word[1]); // 'e' -``` - -## Using Abstractions to Manage Complexity - -Instead of writing code for each item, we use loops and functions to work with lists. - -For example, in Python, we could iterate over a list and find the average of its elements: - -```py -scores = [85, 92, 78, 90] - -# Sum with a loop -total = 0 -for score in scores: - total += score -print("Average:", total / len(scores)) # 86.25 -``` - -and in JS: - -```js -let scores = [85, 92, 78, 90]; - -// Using a loop -let total = 0; -for (let score of scores) { - total += score; -} -console.log("Average:", total / scores.length); -``` - -## How Abstraction Manages Complexity - -Instead of thinking about *every score individually*, you can use the abstraction "list of scores." -- With a name (`scores`), you manipulate the entire group. -- You don't need to worry about how the list is stored in memory. -- Functions and loops let you work with the *concept* of a collection, not every detail. - -What we mean by the last part may be a bit more understandable in some examples of benefits. -- Easier maintenance (add/remove scores without rewriting logic over and over again). -- Reusable functions (average can work for any list of numbers). -- Clearer code (you read "average of scores" instead of `score1 + score2 + score3 + ...`). - -## Nuances - -Remember that Python and JS both use 0-based indexing, which means that the first element of a list/array/string is at index 0 (like we showed before). - -## Quick Facts (From AP) - -- A *list* is an ordered sequence of elements. For example, `[value1, value2, value3, ...]` describes a list where `value1` is the first element, `value2` is the second element, and `value3` is the third element, and so on. -- An *element* is an individual value in a list that is assigned a unique index. -- An *index* is a common method for referencing the elements ina list or string using natural numbers. -- A *string* is an ordered sequence of characters. -- Data abstraction provides a separation between the abstract properties of a data type and the concrete details of its representation. -- Data abstractions manage complexity in programs by giving a collection of data a name without referencing the specific details of the representation. -- Data abstractions can be created using lists. -- Developing a data abstraction to implement in a program can result in a program that is easier to develop and maintain. -- Data abstractions often contain different types of elements. -- The use of lists allows multiple related items to be treated as a single value. Lists are referred to by different names such as array, depending on the programming language. -- **For AP, lists are 1-indexed!** diff --git a/_notebooks/2025-09-26-iterations_scratchers_lesson_IPYNB_2_.md b/_notebooks/2025-09-26-iterations_scratchers_lesson_IPYNB_2_.md deleted file mode 100644 index 32fb5d6033..0000000000 --- a/_notebooks/2025-09-26-iterations_scratchers_lesson_IPYNB_2_.md +++ /dev/null @@ -1,518 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Iterations'] -lesson_language: Python -lesson_topic: Iterations -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.8 Iterations -description: An introduction to College Board's Big Idea 3.8 Iterations. This will help you understand how to write loops in Python and JavaScript. -permalink: /csp/big-idea-3/scratchers/iterations/p4/lesson ---- - -## Iteration Lesson – Big Idea 3.8 - - - -## Warm-Up -Think about these questions: -- How do you brush your teeth every morning? -- Do you repeat steps until your teeth feel clean? -- What are other examples in daily life where we repeat steps? - -Iteration is like repeating those steps in code until a condition is met. - - -## Key Vocabulary -- **Loop** – A structure that repeats instructions. -- **For loop** – Repeats a block of code a specific number of times. -- **While loop** – Repeats a block of code as long as a condition is true. -- **Iteration** – Each repetition of the loop body. - - -## Language comparison: Python vs JavaScript - - -Short notes for beginners: -- Python uses indentation to mark the loop body; JavaScript uses braces `{}`. -- Python commonly uses `range()` and direct iteration over lists; JavaScript often uses `for`, `for...of`, or array methods like `.forEach()`. -- Behavior of `break` and `continue` is the same in both languages but the syntax differs slightly. -- When converting between languages, focus on the loop's goal (counting, iterating, waiting for a condition) and pick the matching pattern in the target language. - -## For loops - -A `for` loop is used when you know (or can determine) how many times you want to repeat something. In Python, `for variable in sequence:` runs the body once for each item in the sequence. - -`for` loops are **definate** loops meaning they only run for a definate amount of variables - -Key parts: -- `variable`: a name that refers to the current item or index each iteration. -- `sequence`: something you can loop over (like `range()`, lists, strings). - -### What happens during a `for` loop (step-by-step) - -Let's look at a tiny loop and trace exactly what the computer does each step. This helps us see how the loop variable changes and when the loop stops. - -Code to trace: -```python -for i in range(1, 4): - print('i is', i) -``` - -Step-by-step explanation: -1. `range(1, 4)` creates the sequence [1, 2, 3]. -2. The loop picks the first item (1) and assigns it to `i`. -3. The body `print('i is', i)` runs and shows `i is 1`. -4. The loop picks the next item (2), assigns to `i`, runs the body, prints `i is 2`. -5. The loop picks the next item (3), prints `i is 3`. -6. There are no more items, so the loop ends. - -Try changing the range numbers to see more or fewer iterations. - - -```python -# Run the tiny loop so you can see the trace -for i in range(1, 4): - print('current value of i =', i) - -``` - -### `for` Popcorn Hack: Iterate a list of names -Example: iterate a list of names and greet each person. - - -```python -blanks = ['', '', ''] -for blank in blanks: - print('Hello,', blank) - -``` - -### Python vs JavaScript: `for` Loops - -### 1) Simple `for` loop (counting) -Python explanation: `for i in range(start, end)` runs i through a sequence of numbers. -```python -for i in range(1, 6): - print(i) # prints 1,2,3,4,5 -``` -JavaScript explanation: `for (let i = start; i < end; i++)` is the usual counting loop. -```javascript -for (let i = 1; i <= 5; i++) { - console.log(i); // prints 1,2,3,4,5 -} -``` -### 2) Looping over an array/list -Python (list): use `for item in list:` -```python -names = ['Anwita','Nicholas','Varada'] -for name in names: - print('Hello', name) -``` -JavaScript (array): use `for...of` or index loop -```javascript -const names = ['Anwita','Nicholas','Varada']; -for (const name of names) { - console.log('Hello', name); -} -``` - -## while Loop - -A `while` loop repeats as long as a condition remains true. Use `while` when you don’t know in advance how many iterations you need — just the condition that should stop the loop. - -A `while` loop is an **indefinate** loop meaning it will repeat as long as a condition is true -Important ideas: -- Ensure something in the loop eventually makes the condition false (like updating a counter). -- Be careful with input-driven loops — always validate and provide a clear exit path. - -Example: Create a list of numbers and end and 5 - -We are going to use what we learned previously in math expressions! - - -```python -# Initialize a variable -num = 1 - -# While loop starts -while num <= 5: # This loop will continue as long as num is less than or equal to 5 - print(num) # Print the current value of the number - num += 1 # This is equivalent to num = num + 1 -# End of the loop -``` - -## Homework help! - -To do what we did above with the list of names, you can also use a while loop! - - -```python -names = ['Anwita', 'Nicholas', 'Varada'] - -# i = 0 # Initialize a variable i to 0 -# while i < ___(names): # Loop continues as long as i is less than the length of the names list (The length is 3) -# print('Hello', names[i]) # Print the name at index i -# i += 1 -``` - -### Doubling using `while` loops - -This loop will continue as long as the number is less than or equal to 100 starting at 2 - - -```python -# Keep doubling until the number is greater than 100 -num = 2 # Start with 2 -while num <= 100: # This loop will continue as long as num is less than or equal to 100 - print(num) # Print the current value of the number - num = num * 2 # This is equivalent to num *= 2 -``` - -### JavaScript equivalent -Here is the same behavior in JavaScript (prints to console): - - -```javascript -%%js -// Start with 2, keep doubling while <= 100 -let num = 2; -while (num <= 100) { - console.log(num); - num = num * 2; // or num *= 2 for shorter syntax -} -``` - -### `while` Popcorn Hack: countdown with a safety counter - -This `while` loop counts down from 10 to 1. Let's built a countdown to blast off with `while` loops! - - -```python -n = 10 -# while n > 0: -# print('T minus', n) -# n -= 1 # same as n = n - 1 - -#print('Blast off!') -``` - -## JavaScript vs. Python: `while` Loops -### 3) `while` loop (indefinite) -Python: repeat until condition false -```python -count = 1 -while count <= 5: - print(count) - count += 1 -``` -JavaScript: similar structure, but different syntax -```javascript -let count = 1; -while (count <= 5) { - console.log(count); - count += 1; -} -``` -### `while` loop in arrays/lists - -```python -names = ['Anwita', 'Nicholas', 'Varada'] -i = 0 -while i < len(names): - print('Hello', names[i]) - i += 1 - -``` - -```javascript -let names = ['Anwita', 'Nicholas', 'Varada']; -let i = 0; -while (i < names.length) { - console.log('Hello ' + names[i]); - i++; -} -``` - - -## Control flow inside loops: break and continue - -- `break` exits the entire loop immediately. -- `continue` skips the rest of the current iteration and goes to the next one. - -Example: print numbers 1–6 but skip 3 and stop when you reach 5. - - -```python -for n in range(1, 8): # numbers 1 to 8 - if n == 3: # when n is 3 - continue # skip number 3 - if n == 6: # when n is 6 - break # stop the whole loop at 6 - print(n) # what number is printed - -# Output: 1 -# 2 -# 4 -# 5 -``` - -### 4) `break` and `continue` -Python: -```python -for i in range(1, 6): - if i == 3: - continue # skip the rest of this iteration - if i == 5: - break # exit the loop early - print(i) -``` -JavaScript: -```javascript -for (let i = 1; i <= 5; i++) { - if (i === 3) continue; - if (i === 5) break; - console.log(i); -} -``` - -## Iterations Game — Multiple Choice (JavaScript / Python) -Choose a language, read the snippet, and pick the correct output or behavior. You will get immediate "Correct" or "Incorrect" feedback and an explanation. -
-
- - -
- -
-

Question 1

-

-    
-
- - - -
-

-
-
-
- - - - -## Check for Understanding - -**Question:** What will this code output? -```python -for i in range(3): - print("hi") -``` - -- A) `hi` -- B) `hi hi` -- C) `hi hi hi` -- D) Nothing - -**Correct Answer:** C - diff --git a/_notebooks/2025-09-26-math-expressions-collaborators_IPYNB_2_.md b/_notebooks/2025-09-26-math-expressions-collaborators_IPYNB_2_.md deleted file mode 100644 index 153ccf181c..0000000000 --- a/_notebooks/2025-09-26-math-expressions-collaborators_IPYNB_2_.md +++ /dev/null @@ -1,739 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Mathematical-Expressions'] -lesson_language: Python -lesson_topic: Mathematical-Expressions -lesson_part: reference -lesson_type: lesson -title: 3.3 Math Expressions -permalink: /csp/big-idea-3/p3/math-expressions/lesson -Authors: Nitya R, Brandon C, Alice L ---- - -
- -
-
-
-

3.3 — Math Expressions

-

Sequencing, Selection, Iteration, and Arithmetic Operations.

-
-
- - - -
-
-

Learning Objectives

-
    -
  • Express an algorithm that uses sequencing without a programming language.
  • -
  • Represent a step-by-step algorithmic process using sequential code statements.
  • -
  • Evaluate expressions that use arithmetic operators.
  • -
-
- -
-

What is an Algorithm?

-

An algorithm is a finite set of instructions that accomplish a specific task.

-

Key concepts:

-
    -
  • Sequencing: first step → second step → third step
  • -
  • Selection: decision-making (yes/no) → different steps depending on outcome
  • -
  • Iteration: repeat steps until a condition is met
  • -
-
- - - -
-

Example Algorithm: Count Even Numbers in a List

-
    -
  1. Set count ← 0
  2. -
  3. Get next number from the user
  4. -
  5. check if its even, if yes then count ← count + 1
  6. -
  7. If more numbers in list, go back to Step 2
  8. -
  9. Display count
  10. -
-

Sequencing: Steps 1 → 2 → 3 → 4 → 5

-

Selection: Step 3 (even or odd decision)

-

Iteration: Step 4 (loop until list exhausted)

-
- -
-

💡 Hack 1: Identify Sequencing, Selection, and Iteration

-

Analyze the following algorithm and identify which parts demonstrate sequencing, selection, and iteration:

-
    -
  1. Set item to the number to search for
  2. -
  3. Get next number in the list
  4. -
  5. If number = item, display “item found”
  6. -
  7. If there are more numbers in the list, go back to Step 2
  8. -
  9. Display “item not found”
  10. -
-
- -
-

Code Statements & Expressions

-

Store values in variables and compute results:

-
Grade ← 82
-highScore ← currentScore
-Name ← firstName + lastName
-Average ← calcAverage(10, 20, 30)
-
- -
-

Hack 2: Predict the Output

-

Identify what is displayed after running the following code segment:

-
num1 ← 2
-num2 ← 4
-num3 ← 5
-num1 ← num2 + num3
-num3 ← num1 + 5
-num2 ← (num1 + num3) / 5
-DISPLAY(num1)
-DISPLAY(num2)
-DISPLAY(num3)
- -

Hints / Thought Process:

-
    -
  • Step 1: Track how num1, num2, and num3 change at each line.
  • -
  • Step 2: Apply arithmetic operations carefully and in order.
  • -
  • Step 3: Remember that assignment updates the variable immediately.
  • -
-
- -
-

Arithmetic Operators & Order of Operations

-
-
-
+  addition (a + b, grade + 10)
--  subtraction (a - b, 100 - pointsDeducted)
-*  multiplication (a * b, base * height)
-/  division  (a / b, sum / 28)
-MOD  modulus (remainder) (a MOD b, 17 MOD 2)
-

note: Python MOD is %

-
-
-
- -
-

Hack 3: Practice

-

Predict the value of result after executing the code:

-
num1 ← 40
-num2 ← num1 / 2
-num3 ← 5 * num2 + 3
-result ← num2 MOD 3 * num1 + 4 - num3 / 2
-DISPLAY(result)
-
- -
-
- - - - -
- - - - - - - - -
-
-

🎮 Flappy Math — Expressions

-

Fly through 10 gates. Each gate asks a tiny math/code question. Answer right to keep going! Click game or press F for fullscreen.

-
- -
-
- - - -
-
Score: 0 / 10
-
- - - -
-
Press Space / click / tap to flap • F to toggle fullscreen
-
- - - -
-

Checkpoint

-

- - - - - -
- - - -
-
-
- - - -
-

You Win!

-

-
- - -
-
-
- - -
-
-

Click / tap to flap. Pass a pipe ➜ answer a quick expression question. Get to 10!

-

Tip: please don't use full screen! PRESS SPACE BAR FIRST, THEN CLICK START TO START THE GAME

-
-
-
-
-
- - - - - diff --git a/_notebooks/2025-09-27-strings_zombies_IPYNB_2_.md b/_notebooks/2025-09-27-strings_zombies_IPYNB_2_.md deleted file mode 100644 index 346f3f9313..0000000000 --- a/_notebooks/2025-09-27-strings_zombies_IPYNB_2_.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Strings'] -lesson_language: Python -lesson_topic: Strings -lesson_part: interactive -lesson_type: lesson -title: 3.4 Strings -description: This page will teach you about strings in programming. -permalink: /csp/strings/zombies -breadcrumb: True -Author: Ethan Patel, Tanay Paranjpe, Neil Manjrekar ---- - -## Strings ---- -### What are Strings? -- A **string** is a sequence of characters **(letters, numbers, symbols, spaces)** enclosed in quotes. -##### Examples: - -- ``"Hello"`` - -- ``"12345"`` - -- ``"Good Morning"`` - -### **Python** - - -```python -myName = "Neil" # <-- Here, we define a string variable called myName and assign it the value "Aneesh". -myNameType = type(myName).__name__ # <-- Here, we use the type() function to get the data type of myName, which is str (string). The __name__ attribute gives us the name of the type as a string. - -print(f"{myName} is a {myNameType} data type.") # <-- This line prints out the value of myName and its data type in a formatted string. -``` - -### **JavaScript** - - -```javascript -%%javascript - -let myName = "Tanay"; // <-- Define a string variable called myName and assign it "Tanay" -let myNameType = typeof myName; // <-- typeof gives the data type (string) - -console.log(`${myName} is a ${myNameType} data type.`); // Makes the two variables into a sentence - -``` - - - - - -### Defining Strings -- In most programming languages, you can make a string with either single (') or double (") quotes: - -### **Python** - - -```python -word = "hello" # <-- Here, we use double quotes instead of single quotes -sentence = 'Python is fun!' # <-- Here, we use single quotes instead of double quotes -# Both are valid ways to define strings in Python -multiline = """This is -a multi-line -string.""" # <-- Triple quotes allow for multi-line strings -print(word) -print(sentence) -print(multiline) -``` - -### **JavaScript** - - -```javascript -%%javascript - -let word = "hello" // Single quotes -let sentence = 'JavaScript is better than Python!' // Double quotes -// Similar to Python, it does not matter whether you use double or single quotes -let multiLine = `Multiline strings -are -very -cool!` // Use ` in JavaScript for multi line quotes - -console.log(word) -console.log(sentence) -console.log(multiLine) -``` - - - - - -## Common String Operations ---- - -### **Python** - - -```python -name = "Aneesh" - -print(name.upper()) # "ANEESH" -print(name.lower()) # "aneesh" -print(len(name)) # 6 -print(name[0]) # "A" (first character) -print(name[-1]) # "h" (last character) -print(name[1:3]) # "ne" (slice) -``` - -### **JavaScript** - - -```javascript -%%javascript - -let food = "Pizza" - -console.log(food.toUpperCase()); // prints pizza in all upper case -console.log(food.toLowerCase()); // prints pizza in all lower case -console.log(food.length) // prints the number of characters in the word pizza -console.log(food[0]); // prints the first character in pizza -console.log(food[food.length - 1]); // prints the last character in pizza -console.log(food.substring(1,4)); // substring slices the word to get a chunk, the index/numbers are assigned to letters -// pizza = 01234 -``` - - - - - -## Concatenation (Combining Strings) ---- - -### **Python** - - -```python -first = "Hello" -second = "World" - -print(first + " " + second) # "Hello World" -print(first + ", " + second + "!") # "Hello, World!" -print("{} {}".format(first, second)) # "Hello World" (str.format) -print(f"{first}, {second}!") # "Hello, World!" (f-string) -``` - -### **JavaScript** - - -```javascript -%%javascript - -let first = "Goodbye"; -let second = "Universe"; - -// Using concat() -console.log(first.concat(" ", second)); // uses concat to combine strings -console.log(first.concat(", ", second, "!")); // also uses concat but adds a ! at the end -console.log(second.concat(first)); // can use concat to combine strings any way - -``` - - - - - -### Practice Questions! - -1. What will the command **concat** do in JavaScript? -2. Is the **substring** command used in? -3. How do you do **multiline** strings in JavaScript? - ---- -### MCQ -Go as fast as you can to try to win! - -[Click here for qualifying](https://whitelunarium.github.io/Aneesh_2026/mcq_strings) - -[Click here for final](https://whitelunarium.github.io/Aneesh_2026/mcq_strings2) diff --git a/_notebooks/2025-09-29-functions_tinkerers_js_lesson_IPYNB_2_.md b/_notebooks/2025-09-29-functions_tinkerers_js_lesson_IPYNB_2_.md deleted file mode 100644 index 7634375480..0000000000 --- a/_notebooks/2025-09-29-functions_tinkerers_js_lesson_IPYNB_2_.md +++ /dev/null @@ -1,851 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'Functions'] -lesson_language: JavaScript -lesson_topic: Functions -lesson_part: interactive -lesson_type: lesson -toc: False -title: Functions -description: This lesson explains JavaScript functions. -author: Tinkerers - Anish G, James B, Vihaan B ---- - - - - - - - - - - - - - - - - - - - - -
RoleName
📋 Scrum MasterAnish Gupta
💻 ScrummerJames Blazek
💻 ScummerVihaan Budhraja
- -
- -

Setup

-Copy the homework file into your personal repository by doing this: - -1. Open the `Open-Coding-Society/pages` repo in one VSCode window and your own `portfolio` repo in the other -2. Drag and drop `2025-09-29-functions_tinkerers_js_hw.ipynb` from pages to your own repo. It is in `_notebooks/CSSE/JavaScriptLessons/Functions`. - -Alternatively, you can use wget: - -```bash -# First cd to the base of your repo - -mkdir -p _notebooks/CSSE/JavascriptLessons/Functions - -wget -O _notebooks/CSSE/JavascriptLessons/Functions/2025-09-29-functions_js_tinkerers_hw "https://raw.githubusercontent.com/Open-Coding-Society/pages/main/_notebooks/CSSE/JavaScriptLessons/Functions/2025-09-29-functions_js_tinkerers_hw.ipynb" -``` - - -Your homework is now copied into your personal repo! This notebook also contains popcorn hacks #1 and #2. - - - -

What are functions?

- - -> Functions in programming are modular units of code designed to perform specific tasks. They encapsulate a set of instructions, allowing for code reuse and organization. - GeeksForGeeks - -Functions allow you to take a piece of code, and almost put it into a box so you can reuse it a lot of times. It also let you modularize code. For example, let's look at the code below. - - -```python -%%html - -
-

Program Output

-

-
- - -``` - - - -
-

Program Output

-

-
- - - - - -This code, while it works, has a lot of code that is reused. We can modularize this code as shown below. - - -```python -%%html - -
-

Program Output

-

-
- - - -``` - - - -
-

Program Output

-

-
- - - - - - - -

Try it out for yourself!

- -
- - -```python -%%html - -
-

Program Output

-

- -
- - - - - -
- - - -``` - - - -
-

Program Output

-

- -
- - - - - -
- - - - - - - - - - -

-
-flowchart LR - A["Inputs: Alice, 16"] --> B["greet() function"] - B --> C["Output: Hello, Alice (16)!"] - A2[Inputs: Bob, 999999999] --> B - B --> C2["Output: Hello, Bob (999999999)!"] - A3[Inputs: Charlie, 1] --> B - B --> C3["Output: Hello, Charlie (1)!"] - A4[Inputs: myname, myage] --> B - B --> C4["Output: Hello, [myname] ([myage])!"] - - classDef func fill:#4169e1,stroke:#333,stroke-width:2px,color:#ffffff; - class B func; -
- -
- -

Defining Functions & Function Syntax

- -The code to create a function is as follows: - -![](https://lh3.googleusercontent.com/proxy/8HuWupeaffPfTzROp_TE2Y4MlniKWW3BoSvSc3oJ35aCJHQbZR0_lmdvqF_bEVNEXzzG53puMLbuIzD1tcH5tfGfRx7sOMAJL_K07adSUML6FbJYOkxSF1pFGoMgXZEtmlxXC-Lq) - -Let's look at the below code. - -``` -function add(a, b) { - return a + b; -} -``` - -`add` is the name of the function. A common JavaScript convention is to use camelCase. Function names are usually verbs- like calculateSum(), drawText(), startGame(), etc. because they do something. - -`a` and `b` are parameters. You aren't fixed to 2 parameters: you can have one, three, zero, or five hundred (if you want to for some reason). -Parameters are like the input to a function: information that the function takes in to be proccessed. - -(Side note: Parameters are the variables listed in the function definition. Arguments are the actual values you pass when calling the function.) - -Next, we use curly braces { } to represent that "hey, the code for **this function specifically** starts/ends here!" - -The `return` keyword is the output of a function: Mozilla says that -> The return statement ends function execution and specifies a value to be returned to the function caller. - -Here's an example: - -```js -function add(a, b) { - return a + b; -} - -let result = add(5, 6); -console.log(result); // Logs 11 -``` - - - -Let's do a practice: what will the below function output and why? - -```js -function add(a, b){ - console.log(a+b); -} - -let result = add(5, 6); -console.log(result); -``` - -
- - View solution - - - The first log to the console will display 11. The second log will say undefined. - This is because the function is not returning anything, and result is being set to a value that does not exist. - -
- - -

Example of Returning in Word Game

- - -``` - -function wrapText(text, maxWidth) { - const words = text.split(' '); - const lines = []; - let currentLine = words[0]; - - for (let i = 1; i < words.length; i++) { - const word = words[i]; - const width = wordCtx.measureText(currentLine + ' ' + word).width; - if (width < maxWidth) { - currentLine += ' ' + word; - } else { - lines.push(currentLine); - currentLine = word; - } - } - lines.push(currentLine); // Add the last line - return lines; -} - -``` - -
- -

🍿 POPCORN HACK NO. 1 🍿

- -Let's start making our own functions :) -Head over to `2025-09-29-functions_tinkerers_js_hw.ipynb` to do the popcorn hack. -Didn't download it yet? Check the **setup section** at the top of this lesson. - -
- - -

More Function Use Cases

- -![](https://media.geeksforgeeks.org/wp-content/uploads/20250721183631453591/Why-Use-Functions__.webp) - - -> Functions can be used to reuse code. - -Let's say I have a function that I need to call multiple times. For example, in Word Game, there is a function called drawText() with this code: - -```js -function drawText(text) { - wordCtx.clearRect(0, 0, wordCanvas.width, wordCanvas.height); - wordCtx.font = '24px "Times New Roman", Times, serif'; - wordCtx.fillStyle = '#dededeff'; - wordCtx.textAlign = 'center'; - - const maxWidth = wordCanvas.width - 20; // Leave some padding - const lineHeight = 30; // Line height for wrapped text - const lines = wrapText(text, maxWidth); - - const startY = (wordCanvas.height - lines.length * lineHeight) / 2; // Center vertically - lines.forEach((line, index) => { - wordCtx.fillText(line, wordCanvas.width / 2, startY + index * lineHeight); - }); -} -``` - -This function is called *twice* in wordgame.md: once when the game starts and once to clear the canvas after done typing. - -This keeps us from having to write this code twice. Instead, we can define it ONCE and call it whenever we want: if we wanted to call it 67 times for some reason, instead of copy pasting the code 67 times, we can just call drawText() whenever needed. - -

Functions for Abstraction & Modularity

- -ABSTRACTION - -> Functions in Programming allow programmers to abstract the details of a particular operation. Instead of dealing with the entire implementation, a programmer can use a function with a clear interface, relying on its functionality without needing to understand the internal complexities. *Functions hide the details of their operation, allowing the programmer to think at a higher level.* - GeeksForGeeks - -MODULARITY - -Using word game as an example, instead of implementing the whole program, we can tackle the steps one by one. These functions are: - -- `drawText(text)` – Draws the prompt text centered on the canvas -- `wrapText(text, maxWidth)` – Splits text into lines that fit within `maxWidth` -- `drawUserText(prompt, input)` – Draws the prompt and user input, highlighting correct/incorrect chars and showing the caret -- `updateStats(prompt, input, startTime)` – Updates WPM and accuracy stats -- `finishGame(prompt, input, startTime)` – Handles game end, calculates mistakes, and shows finish overlay -- `startGame()` – Starts a new game, picks a prompt, and sets up key input handling -- `setProgress(percent)` – Updates the progress bar width and text -- `updateProgress(prompt, input)` – Computes progress from input length and updates the bar -- `createOptionButton(text, val)` – Creates a modal button to select string length -- `escHandler(ev)` – Handles Escape key to close the options menu - -
- - - -

Scope

- -Scope is a common pitfall for those learning functions. Press the button below to run the following code snippet. - - -```python -%%html - - - -

-

- - - - -``` - - - - - -

-

- - - - - - - - -

This is because of SCOPE!

- -Essentially, we have things called -- **Local** variables, and -- **Global** variables - -Variables defined within a JavaScript function become LOCAL TO THAT FUNCTION. - -If I define a variable called `x` inside of a function, it can only be accessed within that function. Even if we use `var`, it will remain stuck inside that function. You should avoid polluting the global scope, but if you absolutely have to (which you don't), you can write something similar to the below code: - -``` -function makeGlobal() { - let localVar = "I am local"; - window.globalVar = localVar; // now accessible globally -} - -makeGlobal(); -console.log(globalVar); // Outputs "I am local" -``` - -
- - - -

🍿 POPCORN HACK NO. 2 🍿

- -Let's practice using functions! - -Head over to the homework notebook to do the popcorn hack. - -
- - - -

Recursion

- -We won't spend too much time on this, but we'll just do an overview of what recursion is. - -Recursion is where a function continuously calls itself. View the example below for a factorial recursion function: - -```js -function factorial(n) { - // If n is 0 or 1, the factorial is 1. - // This condition prevents infinite recursion. - if (n === 0 || n === 1) { - return 1; - } - // Recursive case: the function calls itself with a smaller value of n. - else { - return n * factorial(n - 1); - } -} -``` - -If we run factorial(5), it will do: -- factorial(5) = 5 * factorial(4), which calls: -- factorial(4) = 4 * factorial(3) -- factorial(3) = 3 * factorial(2) -- factorial(2) = 2 * factorial (1) -- factorial(1) = 1 - -### Demo - - -```python -%%html - -

Factorial Recursion Demo

- - - - -
Your results will appear here.
- - -``` - - - - - - -

Factorial Rescursion Demo

- - - - -
Your results will appear here.
- - - - - - - -
- - - -

Arrow Functions (if time)

- -Arrow functions are a more concise way to write functions. Use case scenario: - - - -```python -%%html - -

Result

- -
- - -``` - - - -

Result

- -
- - - - - - - -

HOMEWORK 😈

- - -The homework for functions is located at `2025-09-29-functions_tinkerers_js_hw.ipynb`. -Make sure to attempt all the challenges and turn in your notebook URL to the link on that page. diff --git a/_notebooks/2025-09-30-algorithmic-efficiency_IPYNB_2_.md b/_notebooks/2025-09-30-algorithmic-efficiency_IPYNB_2_.md deleted file mode 100644 index 8dae55e928..0000000000 --- a/_notebooks/2025-09-30-algorithmic-efficiency_IPYNB_2_.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Algorithmic-Efficiency'] -lesson_language: Python -lesson_topic: Algorithmic-Efficiency -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.17 Algorithmic Efficiency -description: Learn about algorithms and how they can be more or less efficient -permalink: /peppa-maze/algorithmic-efficiency ---- - -## Computer Science Principles Lesson 3.17 - Algorithmic Efficiency - -We all love video games - getting to do things that you could never in real life. Some games are simple, 2D games with basic mechanics. Others have complex 3D graphics with ray-tracing, collisions, and a whole bunch of game mechanics that are hard to wrap your head around! Have you ever wondered how these games are able to do so much, so fast? While processing power is a part of it, one of the biggest factors is completely in the hands of the developer - algorithmic efficiency. - -### Nice Yap, but What Does "Algorithmic Efficiency" Even Mean? - -Okay, so this "algorithmic efficiency" thing is important, but what even is it? - -To put it simply, algorithmic efficiency refers to the speed and memory usage of a computer algorithm, which is important to keep track of when coding. The quicker and less memory-intensive an algorithm is, the more efficient it is considered. - -### What's So Important About Algorithmic Efficiency? - -Considering the efficiency of algorithms is important in computer science because processing power and time are limited. It is much better to have an algorithm finish quickly while using little RAM then for it to take 10 minutes and a few fire extinguishers to get the task done! - -### How do We Measure Algorithmic Efficiency? - -Algorithmic efficiency is mainly dependent on time complexity and memory usage. Time complexity can be measured using Big-O Notation. Big-O notation is a representation of the average amount of extra steps a computer has to take for input as it grows. Big-O notation does not necessarily show the exact amount of steps a computer takes to complete an algorithm, but it gives a good estimate based on the average input. Memory usage is mostly dependent on time complexity, and can be derived from an algorithm's Big-O representation. You'll see some examples of Big-O notation later on in this lesson. - -### Example: Designing Algorithms and Measuring Their Efficiency Using Python - -Let's create an algorithm and see how algorithmically efficient it is using Big-O notation. - - -```python -# Define some simple variables -index = 0 -amount = 10 - -# The algorithm we'll be analyzing: -while index < amount: - print("I love Python!") - index += 1 -``` - -In this example, we repeat some code while the "index" variable is less than the "amount" variable. Each time, we increment "index" by 1. How algorithmically efficient is this algorithm? Let's use Big-O notation to show it: - -First, let's look at the outermost loop. The loop will execute "amount" times, so the computer will have to take one extra step for every extra value of "amount". The Big-O notation for this would be O(n), because the computer needs to take n steps for every n inputs, which in this case is the value of "amount". Because "print()" and "index += 1" are things that the computer can do in one step, they have O(1) time complexity (time complexity refers to how many steps a computer takes on average to complate an algorithm, which is what Big-O notation represents). All together, this algorithm has O(n) time complexity. - -### Example: Designing Algorithms and Measuring Their Efficiency Using Javascript - -Let's create an algorithm and see how algorithmically efficient it is using Big-O notation, however this time we'll use Javascript. - - -```javascript -%%js -// Define variables -const amount = 8; -let outerIndex = 0; -let innerIndex = 0; -let overallIndex = 0; - -// The algorithm we'll be analyzing: -while (outerIndex < amount) { //Outer loop - innerIndex = 0; - while (innerIndex < amount) { //Inner loop - overallIndex++; - console.log(`Iteration #${overallIndex}`); - innerIndex++; - } - outerIndex++; -} -``` - - - - - -This one is a little more complicated. The outer loop runs "amount" times, but so does the inner loop. This means that the whole thing runs "amout" times, "amount" times! In terms of Big-O notation, the outer loop has a time complexity of O(n), and within this loop, another loop of O(n) time complexity runs. To figure out the time complexity of the whole algorithm, we need to multiply the inner time complexity by the outer one. What we get is O(n * n), or O(n^2). So, this algorithm's time complexity is O(n^2). diff --git a/_notebooks/2025-09-30-lists_scratchers_lesson_IPYNB_2_.md b/_notebooks/2025-09-30-lists_scratchers_lesson_IPYNB_2_.md deleted file mode 100644 index b5eefac11b..0000000000 --- a/_notebooks/2025-09-30-lists_scratchers_lesson_IPYNB_2_.md +++ /dev/null @@ -1,234 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Lists'] -lesson_language: Python -lesson_topic: Lists -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.10 Lists -description: This is the comprehensive lesson for Big Idea 3.10, Lists. -permalink: /csp/big-idea-3/lists/p4/lesson ---- - -# AP Computer Science Principles - -## Big Idea 3.10: Lists - - -### What Are Lists? - -A list is a collection of data elements that are ordered and can be accessed by their position (index). Lists are fundamental data structures in programming that allow you to store and manipulate multiple values in a single variable. - -### Key Characteristics of Lists: - -- Ordered: Elements maintain their position -- Indexed: Each element has a numeric position (usually starting at 0 or 1) -- Mutable: Elements can be changed, added, or removed -- Can contain duplicates: The same value can appear multiple times - -### Real-World Examples: - -- A shopping list: ["milk", "eggs", "bread", "butter"] -- Test scores: [85, 92, 78, 95, 88] -- Daily temperatures: [72, 75, 68, 71, 73, 76, 74] - - - -## Creating Lists - - - - -```python -# List of integers -ages = [15, 16, 17, 15, 16] - -# List of strings -colors = ["red", "blue", "green", "red"] - -# List of mixed types -mixed = [42, "hello", 3.14, True] -``` - - -```python -// List (array) of integers -let ages = [15, 16, 17, 15, 16]; - -// List of strings -let colors = ["red", "blue", "green", "red"]; - -// List of mixed types -let mixed = [42, "hello", 3.14, true]; - -``` - -## Accessing List Elements - - - - - -```python -fruits = ["apple", "banana", "cherry", "date"] - -print(fruits[0]) # "apple" - first element -print(fruits[1]) # "banana" - second element -print(fruits[3]) # "date" - fourth element -print(fruits[-1]) # "date" - last element (Python only) -``` - -## Example 1 - -### Sum and Average -When working with numeric lists, two common operations are finding the total sum and the average (mean). -Concept: - -- Sum: Add all numbers together -- Average: Divide the sum by how many numbers there are - -### Sample Problem: -A teacher has test scores: [78, 85, 92, 88, 95] -Find the total points and average score. - - -```python -let scores = [78, 85, 92, 88, 95]; - -// Calculate sum -let total = 0; -for (let score of scores) { - total += score; -} - -console.log(`Total points: ${total}`); // 438 - -// Calculate average -let average = total / scores.length; -console.log(`Average score: ${average}`); // 87.6 -``` - - -```python -scores = [78, 85, 92, 88, 95] - -# Calculate sum -total = 0 -for score in scores: - total += score - -print(f"Total points: {total}") # 438 - -# Calculate average -average = total / len(scores) -print(f"Average score: {average}") # 87.6 -``` - -## Example 2: Counting Frequencies -Sometimes you need to count how many times each unique item appears in a list. This is called frequency counting. -### Concept: -Go through each item and keep track of how many times you've seen it using a dictionary (Python) or object (JavaScript). -### Sample Problem: -A survey asked students their favorite season: -["winter", "summer", "fall", "summer", "summer", "spring", "fall"] -Count how many students chose each season. - - -```python -seasons = ["winter", "summer", "fall", "summer", "summer", "spring", "fall"] - -# Create empty dictionary to store counts -frequency = {} - -# Count each item -for season in seasons: - if season in frequency: - frequency[season] += 1 - else: - frequency[season] = 1 - -print(frequency) -# Output: {'winter': 1, 'summer': 3, 'fall': 2, 'spring': 1} -``` - - -```python -let seasons = ["winter", "summer", "fall", "summer", "summer", "spring", "fall"]; - -// Create empty object to store counts -let frequency = {}; - -// Count each item -for (let season of seasons) { - if (frequency[season]) { - frequency[season]++; - } else { - frequency[season] = 1; - } -} - -console.log(frequency); -// Output: {winter: 1, summer: 3, fall: 2, spring: 1} -``` - -## Example 3: Filtering Lists -Filtering means creating a new list that contains only elements meeting certain criteria. -### Concept: -Check each element with a condition. If it passes, add it to the new list. -### Sample Problem: -A list contains ages: [12, 18, 15, 21, 17, 25, 14, 19] -Create a new list with only ages 18 and above (adults). - - -```python -ages = [12, 18, 15, 21, 17, 25, 14, 19] - -# Create empty list for adults -adults = [] - -# Check each age -for age in ages: - if age >= 18: - adults.append(age) - -print(adults) # [18, 21, 25, 19] -``` - - -```python -ages = [12, 18, 15, 21, 17, 25, 14, 19] - -# Create empty list for adults -adults = [] - -# Check each age -for age in ages: - if age >= 18: - adults.append(age) - -print(adults) # [18, 21, 25, 19] -``` - -## Common Problems to Avoid - -- ❌ Off-by-one errors: Remember indexing starts at 0 -- ❌ Index out of range: Don't access list[5] if the list has only 4 elements -- ❌ Modifying list while iterating: Can cause unexpected behavior -- ❌ Forgetting to initialize variables: Set total = 0 before summing - -- ✓ Use descriptive names: student_names instead of list1 -- ✓ Check for empty lists: Before accessing elements -- ✓ Test edge cases: Empty lists, single elements, all same values - -## Summary - Lists are essential for storing and manipulating collections of data. Through them, it is easy to access, create, and filter lists of data. -### Understanding and Mastering These Objectives is Key to Your Success in AP Computer Science Principles: - -- Accessing elements by index -- Computing sum and average -- Counting frequency of items -- Filtering based on conditions -- Searching for specific values diff --git a/_notebooks/2025-10-02-Algorithms-Lesson-SyntaxTerrors_IPYNB_2_.md b/_notebooks/2025-10-02-Algorithms-Lesson-SyntaxTerrors_IPYNB_2_.md deleted file mode 100644 index c5ce39609d..0000000000 --- a/_notebooks/2025-10-02-Algorithms-Lesson-SyntaxTerrors_IPYNB_2_.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Algorithms'] -lesson_language: Python -lesson_topic: Algorithms -lesson_part: reference -lesson_type: lesson -toc: True -comments: False -tailwind: True -infoGraph: algorithms -title: 3.9 Algorithms -description: Understanding Algorithms in Python and JavaScript -permalink: /csp/big-idea-three/algorithms/lesson/p3/syntaxterrors -author: Hope F ---- - -## 3.9 Algorithms - Syntax Terrors - -{%- include tailwind/tabs.html -%} diff --git a/_notebooks/2025-10-02-conditionals_constellators_lesson_IPYNB_2_.md b/_notebooks/2025-10-02-conditionals_constellators_lesson_IPYNB_2_.md deleted file mode 100644 index fb9065cde9..0000000000 --- a/_notebooks/2025-10-02-conditionals_constellators_lesson_IPYNB_2_.md +++ /dev/null @@ -1,193 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'Conditions'] -lesson_language: JavaScript -lesson_topic: Conditions -lesson_part: reference -lesson_type: lesson -title: Conditions -description: This is the JavaScript Conditionals Lesson, taught by the Constellators. -permalink: /csse/javascript/constellators/conditionals-lesson -author: Constellators - Adya S, Niharika B, Salma Z, Anika S, Sophie H ---- - - - -Presented by the -

CONSTELLATORS

- -
- -## **Conditionals** - -In JavaScript, conditionals are essential aspects of programming that are used to control the flow of code based on whether certain conditions are met. They're necessary to make decisions within game code and run different actions based on different conditions. - -TO FIND THIS LESSON (pages repository): Search -> "Constellators - Conditionals Lesson" -> Select the most recent one (should be 10/02/25) - -### What are Conditionals? -- Allows the execution of different blocks of code based on whether a specified condition evaluates to true or false -- This enables programs to make decisions and respond dynamically to various situations -- Analogy: depending on the weather, you either bring outside an umbrella (rain) or a hat (sunny) -- Types: if, if-else, else if, (+switch) - -
- -### Types of Conditionals - -#### 1. If - -- Executes code if a given condition is true - -Example: -```js -if (condition) { - // Code to execute if condition is true -} -``` - -#### 2. If ... Else - -- Basically a true/false --> executes one thing if the condition is true, and a different thing if the condition is false - -Else statement: -- Executes a block of code only if the preceding if (or else if) condition evaluates to false. -- It must always follow an if or else if statement. -- No condition - -Example: -```js -if (condition) { - // Code to execute if condition is true -} else { - // Code to execute if condition is false -} -``` - -#### 3. Else ... If - -- JavaScript's equivalent of elif -- Executes a block of code if the preceding if condition (or any preceding else if conditions) evaluates to false, AND its own specified condition evaluates to true. -- Only the first true condition's block is executed -- Must always follow an if or another else if statement - -Example: -```js -if (condition1) { - // Code to execute if condition1 is true - } else if (condition2) { - // Code to execute if condition2 is true - } else { - // Code to execute if none of the above conditions are true - } -``` - -#### 4. Switch - -- Compares multiple possible outcomes -- More complex than just true/false - -Example: -```js -switch (expression) { - case value1: - // Code to execute if expression matches value1 - break; - case value2: - // Code to execute if expression matches value2 - break; - default: - // Code to execute if no match is found - } -``` - -#### 5. Nested If (Nested Conditionals) - -- An if statement within another conditional. -- Analogy: if-else statement to determine whether it's raining. If it's raining, check if you have an umbrella. - -Example: -```js -if (condition1) { - if (extracondition1) { - // Code to execute if both condition 1 and extra condition are true - } - else { - // Code to execute if condition 1 is true, but extra condition is false - } -} else { - // Code to execute if condition 1 is false -} -``` - -
- -**Summary** - -“if” checks a condition -
“else if" checks another condition if the previous ones were false -
“else” runs if none of the above conditions were true. - -### Popcorn Hack 1 - -Go to the HW file that you can access [here](https://github.com/AdyaShipekar/code-constellations/blob/main/_notebooks/CSSE/JavaScriptLessons/Conditionals/2025-10-02-conditionals_constellators_js_hw.ipynb). Download to your student/portfolio repository and complete Popcorn Hack 1. - -### Examples of Conditionals in OOP Breakout - -To Recap: A **conditional** in code is any statement where the program checks a condition (using `if, else, or else if ` statements) to decide what to do next. Throughout the OOP BREAKOUT game, there are many examples of conditionals and conditional expressions that help the game run smoothly. - -In our OOP Breakout game, you can consider the conditionals the rules of the game world! They let the code make decisions. - -If the ball hits a wall → it bounces back. -If the ball hits a brick → the brick disappears. -If the ball hits the bottom → a life is lost. -Else (if none of those things happen) → the ball just keeps moving. - -**Inside the update() method for the ball:** - -```js -update(canvasWidth, canvasHeight) { -// Wall collision (left/right) -if (this.x + this.dx > canvasWidth - this.radius || this.x + this.dx < this.radius) { -this.dx = -this.dx; -} -// Top -if (this.y + this.dy < this.radius) { - this.dy = -this.dy; - } -this.x += this.dx; -this.y += this.dy; -} -``` - -**Explanation:** - -First conditional: ```if (this.x + this.dx > canvasWidth - this.radius || this.x + this.dx < this.radius)``` -- Checks if the ball is about to hit the left or right wall! -- If true, the ball bounces back by flipping its horizontal direction (```this.dx = -this.dx```). - -Second conditional: ```if (this.y + this.dy < this.radius) ``` -- Checks if the ball is about to hit the top wall! -- If true, it flips the vertical direction (```this.dy = -this.dy```). - -Without these if statements, the ball would fly off the screen forever. The conditionals keep the ball bouncing around, making the game actually playable! - -### Popcorn Hack 2 - -Go to the HW file from before and complete Popcorn Hack 2. - -### Homework - -Complete the homework and submit to [this form](https://docs.google.com/forms/d/e/1FAIpQLSccjujB0DqCnCy5mOE2r4Py8cYuvzmyBk9X-gWSn8XUNQvlDw/viewform?usp=header). - diff --git a/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md b/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md deleted file mode 100644 index 0dbdc9fc51..0000000000 --- a/_notebooks/2025-10-08-calling_procedures_remakers_lesson_IPYNB_2_.md +++ /dev/null @@ -1,263 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Calling-Procedures'] -lesson_language: Python -lesson_topic: Calling-Procedures -lesson_part: interactive -lesson_type: lesson -toc: True -codemirror: True -challenge_submit: True -comments: False -title: 3.12 Calling Procedures -description: 3.12 Calling Procedures -permalink: /csp/big-idea-3/calling-procedures/p4/lesson -author: Samanvi Yachareni, Joan Kim, Ainsley Albert -date: 2026-09-16 ---- - -### 3.12 Calling Procedures - -Every time you send a text message, your phone encodes the characters, transmits a wireless signal to a cell tower, and routes it to your friend. You don’t route network packets by hand — you just press send. That’s calling a procedure: the steps are saved, and you run them whenever you need them. - -#### What is calling a procedure? -A procedure (a function in Python) is a named set of re-usable code instructions. - -- You can call a procedure multiple times with different input values without having to rewrite it -- Different from defining the procedure: defining is creating it, calling is using it -- Calling allows you to run the same set of instructions whenever you need them without rewriting the lines of code. -#### Passing Inputs (Parameters) -You can make procedures more flexible by giving them parameters—input variables that hold data passed into the procedure when you call it. - -- Parameters act as temporary placeholders inside the procedure definition. -- Arguments are the actual values you send into the procedure when you call it. -This allows a single procedure to run the same set of instructions on completely different data without rewriting the code. - -Python Example: - -- Use def to define the function/procedure -- To call a procedure write the name of the procedure followed by parenthesis, and variables if included - -``` -# 1. DEFINE the procedure with a parameter (variable input) -def send_notification(username): - print("New message for " + username + "!") - -# 2. CALL the procedure passing different inputs -send_notification("Joan") -``` - -#### Calling Procedures Inside Procedures (Decomposition) -In computer science, large problems are broken down into smaller steps—a process called decomposition. You can call a helper procedure inside an outer procedure to handle a specific part of a task. Each step can become its own procedure, and one procedure can call another one. This allows programs to become easier to read, use, and debug. - -Python Example: - -``` -# Helper procedure: Calculates the final price with sales tax -def calculate_tax(price): - return price * 1.07 - -# Outer procedure: Handles the checkout process -def checkout(item_name, base_price): - total = calculate_tax(base_price) # Calling the helper procedure - print("Purchased " + item_name + " for $" + str(total)) - -# Execution starts here -checkout("Sneakers", 80.0) -``` - -#### Key Takeaways - -- Defining vs. Calling: Defining a procedure (def) creates the instructions; calling a procedure using its name with parentheses () actually executes them. -- Reusability: Calling procedures allows you to run the same code multiple times throughout your program without retyping it. -- Decomposition: Breaking complex tasks into smaller, manageable steps makes code easier to read, debug, and maintain. -- Helper Procedures: Outer procedures can call smaller helper procedures to handle specific sub-tasks and combine the results. -#### 1. LxD Cycle Process -**Empathize:** I noticed students were copy-pasting repetitive blocks of code throughout their Python scripts rather than writing modular functions. This made their code cluttered, difficult to debug, and hard to update. - -**Define:** - -- POV: AP CSP students need a clear way to practice writing and calling Python procedures so they can eliminate code duplication and organize programs logically. -- Learning Goal: Students will define procedures with parameters and call helper procedures within outer functions using Python. -**Ideate:** - -- HMW Question: How might we teach procedural decomposition and calling syntax in under 2 minutes so students can quickly jump to hands-on execution? -- Activity: A quick code-refactoring challenge where students convert duplicate print/math statements into a modular function with helper procedures. -**Prototype & Test:** During peer feedback, my team mentioned that the original reading material was too long and wordy. I streamlined the explanation down to core bullet points and replaced the open-ended coding task with two runnable code challenges. - -#### 2. Lesson Plan - -- **Learning Objective:** Define a Python procedure with parameters, call it using arguments, and utilize helper procedures to decompose tasks. -- **Success Criteria:** You can identify the difference between defining and calling a function, pass parameters correctly, and execute a helper procedure inside an outer procedure in the code runner. -#### 3. Hacks & Practice Tasks - -#### Popcorn Hack (In-Class Code Runner) -Task: The code below prints receipt lines manually. Refactor it by defining a procedure apply_discount(price) that takes a price, subtracts $5, and returns the new price. Then call it inside print_receipt. - -{% capture popcorn_challenge %} -Refactor the receipt code by defining an `apply_discount(price)` helper procedure and calling it inside `print_receipt`. -{% endcapture %} - -{% capture popcorn_code %} -# TODO: Define the apply_discount(price) helper procedure here - -def print_receipt(item, original_price): - # TODO: Call apply_discount here to get the final_price - final_price = original_price - print("Item: " + item + " | Final Price: $" + str(final_price)) - -# Test your code -print_receipt("Game Controller", 60.0) -{% endcapture %} - -{% include runners/code.html runner_id="procedures-popcorn" language="python" challenge=popcorn_challenge code=popcorn_code %} - -#### Homework Hack (Code Runner Challenge) -Task: Refactor the messy code below. - -1. Create a helper procedure is_passing(score) that returns True if score >= 70, and False otherwise. -2. Create an outer procedure evaluate_student(name, score) that calls is_passing(score). -3. If passing, print "| Status: Passed". Otherwise, print "| Status: Needs Review". -4. Call evaluate_student twice with different values. - -{% capture homework_challenge %} -Create a helper procedure `is_passing(score)` and an outer procedure `evaluate_student(name, score)` that calls it twice with different values. -{% endcapture %} - -{% capture homework_code %} -# TODO: Write your helper procedure 'is_passing' here - -# TODO: Write your outer procedure 'evaluate_student' here - -# TODO: Call evaluate_student twice below -{% endcapture %} - -{% include runners/code.html runner_id="procedures-homework" language="python" challenge=homework_challenge code=homework_code %} - -#### 4. Grading Plan (1 Point Total) -Classroom Rubric - -- 0.2 points: Popcorn Completion: Student successfully defined apply_discount, integrated it into print_receipt, and ran the cell cleanly using %%python. -- 0.8 points: Homework Completion -- 0.3 Parameter & Procedure Definition: Correctly uses def with appropriate parameters for both procedures. -- 0.3 Helper Calling Logic: Calls is_passing inside evaluate_student to handle the conditional check. -- 0.2 Execution & Outputs: Calls the outer procedure twice with different inputs and produces correct status outputs. -#### Quick Validation Checklist -[ ] Present: %%python and UI_RUNNER headers in code blocks. -[ ] Present: Helper procedure called inside the main procedure. -[ ] Absent: Hardcoded repetitive logic or global variables outside of procedures. - -#### 5. Lesson Revisions & Feedback Evidence -**Feedback Received:** Peer reviewers noted that the original lesson was dense, taking over 5 minutes to read, and lacked interactive execution elements on the page. - -**Revision Made:** Reduced explanation text to three bullet points, replaced theoretical game discussions with direct in-browser Code Runner challenges, and structured the Popcorn Hack so it can be completed in under 2 minutes. - -By Joan Kim, Samanvi Yachareni, Ainsley Albert - -
- - -
- ↑ - Submit Assignment -
- -
- - - -
-
diff --git a/_notebooks/2025-10-09-developing-algorithms_crashers_IPYNB_2_.md b/_notebooks/2025-10-09-developing-algorithms_crashers_IPYNB_2_.md deleted file mode 100644 index e2fd28b27b..0000000000 --- a/_notebooks/2025-10-09-developing-algorithms_crashers_IPYNB_2_.md +++ /dev/null @@ -1,549 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Algorithms'] -lesson_language: Python -lesson_topic: Developing-Algorithms -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.9 Developing Algorithms -tags: ['python', 'javascript', 'variables', 'assignment', 'beginner'] -description: Learn how to develop algorithms through the Peppa Pig Maze game -permalink: /csp/developing-algorithms/crashers ---- - -# Peppa Pig Algorithm Adventures - -Peppa Pig wants to reach the end of a maze! Along the way, we'll explore what **algorithms** are — step-by-step sets of instructions to solve problems — and how computers use them to make decisions and perform actions. - -## What Is an Algorithm? - -An **algorithm** is a clear, step-by-step process for solving a problem. You can think of it like a recipe: each instruction must be followed in order to reach the correct result. - -For example, if Peppa wants to reach her toy chest, her algorithm might be: - -1. Walk forward three steps -2. Turn left -3. Walk two steps -4. Open the chest - -In programming, algorithms are written using code so that computers can follow similar logical steps automatically. - -## 1. Simple Algorithm Examples in Python - -Let's start with a basic example showing two ways to add two numbers. Both are simple algorithms that achieve the same goal differently. - - -```python -# Example 1: Two different algorithms to add two numbers -a = 3 -b = 5 - -# Algorithm 1: Step-by-step addition -def add_numbers_manual(x, y): - total = 0 # start from 0 - total += x # add first number - total += y # add second number - return total - -# Algorithm 2: Direct addition (different approach) -def add_numbers_direct(x, y): - return x + y # simply add them in one step - -print('Sum using step-by-step addition:', add_numbers_manual(a, b)) -print('Sum using direct addition:', add_numbers_direct(a, b)) -``` - - Sum using method A: 8 - Sum using method B: 8 - - -Both methods produce the same result. The first shows a clear step-by-step algorithm, while the second uses a simpler Python expression. - -## 2. Boolean Expressions and Conditional Statements - -Algorithms often make decisions. A **conditional statement** tells the computer to do something *only if* a certain condition is true. This uses **Boolean logic** (true or false values). - - -```python -x = 10 -y = 5 - -# Conditional statement algorithm -if x > y: - print('x is greater than y') -else: - print('y is greater or equal to x') - -# Equivalent Boolean expression -print('x is greater than y' if x > y else 'y is greater or equal to x') -``` - - x is greater than y - x is greater than y - - -Here, the algorithm checks whether one number is greater than another and prints a message accordingly — just like a maze game might check whether Peppa can move in a direction before she takes a step. - - -```javascript -%%javascript -// Boolean algorithm example in JavaScript -function isEven(num) { - return num % 2 === 0; // returns true or false -} - -let value = 7; - -// Use the Boolean result in a conditional statement -let result = isEven(value); // result is true if even, false if odd - -if (result) { - console.log(value + ' is even'); -} else { - console.log(value + ' is odd'); -} - -// You can also directly print the Boolean value -console.log('Is ' + value + ' even? ' + result); - -``` - - - - - -This JavaScript code defines a function called `isEven` that checks if a number is even using the modulo operator. It then uses this function to determine if the variable `value` is even or odd, printing a message to the console. - -## 3. Peppa Pig Maze Algorithm (JavaScript Example) - -Now let’s look at a JavaScript version that uses an algorithm to control Peppa’s movement through a maze. Each time you press a button, the algorithm checks whether the move is allowed (no walls or boundaries) and updates Peppa’s position. - - -```python -from IPython.display import display, HTML - -display(HTML(""" - - - -
-

🐷 Peppa's Mini Maze Algorithm Demo

- - -
- - -
- - - - -
- - -
-
- - -""")) - -``` - - - - - - -
-

🐷 Peppa's Mini Maze Algorithm Demo

- - -
- - -
- - - - -
- - -
-
- - - - - -Here, the algorithm: -- Checks if Peppa can move (Boolean condition). -- Updates her position if the move is valid. -- Redraws the maze after each action. - -This demonstrates how logical checks and movement rules form the backbone of many game algorithms. - -## 4. Different Algorithms for the Same Problem (Python) - -Let's compare two numbers to find the larger one using two different approaches. - - -```python -a = 7 -b = 9 - -# Algorithm 1: Using if-else -if a > b: - max_val = a -else: - max_val = b -print('Max using if statement:', max_val) - -# Algorithm 2: Using Python's built-in max() -print('Max using built-in max:', max(a, b)) -``` - - Max using if statement: 9 - Max using built-in max: 9 - - -Both algorithms solve the same problem but in different ways — one step-by-step using an `if` statement, the other using a built-in function for simplicity. The built-in max() function quickly compares the values you give it and returns the largest one. - -## Key Takeaways - -- Algorithms are clear, step-by-step instructions to solve problems. -- The same problem can be solved with different algorithms that vary in speed, clarity, or efficiency. -- Boolean logic and conditionals let programs make smart decisions. -- Python and JavaScript both show how algorithms control logic and visuals — from adding numbers to moving Peppa through her maze. -- Try modifying the examples to see how algorithm changes affect behavior! diff --git a/_notebooks/2025-10-09-developing_procedures_remakers_lesson_IPYNB_2_.md b/_notebooks/2025-10-09-developing_procedures_remakers_lesson_IPYNB_2_.md deleted file mode 100644 index 44ba3fe985..0000000000 --- a/_notebooks/2025-10-09-developing_procedures_remakers_lesson_IPYNB_2_.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -layout: post -courses: {'csp': {'week': 1}} -categories: ['Python', 'Developing-Procedures'] -lesson_language: Python -lesson_topic: Developing-Procedures -lesson_part: interactive -lesson_type: lesson -toc: True -comments: False -title: 3.13 Developing Procedures -description: Lesson for developing procedures. -permalink: /csp/big-idea-3/developing-procedures/p4/introduction -author: Krishna Visvanath, Sloane Sommers ---- - -# Developing Procedures (Methods / Functions) - -Learning goals: -- Understand what a procedure (method/function) is and why we use them. -- See equivalent examples in Java and Python. -- Play a short, interactive minigame that shows why good procedure names and organization matter. - -## What is a procedure? -A procedure (also called a method or function) is a named block of code that does one task. -Think of a procedure like a recipe step: it has a name, inputs (ingredients), and it produces a result or performs an action. - -## Story: The Dessert Robot- The Importance of Naming -Imagine a robot chef who makes desserts. If we tell the robot `makeDessert()` it needs clear sub-steps: `measureFlour()`, `mixIngredients()`, `bake()`. Additionally, if we need to review code later, it is much easier to find the series of events responsible for `makeDessert()`. If we instead call everything `doIt()` the robot — and humans reading the code — get confused. Clear names make code easier to read, test, and reuse. - -### Java example (methods) -Below is a short Java-style example showing a class with methods. This cell is explanatory only — it shows syntax and structure but the procedures aren't called. - - -```python - -function makeDessert() { - measureFlour(); - mixIngredients(); - bake(); -} - -function measureFlour() { - console.log("Measuring 2 cups of flour."); -} - -function mixIngredients() { - console.log("Mixing flour, sugar, eggs."); -} - -function bake() { - console.log("Baking at 350°F for 25 minutes."); -} - -// Run the procedure -makeDessert() - -``` - - - - - -### Python example (functions) -Here's the same idea in Python. Functions perform small tasks and are called from a main function. - - -```python -def make_dessert(): - measure_flour() - mix_ingredients() - bake() - -def measure_flour(): - print("Measuring 2 cups of flour.") - -def mix_ingredients(): - print("Mixing flour, sugar, eggs.") - -def bake(): - print("Baking at 350°F for 25 minutes.") - -# Run the procedure -if __name__ == '__main__': - make_dessert() -``` - -## Mini-game: Name the Procedures -The game below shows a list of steps the program can take, each implemented as a function. Students type a name for a new procedure and the game will call it. If your name clearly describes the steps, it's easy to understand what the game will do. If you name everything `do_step` the code is confusing. Try both and see the difference. -The cell that follows is interactive. Run it and follow the prompts in the notebook output. - - -```python -import random - -def choose_ingredient(): - return random.choice(['flour', 'sugar', 'eggs', 'milk']) - -def mix(item): - print(f"Mixing {item} into the bowl.") - -def heat(): - print('Heating the oven to a friendly temperature...') - -def finish(): - print('Dessert is ready!') - -def play_game(): - print('Mini-game: Name a procedure for choosing an ingredient, putting it into the bowl (mixing), heating/baking, finishing the dessert') - name = input('Type a procedure name you want to create (e.g. prepare_ingredient): ').strip() - if not name: - print('No name entered — using default: prepare_ingredient') - name = 'prepare_ingredient' - - # Create a new procedure dynamically with the given name that runs the sequence - def dynamic_procedure(): - ingr = choose_ingredient() - mix(ingr) - heat() - finish() - - # Bind it into globals so we can show how naming helps with readability - globals()[name] = dynamic_procedure - - print(f'Created a procedure called that does multiple steps.') - print('Now lets show two ways to look at the code:') - - print('Good name (readable):') - print(f' {name}() # clearly indicates the goal is to prepare an ingredient and finish the dessert') - print('Poor name (confusing):') - print(' do_step() # what does this do? you must open the function to find out') - - run = input('Type to execute your procedure now, or anything else to cancel: ').strip().lower() - if run == 'run': - print('Running the procedure...') - globals()[name]() - else: - print('Canceled. You can run the procedure later by calling it by name.') - -if __name__ == '__main__': - play_game() -``` - - Mini-game: Name a procedure for choosing an ingredient, putting it into the bowl (mixing), heating/baking, finishing the dessert - Created a procedure called that does multiple steps. - Now lets show two ways to look at the code: - Good name (readable): - prepare_ingredient() # clearly indicates the goal is to prepare an ingredient and finish the dessert - Poor name (confusing): - do_step() # what does this do? you must open the function to find out - Canceled. You can run the procedure later by calling it by name. - - -### Demonstration of poor naming -Below are two short examples showing the risk of vague names. It's much harder to remember `do_step()` does choosing, mixing, heating, and finishing. Good names reduce bugs and make collaboration easier. - - -```python -# Example showing bad naming -def do_step(): - print('Choosing ingredient...') - print('Mixing...') - print('Heating...') - print('Finished!') - -# Later a collaborator sees do_step() and doesn't know what it does without opening it -print('Calling do_step() (confusing name):') -do_step() -``` - - -```python -# Second example showing bad naming -def do_step(): - print('thing1') - print('thing2') - print('thing3') - -# Later a collaborator is debugging code, and does not know what each procedure does without opening it, meaning they have to go through every line to debug -``` - -## Teaching tips and exercises -- Exercise 1: Rename the functions in the Python example to be more descriptive. -- Exercise 2: Convert the Python functions to Java methods and explain access (public/private). -- Exercise 3: Split a long procedure into smaller ones and show how tests become easier. - -## How to run the mini-game -Run the Python cells in order. When you reach the mini-game cell, you'll be prompted to type a procedure name and optionally run it. If you use the notebook server (Jupyter), the input prompt will appear under the cell output. diff --git a/_notebooks/2026-01-07-arrays_IPYNB_2_.md b/_notebooks/2026-01-07-arrays_IPYNB_2_.md deleted file mode 100644 index cd1fe99621..0000000000 --- a/_notebooks/2026-01-07-arrays_IPYNB_2_.md +++ /dev/null @@ -1,459 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'Arrays'] -lesson_language: JavaScript -lesson_topic: Arrays -lesson_part: interactive -lesson_type: lesson -codemirror: True -microblog: True -title: Arrays -description: Learn about arrays in JavaScript, including how to create, access, and manipulate them. -permalink: /js/arrays -author: Sadaf, Sujay, Arjun, Joshika ---- - -## What are Arrays? - - - -An **array** is a collection of elements (values) stored in a single variable. Each element in an array can be accessed by its **index** (position), starting from 0. - -Think of an array like a row of boxes, each containing a value: -- Box 0 contains the first element -- Box 1 contains the second element -- Box 2 contains the third element -- And so on... - -### Why Use Arrays? -- Store multiple values in one variable -- Easy to access values by position -- Useful for loops (process many items at once) -- Organize related data together - - - -{% capture challenge0 %} -Add or remove a new value in the array and see what happens! -{% endcapture %} - -{% capture code0 %} -let fruits = ["apple", "banana", "orange", "grape"]; - -console.log("My array of fruits:"); -console.log(fruits); -console.log(); - -console.log("First fruit (index 0):", fruits[0]); -console.log("Third fruit (index 2):", fruits[2]); -console.log(); - - -console.log("Number of fruits:", fruits.length); -{% endcapture %} - -{% capture source0 %} -```javascript -%%js - -// CODE_RUNNER: Add or remove a new value in the array and see what happens! - -let fruits = ["apple", "banana", "orange", "grape"]; - -console.log("My array of fruits:"); -console.log(fruits); -console.log(); - -console.log("First fruit (index 0):", fruits[0]); -console.log("Third fruit (index 2):", fruits[2]); -console.log(); - - -console.log("Number of fruits:", fruits.length); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-arrays-0" - language="javascript" - challenge=challenge0 - code=code0 - source=source0 -%} - - -## Modifying Arrays - -You can change, add, or remove elements from an array: - - - -{% capture challenge1 %} -Practice modifying arrays by changing, adding, and removing elements! -{% endcapture %} - -{% capture code1 %} -// Start with an array -let colors = ["red", "blue", "green"]; -console.log(colors); -console.log(); - -// Change an element -colors[1] = "yellow"; -console.log(colors); -console.log(); - -// Add an element -colors.push("purple"); -console.log(colors); -console.log(); - -// Remove an element -colors.splice(colors.indexOf("red"), 1); -console.log(colors); -{% endcapture %} - -{% capture source1 %} -```javascript -%%js - -// CODE_RUNNER: Practice modifying arrays by changing, adding, and removing elements! - -// Start with an array -let colors = ["red", "blue", "green"]; -console.log(colors); -console.log(); - -// Change an element -colors[1] = "yellow"; -console.log(colors); -console.log(); - -// Add an element -colors.push("purple"); -console.log(colors); -console.log(); - -// Remove an element -colors.splice(colors.indexOf("red"), 1); -console.log(colors); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-arrays-1" - language="javascript" - challenge=challenge1 - code=code1 - source=source1 -%} - - -## Looping Through Arrays - -Arrays are powerful when combined with loops. You can process each element without writing it by hand: - - - -{% capture challenge2 %} -Modify the numbers array to see different outputs -{% endcapture %} - -{% capture code2 %} -// Using a for loop to go through each element -let numbers = [10, 20, 30, 40, 50]; - -console.log("Numbers in the array:"); -for (let num of numbers) { - console.log(num); -} - -console.log(); -console.log("Double each number:"); -for (let num of numbers) { - console.log(num * 2); -} - -console.log(); -console.log("Using index to access elements:"); -for (let i = 0; i < numbers.length; i++) { - // conversion fails with template literals - console.log(`Index ${i}: ${numbers[i]}`); - // conversion works with concat - console.log("Index " + i + ": " + numbers[i] ); - -} -{% endcapture %} - -{% capture source2 %} -```javascript -%%js - -// CODE_RUNNER: Modify the numbers array to see different outputs - -// Using a for loop to go through each element -let numbers = [10, 20, 30, 40, 50]; - -console.log("Numbers in the array:"); -for (let num of numbers) { - console.log(num); -} - -console.log(); -console.log("Double each number:"); -for (let num of numbers) { - console.log(num * 2); -} - -console.log(); -console.log("Using index to access elements:"); -for (let i = 0; i < numbers.length; i++) { - // conversion fails with template literals - console.log(`Index ${i}: ${numbers[i]}`); - // conversion works with concat - console.log("Index " + i + ": " + numbers[i] ); - -} -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-arrays-2" - language="javascript" - challenge=challenge2 - code=code2 - source=source2 -%} - - -## Real-World Example: Student Grades - -Let's calculate the average grade of students: - - - -{% capture challenge3 %} -Change the student grades to yours in the array to see different results -{% endcapture %} - -{% capture code3 %} -// Array of student grades -let grades = [85, 92, 78, 95, 88, 91]; - -// Calculate the sum -let total = 0; -for (let grade of grades) { - total = total + grade; -} - -// Calculate the average -let average = total / grades.length; - -console.log(`Student grades: ${grades}`); -console.log(`Total points: ${total}`); -console.log(`Number of students: ${grades.length}`); -console.log(`Average grade: ${average.toFixed(1)}`); -console.log(); - -// Find the highest and lowest grades -console.log(`Highest grade: ${Math.max(...grades)}`); -console.log(`Lowest grade: ${Math.min(...grades)}`); -{% endcapture %} - -{% capture source3 %} -```javascript -%%js - -// CODE_RUNNER: Change the student grades to yours in the array to see different results - -// Array of student grades -let grades = [85, 92, 78, 95, 88, 91]; - -// Calculate the sum -let total = 0; -for (let grade of grades) { - total = total + grade; -} - -// Calculate the average -let average = total / grades.length; - -console.log(`Student grades: ${grades}`); -console.log(`Total points: ${total}`); -console.log(`Number of students: ${grades.length}`); -console.log(`Average grade: ${average.toFixed(1)}`); -console.log(); - -// Find the highest and lowest grades -console.log(`Highest grade: ${Math.max(...grades)}`); -console.log(`Lowest grade: ${Math.min(...grades)}`); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-arrays-3" - language="javascript" - challenge=challenge3 - code=code3 - source=source3 -%} - - -## Key Takeaways - -✅ **Arrays** store multiple values in a single variable -✅ **Index** starts at 0 for the first element -✅ Access elements using `array[index]` -✅ Use **loops** to process all elements -✅ Common operations: append, remove, change, loop, sum, average - -Arrays are one of the most important data structures in programming. Master them and you'll be able to solve many problems efficiently! - -# Arrays Homework 🎯 - -Welcome to the Arrays homework! These exercises will help you practice the key array concepts from the lesson: accessing elements, modifying arrays, looping through arrays, and performing calculations. - -Complete all exercises below. Good luck! 💪 - ---- - -## Exercise 1: Array Basics - Access Elements - -Create an array with 5 different items (could be favorite movies, books, games, etc.). Then: -1. Print the entire array -2. Access and print the first element (index 0) -3. Access and print the last element -4. Print the total number of items in the array - - - -{% capture challenge4 %} -Exercise 1 - Array Basics -{% endcapture %} - -{% capture code4 %} -// TODO: Write your code here for Exercise 1 -// Create an array with 5 items -// Print the array -// Print the first element -// Print the last element -// Print the length -{% endcapture %} - -{% capture source4 %} -```javascript -%%js - -// CODE_RUNNER: Exercise 1 - Array Basics - -// TODO: Write your code here for Exercise 1 -// Create an array with 5 items -// Print the array -// Print the first element -// Print the last element -// Print the length - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-arrays-4" - language="javascript" - challenge=challenge4 - code=code4 - source=source4 -%} - - -## Exercise 2: Modify Arrays - -Start with this shopping list: `["milk", "eggs", "bread", "cheese"]` -Then perform these operations: -1. Print the original array -2. Change the second item to "butter" -3. Add "yogurt" to the end using push() -4. Remove "bread" from the array -5. Print the final array - - - -{% capture challenge5 %} -Exercise 2 - Arrays Manipulation -{% endcapture %} - -{% capture code5 %} -// TODO: Write your code here for Exercise 2 -// Start with the shopping list -// Modify it as described above -{% endcapture %} - -{% capture source5 %} -```javascript -%%js - -// CODE_RUNNER: Exercise 2 - Arrays Manipulation - -// TODO: Write your code here for Exercise 2 -// Start with the shopping list -// Modify it as described above -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-arrays-5" - language="javascript" - challenge=challenge5 - code=code5 - source=source5 -%} - - -## Exercise 3: Loop Through an Array - -Create an array with 5 numbers: `[10, 25, 30, 15, 20]` - -Write a loop that: -1. Prints each number with a message (e.g., "Number: 10") -2. Prints each number multiplied by 2 -3. Calculates and prints the sum of all numbers - - - -{% capture challenge6 %} -Exercise 3 - Arrays Manipulation -{% endcapture %} - -{% capture code6 %} -// TODO: Write your code here for Exercise 3 -// Create the numbers array -// Loop through and print each number -// Print each number multiplied by 2 -// Calculate and print the sum -{% endcapture %} - -{% capture source6 %} -```javascript -%%js - -// CODE_RUNNER: Exercise 3 - Arrays Manipulation - -// TODO: Write your code here for Exercise 3 -// Create the numbers array -// Loop through and print each number -// Print each number multiplied by 2 -// Calculate and print the sum - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-arrays-6" - language="javascript" - challenge=challenge6 - code=code6 - source=source6 -%} - - -Google form link is here: https://forms.gle/X47CB92yKuLVRHq98 diff --git a/_notebooks/2026-01-09-data_abstraction_IPYNB_2_.md b/_notebooks/2026-01-09-data_abstraction_IPYNB_2_.md deleted file mode 100644 index a705baa406..0000000000 --- a/_notebooks/2026-01-09-data_abstraction_IPYNB_2_.md +++ /dev/null @@ -1,441 +0,0 @@ ---- -layout: post -categories: ['JavaScript', 'Data-Abstraction'] -lesson_language: JavaScript -lesson_topic: Data-Abstraction -lesson_part: interactive -lesson_type: lesson -title: Data Abstraction! -courses: {'csse': {'week': 5}} -codemirror: True -microblog: True -permalink: /js/data-abstraction -description: How Data Abstraction is used in Programming -author: Rashi Gaurav, Rigved Reddy Gaddam, and Jasan Boparai ---- - -## What is Data Abstraction?? - IMAGINE -Simply driving a steering wheel without understanding how the parts inside work. This is exactly what Data Abstraction is. - -Data Abstraction simplifies complex systems by showing only the essential features and hiding complex details, so users can easily understand and interact with systems or apps! - - It focuses on *what* something does rather than *how* it does it. - -### Example #1: Rounding numbers -One example is built-in functions in JavaScript, because they allow you to use one simple, clear command to run a type of function, but don't show *how* the built-in function was coded. - - - -{% capture challenge0 %} -Try out Data Abstraction with Math.round() -{% endcapture %} - -{% capture code0 %} -// Abstraction in Action: Math.round() - -// The Complex Data (Input) -const messyNumber = 7.84236; - - -// We call the built-in function. -// We don't care *how* it calculates the rounding - -// only that it *does* the rounding -const roundedResult = Math.round(messyNumber); - -// The Simple Result (Output) -console.log(`The original messy number was: ${messyNumber}`); -console.log(`The simplified, rounded result is: ${roundedResult}`); -// Expected output: 8 -{% endcapture %} - -{% capture source0 %} -```javascript -%%js -// CODE_RUNNER: Try out Data Abstraction with Math.round() - -// Abstraction in Action: Math.round() - -// The Complex Data (Input) -const messyNumber = 7.84236; - - -// We call the built-in function. -// We don't care *how* it calculates the rounding - -// only that it *does* the rounding -const roundedResult = Math.round(messyNumber); - -// The Simple Result (Output) -console.log(`The original messy number was: ${messyNumber}`); -console.log(`The simplified, rounded result is: ${roundedResult}`); -// Expected output: 8 - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-data-abstraction-0" - language="javascript" - challenge=challenge0 - code=code0 - source=source0 -%} - - -#### What's hidden: -The internal logic the JavaScript uses to look at the decimal part (.84236), determine it's >= 0.5, and then round the integer part (7 -> 8). All of this is abstracted away! - -### Example #2: Adding two numbers -The user should be able to call addNumbers(a, b) and trust it works without needing to see the math inside. - - YOUR JOB: -The code below is "broken". Complete the function so that it successfully returns the sum of the two inputs. - - hint: use the *return* keyword inside the function - - - -{% capture challenge1 %} -Display two numbers, and add them! -{% endcapture %} - -{% capture code1 %} -// The Abstraction (The Function) -function addNumbers(num1, num2) { - // Add code here -} - -let a = 2 -let b = 3 - -// Use the abstraction to get the result -let result = addNumbers(a, b); - -console.log(result); -{% endcapture %} - -{% capture source1 %} -```javascript -%%js -// CODE_RUNNER: Display two numbers, and add them! - -// The Abstraction (The Function) -function addNumbers(num1, num2) { - // Add code here -} - -let a = 2 -let b = 3 - -// Use the abstraction to get the result -let result = addNumbers(a, b); - -console.log(result); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-data-abstraction-1" - language="javascript" - challenge=challenge1 - code=code1 - source=source1 -%} - - -## Data Abstraction with Classes -Secondly, Data Abstraction can be seen in Object Oriented Programming, specifically with Classes and Objects . Classes are essential tools for simplifying how we handle data. - -### Example #3: Checking Account Balance - - - -{% capture challenge2 %} -Use the abstraction to deposit $200 -{% endcapture %} - -{% capture code2 %} -class BankAccount { - constructor() { - this.balance = 500; - } - - deposit(amount) { - this.balance = this.balance + amount; - console.log("💰 Deposited: $" + amount); - } -} - -const myAccount = new BankAccount(); - -// Write code here -// Hint: myAccount.______(); - -// 3. Check the result -console.log("Final Balance: $" + myAccount.balance); -{% endcapture %} - -{% capture source2 %} -```javascript -%%js -// CODE_RUNNER: Use the abstraction to deposit $200 -class BankAccount { - constructor() { - this.balance = 500; - } - - deposit(amount) { - this.balance = this.balance + amount; - console.log("💰 Deposited: $" + amount); - } -} - -const myAccount = new BankAccount(); - -// Write code here -// Hint: myAccount.______(); - -// 3. Check the result -console.log("Final Balance: $" + myAccount.balance); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-data-abstraction-2" - language="javascript" - challenge=challenge2 - code=code2 - source=source2 -%} - - -## Inheritance -In programming, Inheritance allows one class (called a subclass / child class) to "borrow" features (properties and methods) from another class (the adult). - -Real World Example: Smartphone - -The Parent Class: A basic phone that can make calls - -The Child Class: An iPhone that inherits the ability to make phone calls, but adds its own features - - - -{% capture challenge3 %} -Use the inherited methods to make a call and take a photo -{% endcapture %} - -{% capture code3 %} -class Phone { - makeCall() { - console.log("Making a phone call"); - } -} - -// Child class -class SmartPhone extends Phone { - takePhoto() { - console.log("Taking a photo"); - } -} - -const myNewPhone = new SmartPhone(); - -// Hint: const_name.method(); -{% endcapture %} - -{% capture source3 %} -```javascript -%%js -// CODE_RUNNER: Use the inherited methods to make a call and take a photo -class Phone { - makeCall() { - console.log("Making a phone call"); - } -} - -// Child class -class SmartPhone extends Phone { - takePhoto() { - console.log("Taking a photo"); - } -} - -const myNewPhone = new SmartPhone(); - -// Hint: const_name.method(); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-data-abstraction-3" - language="javascript" - challenge=challenge3 - code=code3 - source=source3 -%} - - -## HOMEWORK - -1. This is a code of a calculator. Please read through the code first to try and understand what it does. There are many unnecessary lines within the code. Please identify the unnecessary lines and delete them. - - - -{% capture challenge4 %} -Homework for data abstraction -{% endcapture %} - -{% capture code4 %} -function calculator(num1, num2, operator) { - let nothing = 0; - let randomText = "calculator running"; - let temp = null; - - nothing = nothing + 0; - nothing = nothing * 1; - - let result; - - if (randomText === "calculator running") { - temp = "still running"; - } - - if (operator === "+") { - result = num1 + num2; - } else if (operator === "-") { - result = num1 - num2; - } else if (operator === "*") { - result = num1 * num2; - } else if (operator === "/") { - result = num1 / num2; - } else { - result = "Invalid operator"; - } - - for (let i = 0; i < 3; i++) { - nothing += 0; - } - - result = result; - - return result; -} - -console.log(calculator(10, 5, "+")); -console.log(calculator(10, 5, "-")); -console.log(calculator(10, 5, "*")); -console.log(calculator(10, 5, "/")); -{% endcapture %} - -{% capture source4 %} -```javascript -%%js -// CODE_RUNNER: Homework for data abstraction -function calculator(num1, num2, operator) { - let nothing = 0; - let randomText = "calculator running"; - let temp = null; - - nothing = nothing + 0; - nothing = nothing * 1; - - let result; - - if (randomText === "calculator running") { - temp = "still running"; - } - - if (operator === "+") { - result = num1 + num2; - } else if (operator === "-") { - result = num1 - num2; - } else if (operator === "*") { - result = num1 * num2; - } else if (operator === "/") { - result = num1 / num2; - } else { - result = "Invalid operator"; - } - - for (let i = 0; i < 3; i++) { - nothing += 0; - } - - result = result; - - return result; -} - -console.log(calculator(10, 5, "+")); -console.log(calculator(10, 5, "-")); -console.log(calculator(10, 5, "*")); -console.log(calculator(10, 5, "/")); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-data-abstraction-4" - language="javascript" - challenge=challenge4 - code=code4 - source=source4 -%} - - -2. Below a pet class is given. -Your Job is to add a new subclass, Dog, that inherits from the Pet Class - - - -{% capture challenge5 %} -Add a Dog subclass -{% endcapture %} - -{% capture code5 %} -class Pet { - eat() { - console.log("Nom nom nom"); - } -} - -// Create the Dog class that extends Pet - -// We would also like you to create a method like eat() but called bark() that prints "Woof woof!" - -// Refer back to the syntax of the classes examples such as phone and smartphone if you need help! - -// Write your code here -{% endcapture %} - -{% capture source5 %} -```python -%%js - -// CODE_RUNNER: Add a Dog subclass -class Pet { - eat() { - console.log("Nom nom nom"); - } -} - -// Create the Dog class that extends Pet - -// We would also like you to create a method like eat() but called bark() that prints "Woof woof!" - -// Refer back to the syntax of the classes examples such as phone and smartphone if you need help! - -// Write your code here - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-data-abstraction-5" - language="javascript" - challenge=challenge5 - code=code5 - source=source5 -%} - diff --git a/_notebooks/2026-01-13-iterations_lesson_IPYNB_2_.md b/_notebooks/2026-01-13-iterations_lesson_IPYNB_2_.md deleted file mode 100644 index a57833224b..0000000000 --- a/_notebooks/2026-01-13-iterations_lesson_IPYNB_2_.md +++ /dev/null @@ -1,317 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'Iteration'] -lesson_language: JavaScript -lesson_topic: Iteration -lesson_part: interactive -lesson_type: lesson -microblog: True -codemirror: True -title: Iterations -description: An intro to iterations using Code Runner -permalink: /js/iterations -author: Rishab Shyamal, Flora Segale, Chetan Tiduwar ---- - -## Intro to iterations -- The basic gist of iterations are to repeat multiple actions for a desirable result -- Used to repeat code more efficiently compared to just writing out all the functions line by line - - -The syntax of a for loop consists of three main parts: - - -```python -for (initialization; condition; increment) { - // Code to execute -} -``` - -Initialization: This sets up a counter variable and runs once at the beginning of the loop. - -Condition: Before each iteration, the loop checks this condition. If it's true, the loop continues; if false, the loop ends. - -Increment: This updates the counter variable after each iteration. - -### For Loop with Syntax Error - - - -{% capture challenge0 %} -Run loop, the fix the Syntax Error -{% endcapture %} - -{% capture code0 %} -for (let i = 1, i <= 5; i++) { - console.log(i); -} -{% endcapture %} - -{% capture source0 %} -```python -%%js - -// CODE_RUNNER: Run loop, the fix the Syntax Error - -for (let i = 1, i <= 5; i++) { - console.log(i); -} - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-iterations-0" - language="javascript" - challenge=challenge0 - code=code0 - source=source0 -%} - - -### Usage: Looping Through Arrays -You can use a for loop to iterate over elements in an array. - - - -{% capture challenge1 %} -Run loop, then add another fruit to the array and print all fruits -{% endcapture %} - -{% capture code1 %} -let fruits = ["Heart Shaped Herb", "Yami Yami no Mi", "Gomu Gomu no Mi"]; - -for (let i = 0; i < fruits.length; i++) { - console.log(fruits[i]); -} -{% endcapture %} - -{% capture source1 %} -```python -%%js - -// CODE_RUNNER: Run loop, then add another fruit to the array and print all fruits - -let fruits = ["Heart Shaped Herb", "Yami Yami no Mi", "Gomu Gomu no Mi"]; - -for (let i = 0; i < fruits.length; i++) { - console.log(fruits[i]); -} - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-iterations-1" - language="javascript" - challenge=challenge1 - code=code1 - source=source1 -%} - - -Add two of your own fruits and try it out! - -### Objects - -for loops can also be used to iterate **objects** over each **key** and its **value** - - - -{% capture challenge2 %} -Run loop, then change to your Personal Info -{% endcapture %} - -{% capture code2 %} -const personInfo = { // Define an object - name: "Rishab", - age: 15, - city: "San Diego", - occupation: "High School Student" -}; - -for (let key in personInfo) { // Notice we are using for... in... instead of for... of... - console.log(key + ": " + personInfo[key]); -} -{% endcapture %} - -{% capture source2 %} -```python -%%js - -// CODE_RUNNER: Run loop, then change to your Personal Info - -const personInfo = { // Define an object - name: "Rishab", - age: 15, - city: "San Diego", - occupation: "High School Student" -}; - -for (let key in personInfo) { // Notice we are using for... in... instead of for... of... - console.log(key + ": " + personInfo[key]); -} -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-iterations-2" - language="javascript" - challenge=challenge2 - code=code2 - source=source2 -%} - - -# 🌿 **Understanding `while` Loops** - -A **`while` loop** repeats a block of code **as long as a condition is true**. -It’s useful when you don’t know exactly how many times something should run — you just know the rule for when it should stop. - -A `while` loop always includes: - -- **A starting value** -- **A condition** checked before each loop -- **A change** inside the loop that eventually makes the condition false - -If the condition never becomes false, the loop runs forever — an **infinite loop**. - -# 🌱 **Simple Example** - - - -{% capture challenge3 %} -Run loop, then change the starting value, condition, and increment -{% endcapture %} - -{% capture code3 %} -let counter = 0; - -while (counter < 5) { - console.log("The counter is:", counter); - counter += 1; -} -{% endcapture %} - -{% capture source3 %} -```javascript -%%js - -// CODE_RUNNER: Run loop, then change the starting value, condition, and increment -let counter = 0; - -while (counter < 5) { - console.log("The counter is:", counter); - counter += 1; -} -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-iterations-3" - language="javascript" - challenge=challenge3 - code=code3 - source=source3 -%} - - -Try experimenting with: - -- Changing the starting value -- Changing the condition -- Changing the increment (e.g., `counter += 2`) -- Making it count down instead of up - -# 🌼 **Playful Example: Growing Vine** - -This version is visual, fun, and great for experimenting with iteration. - -Try experimenting with: - -- Changing the maximum length -- Make the vine shrink instead of grow -- Replace the emoji with another symbol -- Increase the growth rate (e.g., `length += 2`) - - - -{% capture challenge4 %} -Run loop to see growing vine -{% endcapture %} - -{% capture code4 %} -// Growing vine using a while loop - - -let length = 1; - -while (length <= 10) { - console.log("🌿".repeat(length)); - length += 1; -} -{% endcapture %} - -{% capture source4 %} -```python -%%js -// Growing vine using a while loop - -// CODE_RUNNER: Run loop to see growing vine - -let length = 1; - -while (length <= 10) { - console.log("🌿".repeat(length)); - length += 1; -} - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-iterations-4" - language="javascript" - challenge=challenge4 - code=code4 - source=source4 -%} - - -## Challenge Iteration -Write an iteration to calculate the sum of all numbers from 1 to n -Test it with an input of 5 - -Hint: use 'n' to define your condition, and replace 'n' with the number that you want to be the upper limit you are adding to your sum. - - - -{% capture challenge5 %} -Complete function to Sum Numbers from 1 to n, and call the function with a parameter of your choice -{% endcapture %} - -{% capture code5 %} -function sumNumbers(n) { - let sum = 0; -{% endcapture %} - -{% capture source5 %} -```python -%%js - -// CODE_RUNNER: Complete function to Sum Numbers from 1 to n, and call the function with a parameter of your choice - -function sumNumbers(n) { - let sum = 0; -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-iterations-5" - language="javascript" - challenge=challenge5 - code=code5 - source=source5 -%} - diff --git a/_notebooks/2026-01-16-json_lesson_IPYNB_2_.md b/_notebooks/2026-01-16-json_lesson_IPYNB_2_.md deleted file mode 100644 index f72fe589ed..0000000000 --- a/_notebooks/2026-01-16-json_lesson_IPYNB_2_.md +++ /dev/null @@ -1,349 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'JSON'] -lesson_language: JavaScript -lesson_topic: JSON -lesson_part: interactive -lesson_type: lesson -codemirror: True -microblog: True -title: JSON and JavaScript Objects -description: JSON Structures using Code Runner -permalink: /js/json -author: Finn Dyess, Matteo ---- - -# JSON and JavaScript Objects - -## All About JSON and JavaScript Objects - -Let's imagine this. You're in your room, with tons of stuff laid out however you want: clothes on the bed, books stacked on a shelf, maybe a backpack open with notebooks inside. You can walk around, grab things, move them, and even use them right away. - -This is what a **JavaScript** object is like. It lives inside your program, and JavaScript can interact with it directly. - -Now imagine that you need to ship your stuff to someone else. - -You can't just send your entire room as-is. You have to: -- Put everything to boxes -- Label everything clearly -- Follow shipping rules so nothing breaks - -That is what JSON is like. JSON is how we *package data* so it can be sent, stored, or shared. It is not meant to be used directly, but instead to travel. - -In this lesson, we will go over: -- What JavaScript objects are -- What JSON is -- Why they appear similar but have different functions -- How to convert between the two - -## Section 1: JavaScript Objects -A **JavaScript object** is a collection of related information stored in one variable. - -JavaScript objects: -- Live inside JavaScript code -- Can store different types of data -- Can include functions -- Are flexible - -Here's a basic example of a JavaScript object: - - -```javascript -%%js - -const student = { - name: "Alex", - age: 16, - enrolled: true, - greet: function () { - return "Hello!"; - } -}; -``` - -Notice a few things: -- The keys **do not** need quotes -- The object includes a function -- JavaScript understands this immediately - -This only works because JavaScript is running the code. - -## Code Runner 1 -Here's what to do: - -Run the code below, then try changing it. - - - -{% capture challenge0 %} -Personalize your student record JSON object -{% endcapture %} - -{% capture code0 %} -const student = { - name: "Bartholomew", - age: 15, - grade: "9th" -}; - - -console.log(student.name); -console.log(student.age); -{% endcapture %} - -{% capture source0 %} -```javascript -%%js - -// CODE_RUNNER: Personalize your student record JSON object - -const student = { - name: "Bartholomew", - age: 15, - grade: "9th" -}; - - -console.log(student.name); -console.log(student.age); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-json-0" - language="javascript" - challenge=challenge0 - code=code0 - source=source0 -%} - - -Try the following: -- Change the student's name to your own -- Log the entire object - -Now try this: - - -```python -console.log(student.school); -``` - -This will print `undefined`. -This isn't because of an error, but instead because `student.school` was never defined. -JavaScript objects are flexible. They do not break just because a property is undefined. - -## Section 2: What is JSON? - -JSON stands for JavaScript Object Notation. - -Even though it has the word *JavaScript* in the name, JSON is **not JavaScript code.** - -JSON is: -- A text format -- Used to send and store data - -Because JSON is meant to be shared, it has **strict rules**. - -### JSON Rules -JSON: -- Required double quotes for all keys -- Does NOT allow functions -- Does NOT allow comments -- Does NOT allow trailing commas - -If any rule is broken, then JSON will fail. - -## Code Runner 2 - - - - - -{% capture challenge1 %} -Personalize your student record again and parse it from JSON -{% endcapture %} - -{% capture code1 %} -const jsonData = ` -{ - "name": "Finn", - "age": 15, - "isStudent": true -} -`; - - -const parsedData = JSON.parse(jsonData); -console.log(parsedData); -{% endcapture %} - -{% capture source1 %} -```javascript -%%js - -// CODE_RUNNER: Personalize your student record again and parse it from JSON - -const jsonData = ` -{ - "name": "Finn", - "age": 15, - "isStudent": true -} -`; - - -const parsedData = JSON.parse(jsonData); -console.log(parsedData); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-json-1" - language="javascript" - challenge=challenge1 - code=code1 - source=source1 -%} - - -Now, intentionally break it. Try these examples: -- Remove quotes from a key -- Add a trailing comma -- Change `true` to `True` -- Add a comment - -When JSON breaks, JavaScript returns an error. -This is because JSON must be readable so computers can read it reliably. - -## Section 3: Converting Between JSON and JavaScript Objects - - - -{% capture challenge2 %} -Converting a JavaScript object to JSON and back (with your own data) -{% endcapture %} - -{% capture code2 %} -const user = { - username: "coder123", - score: 42, - premium: false -}; - - -const jsonString = JSON.stringify(user); -console.log(jsonString); - - -const parsedUser = JSON.parse(jsonString); -console.log(parsedUser); -{% endcapture %} - -{% capture source2 %} -```javascript -%%js - -// CODE_RUNNER: Converting a JavaScript object to JSON and back (with your own data) - -const user = { - username: "coder123", - score: 42, - premium: false -}; - - -const jsonString = JSON.stringify(user); -console.log(jsonString); - - -const parsedUser = JSON.parse(jsonString); -console.log(parsedUser); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-json-2" - language="javascript" - challenge=challenge2 - code=code2 - source=source2 -%} - - -Try the following: -- Add a new property -- Add an array -- Add a nested object - - -## JSON Objects Summary -- Elements are stored in a hash table (key-value) -- You can edit the hash table -- Store different data types -- You can nest objects -- Purpose: store related data, store/organize more complex data, transfer data in JSON format -## Homework Assignment: JSON Challenge -Create a resume containing your personal information, skills, and education and print it as a JSON string. - - - -{% capture challenge3 %} -Create a resume as a JavaScript Object and print to the console as JSON -{% endcapture %} - -{% capture code3 %} -// 1. Create a JavaScript object named `resume` with the following properties: -const resume = { - fullName: "", // Add your full name - email: "", // Add your email - education: "", // Add your grade - address: { // Nested object - city: "", - state: "", - country: "" - }, - skills: [] // Array of strings -}; -// 2. Access and display properties for full name, email, and city using dot notation. Look at section 1. -// 3. Convert the `resume` JavaScript object into a JSON string and store it in a variable named `jsonString`, then log the JSON string to the console. Look at Section 3. -// 4. Parse the JSON string back into a JavaScript object and store it in a variable named `parsedResume`, then log the object to the console. Look at Section 3. -{% endcapture %} - -{% capture source3 %} -```javascript -%%js - -// CODE_RUNNER: Create a resume as a JavaScript Object and print to the console as JSON - -// 1. Create a JavaScript object named `resume` with the following properties: -const resume = { - fullName: "", // Add your full name - email: "", // Add your email - education: "", // Add your grade - address: { // Nested object - city: "", - state: "", - country: "" - }, - skills: [] // Array of strings -}; -// 2. Access and display properties for full name, email, and city using dot notation. Look at section 1. -// 3. Convert the `resume` JavaScript object into a JSON string and store it in a variable named `jsonString`, then log the JSON string to the console. Look at Section 3. -// 4. Parse the JSON string back into a JavaScript object and store it in a variable named `parsedResume`, then log the object to the console. Look at Section 3. - - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-json-3" - language="javascript" - challenge=challenge3 - code=code3 - source=source3 -%} - - -Hint: use above code runners as examples, then edit them diff --git a/_notebooks/2026-01-20-booleans-lessons_IPYNB_2_.md b/_notebooks/2026-01-20-booleans-lessons_IPYNB_2_.md deleted file mode 100644 index c3b4ce8d4a..0000000000 --- a/_notebooks/2026-01-20-booleans-lessons_IPYNB_2_.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'Booleans'] -lesson_language: JavaScript -lesson_topic: Booleans -lesson_part: interactive -lesson_type: lesson -microblog: True -codemirror: True -title: Booleans -description: An intro to booleans using Code Runner -permalink: /js/booleans -author: Ahmad, Matt, Ashi ---- - - Booleans - -- Booleans are one of the most fundamental data types in programming -- A boolean can only have two values: `true` or `false` -- Used to make decisions in code and control the flow of programs - -The basic syntax of a boolean: -```javascript -let isStudent = true; -let isRaining = false; -``` - - -```javascript -%%js - -let isActive = true; -console.log(isActive); -console.log("Boolean value: " + isActive); -console.log("Boolean value: " + isActive); -``` - - - - - -### Usage: Boolean Comparisons -You can use comparison operators to create boolean values. - - - -{% capture challenge0 %} -Run code, then change to your own conditions -{% endcapture %} - -{% capture code0 %} -let hasLicense = true; -let hasCar = false; -let canDrive = hasLicense && hasCar; - -console.log("Has license: " + hasLicense); -console.log("Has car: " + hasCar); -console.log("Can drive: " + canDrive); -{% endcapture %} - -{% capture source0 %} -```javascript -%%js - -let age = 15; -let isAdult = age >= 18; -let isTeenager = age >= 13 && age <= 19; - -console.log("Is adult: " + isAdult); -console.log("Is teenager: " + isTeenager); - -// Test with different ages -console.log(isAdult && isTeenager); // false - can't be both adult and teenager -console.log(isAdult || isTeenager); // true - at least one is true - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-booleans-0" - language="javascript" - challenge=challenge0 - code=code0 - source=source0 -%} - - - - - - -### Boolean Operators -Booleans can be combined using **logical operators** like `&&` (and), `||` (or), and `!` (not) - - - -{% capture challenge1 %} -Run code, then change to your own conditions -{% endcapture %} - -{% capture code1 %} -function isPositiveAndEven(num) { - let isPositive = num > 0; - let isEven = num % 2 === 0; - return isPositive && isEven; -} - -document.body.innerHTML += isPositiveAndEven(8); // true -{% endcapture %} - -{% capture source1 %} -```javascript -%%js - -// CODE_RUNNER: Run code, then change to your own conditions -let hasLicense = true; -let hasCar = false; -let canDrive = hasLicense && hasCar; - -console.log("Has license: " + hasLicense); -console.log("Has car: " + hasCar); -console.log("Can drive: " + canDrive); - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-booleans-1" - language="javascript" - challenge=challenge1 - code=code1 - source=source1 -%} - - - -## HomeWork Boolean -Write a function that checks if a number is positive AND even - -Test it with an input of 8 - -Hint: use the modulo operator (%) to check if a number is even, and comparison operators to check if it's positive. - - - -```javascript -%%js -//code_runner: Run code, then change to your own conditions -function isPositiveAndEven(num) { - let isPositive = num > 0; - let isEven = num % 2 === 0; - return isPositive && isEven; -} - -document.body.innerHTML += isPositiveAndEven(8); // true - -``` diff --git a/_notebooks/2026-01-20-math-exp_IPYNB_2_.md b/_notebooks/2026-01-20-math-exp_IPYNB_2_.md deleted file mode 100644 index 91d54210d3..0000000000 --- a/_notebooks/2026-01-20-math-exp_IPYNB_2_.md +++ /dev/null @@ -1,302 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'Mathematical-Expressions'] -lesson_language: JavaScript -lesson_topic: Mathematical-Expressions -lesson_part: interactive -lesson_type: lesson -codemirror: True -microblog: True -title: Mathematical Expressions -permalink: /js/math -author: Samaghna Deshatty, Isha Chaturvedi, Ayden Dudley ---- - -## JS Lessons - - - - - -### **Introduction to Mathematical Expresions** - -📌 What are Mathematical Expressions? -Mathematical expressions in coding are combintations of numbers, varibles, and operators that are used to calculate given values or solve problems in a program. - -For Example: - -`1 + 2 * 3;` - -> **Key Ideas:** Mathematical expressions in programming are almost idnetical to the mathematical expresions done in your math class, it is just a difference of how they are written. - ---- - -### **Key Mathematical Operators** - -| Operator | Symbol | Example | Result | Example use case | -|------------------|--------|-------------|--------|-----------------------------| -| Addition | `+` | `2 + 3` | `5` | `console.log(2 + 3);` | -| Subtraction | `-` | `5 - 2` | `3` | `console.log(5 - 2);` | -| Multiplication | `*` | `4 * 3` | `12` | `console.log(4 * 3);` | -| Division | `/` | `10 / 2` | `5` | `console.log(10 / 2);` | -| Modulo | `%` | `7 % 3` | `1` | `console.log(7 % 3);` | -| Exponentiation | `**` | `2 ** 3` | `8` | `console.log(2 ** 3);` | - -You can also use inequality operators in if statements (>, <, ==, <=, =>) - ---- - -### **Variables in Expressions** -You can use variables to store values and build expressions: - -`let x = 5` - ---- - -### **Order of Operations** -Order of operations is used in programming just as it is used in regular math, any equation given to the cell will be done using PEMDAS -- Parentheses -- Exponents -- Multiplication/Division -- Addition/Subtraction - -In any equation that is inputed to the coding cell all eqaution will use order of operation to correctly solve the information given. - - - -{% capture challenge0 %} -Identitfy the error in the following code and fix it. -{% endcapture %} - -{% capture code0 %} -let number = 5; - -console.log(number;);// hint: there's a syntax error here -{% endcapture %} - -{% capture source0 %} -```javascript -%%js - -// CODE_RUNNER: Identitfy the error in the following code and fix it. - -let number = 5; - -console.log(number;);// hint: there's a syntax error here -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-math-0" - language="javascript" - challenge=challenge0 - code=code0 - source=source0 -%} - - - - -{% capture challenge1 %} -How does changing the value of variables affect the output? Try changing the values of x and y below and see what happens to total1 and total2. -{% endcapture %} - -{% capture code1 %} -let x = 10; -let y = 3; -let total1 = x + y + 2; // total = 10 + 3 + 2 = 15 - -console.log("The total is: " + total1); // final output -{% endcapture %} - -{% capture source1 %} -```javascript -%%js - -// CODE_RUNNER: How does changing the value of variables affect the output? Try changing the values of x and y below and see what happens to total1 and total2. - -let x = 10; -let y = 3; -let total1 = x + y + 2; // total = 10 + 3 + 2 = 15 - -console.log("The total is: " + total1); // final output -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-math-1" - language="javascript" - challenge=challenge1 - code=code1 - source=source1 -%} - - - - -{% capture challenge2 %} -Modulo is used to check the divisibility of certain numbers.It can also be used to see if number are even or odd, using the code below change the values of x to see how modulo works. -{% endcapture %} - -{% capture code2 %} -let x = 17; -let total = x % 2; - -console.log(x + " % 2 = " + total); - -if (x % 2 === 0) { - console.log(x + " number is even"); -} else { - console.log(x + " number is odd"); -} -{% endcapture %} - -{% capture source2 %} -```javascript -%%js - -// CODE_RUNNER: Modulo is used to check the divisibility of certain numbers.It can also be used to see if number are even or odd, using the code below change the values of x to see how modulo works. - -let x = 17; -let total = x % 2; - -console.log(x + " % 2 = " + total); - -if (x % 2 === 0) { - console.log(x + " number is even"); -} else { - console.log(x + " number is odd"); -} - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-math-2" - language="javascript" - challenge=challenge2 - code=code2 - source=source2 -%} - - -## Advanced Code ( optional ) -The below code cell is built into the page. The cell shows advanced ways of building a custom runner. You must run the cell to ensure code is in page when running make or view in deployed actions. FYI, this uses most common elements you need to understand when building an interactive web page. - - -- Style for text area and buttons -- HTML Document Object Model (DOM) definitions -- Event handling -- Evaluation of the textarea example code - - -```python - - - - -

JavaScript - Math Challenge user conventional Style, HTML, and JS

-

Set a variable x to any number. Then calculate:

-
    -
  • x + 5
  • -
  • x * 2
  • -
  • x % 3 (remainder when x is divided by 3)
  • -
-

Print all three results in a single line. Try different values of x!

- - - -
- - -

Output:

-
- - - -``` - -## Homework Problems - - - -{% capture challenge3 %} -Homework Problem #1. Create a program that check if a number y is divisible by 5 or not, use modulo in this! -{% endcapture %} - -{% capture code3 %} -// hint: use challenge problem #3 code above to help you! -{% endcapture %} - -{% capture source3 %} -```javascript -%%js - -// CODE_RUNNER: Homework Problem #1. Create a program that check if a number y is divisible by 5 or not, use modulo in this! -// hint: use challenge problem #3 code above to help you! - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-math-3" - language="javascript" - challenge=challenge3 - code=code3 - source=source3 -%} - - - - -{% capture challenge4 %} -Homework Problem #1. Create a program that has three variables, a,b,and sum, which adds them together, use console.log to print the final output. -{% endcapture %} - -{% capture code4 %} -// hint: use challenge problem #2 code above to help you! -{% endcapture %} - -{% capture source4 %} -```javascript -%%js - -// CODE_RUNNER: Homework Problem #1. Create a program that has three variables, a,b,and sum, which adds them together, use console.log to print the final output. -// hint: use challenge problem #2 code above to help you! -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-math-4" - language="javascript" - challenge=challenge4 - code=code4 - source=source4 -%} - diff --git a/_notebooks/2026-01-27-Strings_IPYNB_2_.md b/_notebooks/2026-01-27-Strings_IPYNB_2_.md deleted file mode 100644 index 392c2730f2..0000000000 --- a/_notebooks/2026-01-27-Strings_IPYNB_2_.md +++ /dev/null @@ -1,183 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'Strings'] -lesson_language: JavaScript -lesson_topic: Strings -lesson_part: interactive -lesson_type: lesson -codemirror: True -microblog: True -title: Strings -description: Strings using Code Runner -permalink: /js/strings -author: Seonyoo Pak, Adam Ong, Roger Wang ---- - -## Introduction - -**What Exactly Are Strings?** Strings are essentially sequences of characters used to represent text in programming. They can include letters, numbers, symbols, and spaces. - - -**Example Code:** - -~~~js -// Add two strings together - -let fruit1 = "Apple"; -let fruit2 = "Banana"; -let combinedFruits = fruit1 + " and " + fruit2; -console.log("Fruits to eat: " + combinedFruits); -~~~ - -In the example above, there are two variables: fruit1 and fruit2. Notice how apple and banana are in quotation marks? That indicates that they are strings. In JavaScript, strings are enclosed in single quotes (' '), double quotes (" "), or backticks (` `). The "and" in between the two fruits is also a string. When we add the strings together using the + operator, we get a new string that combines them. - -Now you try: - - - -{% capture challenge0 %} -Identify and correct the error in the code. -{% endcapture %} - -{% capture code0 %} - let sport1 = "Soccer"; - let sport2 = "Basketball"; - - console.log(The sports I play are: + sport1 + " and " + sport2); -{% endcapture %} - -{% capture source0 %} -```javascript -%%js - -// CODE_RUNNER: Identify and correct the error in the code. - - let sport1 = "Soccer"; - let sport2 = "Basketball"; - - console.log(The sports I play are: + sport1 + " and " + sport2); -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-strings-0" - language="javascript" - challenge=challenge0 - code=code0 - source=source0 -%} - - -## String Length and Indexing - -**String Lenth:** You can find out how many characters are in a string using the `.length` property. Spaces also count as a character. - -**Example:** - -~~~js -let message = "Hello World"; -console.log(message.length); // Will output 11 because there are 11 characters -~~~ - -**String Indexing:** Each character in a string has an index, starting from 0 for the first character. You can access individual characters using bracket notation. - -**Example:** - -~~~js -let greeting = "Hello World"; -console.log(greeting[0]); // Will output "H" -console.log(greeting[6]); // Will output "W" -~~~ - - - -{% capture challenge1 %} -Modify this code so that the password requires at least 8 characters and the first character is equal to 3. Remember, the first character is 0, not 1. -{% endcapture %} - -{% capture code1 %} -let password = "abc"; -if (password.length < 8 || password[0] !== "3") { // FYI, "||" means OR, and "!==" means NOT EQUAL TO - console.log("Password must be at least 8 characters and start with '3'"); -} else { - console.log("Password is valid!"); -} -{% endcapture %} - -{% capture source1 %} -```javascript -%%js - -// CODE_RUNNER: Modify this code so that the password requires at least 8 characters and the first character is equal to 3. Remember, the first character is 0, not 1. - -let password = "abc"; -if (password.length < 8 || password[0] !== "3") { // FYI, "||" means OR, and "!==" means NOT EQUAL TO - console.log("Password must be at least 8 characters and start with '3'"); -} else { - console.log("Password is valid!"); -} -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-strings-1" - language="javascript" - challenge=challenge1 - code=code1 - source=source1 -%} - - -## String Concatenation - -**String Concatenation:** is simply the process of combining two or more strings together. In JavaScript, you can concatenate strings using the `+` operator. - -**Example:** - -~~~js -let firstName = "John"; -let lastName = "Smith"; -let fullName = firstName + " " + lastName; // Those quotation marks just add a space between the words -console.log(fullName); // Will output "John Smith" -~~~ - - - - -{% capture challenge2 %} -Add your own information to the constants below and use concatenation to print a sentence about yourself. -{% endcapture %} - -{% capture code2 %} -const name = "x"; -const age = y; -const city = "z"; - -// Your code here -{% endcapture %} - -{% capture source2 %} -```javascript -%%js - -// CODE_RUNNER: Add your own information to the constants below and use concatenation to print a sentence about yourself. - -const name = "x"; -const age = y; -const city = "z"; - -// Your code here - - -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-strings-2" - language="javascript" - challenge=challenge2 - code=code2 - source=source2 -%} - diff --git a/_notebooks/2026-02-19-variables_IPYNB_2_.md b/_notebooks/2026-02-19-variables_IPYNB_2_.md deleted file mode 100644 index 1ff9e3e366..0000000000 --- a/_notebooks/2026-02-19-variables_IPYNB_2_.md +++ /dev/null @@ -1,280 +0,0 @@ ---- -layout: post -courses: {'csse': {'week': 5}} -categories: ['JavaScript', 'Variables'] -lesson_language: JavaScript -lesson_topic: Variables -lesson_part: interactive -lesson_type: lesson -codemirror: True -microblog: True -title: Variables -description: HTML Domain and Variables lesson -permalink: /js/variables/ -author: Aadi Saini, Daniel Livitz, Kashyap Tubati ---- - -### What are variables? -A variable is a container where you store stuff. Think of it like your lunchbox: `let lunchbox = "sandwich";` - -Meaning: -let → When creating a new variable you use let - -lunchbox → the name of the variable - -"sandwich" → the value or info that is stored in the variable - - - -### Why are variables helpful? -Instead of repeating the same thing again and again, you store it once and reuse it. - -### 1. let vs const - -When you create variables, you use let or const. - -Let is used when the value can change -**Examples:** your points in a video game, your age - -`let points = 0; points = points + 1;` - -Const is used when the value should NOT change. -**Examples:** your student ID, your birthday, your permanent username - -`const studentID = "S12345";` -`const birthday = "2012-08-19";` -`const username = "Daniel_the_Miner";` - Now you go ahead and try! - - - -{% capture challenge0 %} -Create 2 variables. One of your birthday and one of a point system that adds by 3. (Look at the reading above for help) -{% endcapture %} - -{% capture code0 %} -let // Put a variable here -const // Put another variable here - -console.log(Points) -console.log(Birthday) -{% endcapture %} - -{% capture source0 %} -```javascript -%%js - -// CODE_RUNNER: Create 2 variables. One of your birthday and one of a point system that adds by 3. (Look at the reading above for help) - -let // Put a variable here -const // Put another variable here - -console.log(Points) -console.log(Birthday) -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-variables-0" - language="javascript" - challenge=challenge0 - code=code0 - source=source0 -%} - - - -### Data Types - -**A data type is what kind of value is stored in the variable. Here are the main ones:** - - - -`let pencils = 12;` Number → how many(quantitative) - -`let teacherName = "Mr. Lee";`String → text (You only need double quotes when writing strings) - -`let isPresent = true;` Boolean → true or false value - -`let homework;` Undefined → declared but not filled yet - -`let deskItem = null;` Null → intentionally empty - -### Reference Data Types (Bigger containers) - -**When you need to store multiple varibles together into category.** - -Object → a bundle of related info -Array → a list of the same type of data - -**Objects** - -Instead of storing everything separately: -`let name = "Ava";` `let grade = 7;` `let hasPencil = true;` - -You can group it into one object: -`const student = { name: "Ava", grade: 7, hasPencil: true };` - -**Arrays:** - -Instead of storing every item separately: -`let snack1 = "chips";` `let snack2 = "apple";` `let snack3 = "cookie";` - -You can group it into one array: - `let snacks = ["chips", "apple", "cookie"];` - - - -{% capture challenge1 %} -Make an an object of your favorite food, color and movie. (Refer above for help) -{% endcapture %} - -{% capture code1 %} -console.log(FavoriteThings) -{% endcapture %} - -{% capture source1 %} -```javascript -%%js - -// CODE_RUNNER: Make an an object of your favorite food, color and movie. (Refer above for help) - -console.log(FavoriteThings) -``` -{% endcapture %} - -{% include runners/code.html - runner_id="js-variables-1" - language="javascript" - challenge=challenge1 - code=code1 - source=source1 -%} - - -## HTML DOM (Document Object Model) - -Now, to go to HTML DOM. Imagine HTML DOM like this: It's essentially the HTML code, but with changes applied to it. Here's a better way to visualize that: You are playing the Pong Game on the `pages.opencodingsociety.com` website, and you are playing against an AI paddle. Now, imagine a score tracker on the top that counts the points that each side has. Javascript would change the HTML DOM in this scenario by changing the amount of points each side has. - -### So how does HTML DOM connect to variables? - -It's very simple actually. Taking something like the ping pong game, Javascript would store data like a variable for `player score` and then the DOM would just take the value of that variable and then output it to the rendered site. - - -
- - - - - - - - -
- - - - - - - - - - - - - - - -1. The first part of the code is the HTML button, text and DOM id → `