{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Programming Techniques — Error Detective\n", "\n", "## Semi-independent discussion exercise\n", "\n", "For each example:\n", "\n", "1. **Predict** what will happen before running the cell.\n", "2. Run the cell.\n", "3. Identify the type of problem.\n", "4. Explain **when** Python detects it.\n", "5. Suggest the smallest possible correction.\n", "\n", "### Three useful categories\n", "\n", "- **Syntax / pre-execution error**: Python cannot correctly parse the program.\n", "- **Runtime error**: execution starts, but an error occurs while an instruction is being executed.\n", "- **Logical error**: the program runs without an exception, but the result is not what was intended.\n", "\n", "> In introductory discussions, syntax errors are sometimes loosely called *compile-time errors*. In CPython, source code is first compiled to bytecode and then executed by the Python interpreter." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 1 — Something is missing\n", "\n", "Before running the cell, discuss:\n", "\n", "- Will Python execute the `print` instruction?\n", "- What kind of error do you expect?\n", "- Where is the problem?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Welcome to Python!\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Syntax / pre-execution error (`SyntaxError`).\n", "\n", "The closing parenthesis is missing, so Python cannot correctly parse the instruction.\n", "\n", "Correct version:\n", "\n", "```python\n", "print(\"Welcome to Python!\")\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 2 — A string that never ends\n", "\n", "Predict the result before running the cell." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Programming is fun!)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Syntax / pre-execution error (`SyntaxError`).\n", "\n", "The opening quotation mark starts a string, but the string is never closed.\n", "\n", "Correct version:\n", "\n", "```python\n", "print(\"Programming is fun!\")\n", "```" ] }, { "cell_type": "markdown", "id": "a62cea8d", "metadata": {}, "source": [ "## Example 2.1 - harder\n", "Find the problem with this code snippet and fix it without looking at the solution." ] }, { "cell_type": "code", "execution_count": null, "id": "ced7fa6f", "metadata": {}, "outputs": [], "source": [ "print('programming isn't boring at all!')" ] }, { "cell_type": "markdown", "id": "ac99698f", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Syntax / pre-execution error (`SyntaxError`).\n", "\n", "The opening quotation mark starts a string, but the first apostrophe is not properly escaped. Double quotes can include a single quote inside a string, or vice versa. In this case, the string should be enclosed in double quotes to avoid confusion with the apostrophe.\n", "\n", "Correct version:\n", "\n", "```python\n", "print(\"Programming isn't boring at all!\")\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 3 — Valid syntax, invalid operation\n", "\n", "Discuss:\n", "\n", "- Is the syntax valid?\n", "- Can Python start executing the instruction?\n", "- What operation creates the problem?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(10 / 0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Runtime error (`ZeroDivisionError`).\n", "\n", "The instruction is syntactically valid. The error appears only when Python tries to perform division by zero." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 4 — What is `age`?\n", "\n", "Predict what happens." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Your age is\", age)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Runtime error (`NameError`).\n", "\n", "The syntax is valid, but when the instruction is executed Python looks for the name `age`. No value has previously been associated with that name.\n", "\n", "For example:\n", "\n", "```python\n", "age = 20\n", "print(\"Your age is\", age)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 5 — Can these two values be added?\n", "\n", "Predict the result before running the cell." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"3\" + 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Runtime error (`TypeError`).\n", "\n", "> note that `+` can be used to concatenate strings\n", "> ```python\n", "> \"Hello\" + \"World!\"\n", "> ```\n", "\n", "`\"3\"` is text, while `2` is a number. Python does not automatically decide whether the intended operation is text concatenation or numerical addition.\n", "\n", "Possible corrections:\n", "\n", "```python\n", "print(\"3\" + \"2\") # \"32\"\n", "print(3 + 2) # 5\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 6 — A `print()` parameter\n", "\n", "You have already seen some optional parameters of `print()`.\n", "\n", "What do you expect from this instruction?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"red\", \"green\", \"blue\", sep=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Runtime error (`TypeError`).\n", "\n", "The instruction is syntactically valid, but the value passed to `sep` is not valid. `sep` must be a string (or `None`), not an integer.\n", "\n", "For example:\n", "\n", "```python\n", "print(\"red\", \"green\", \"blue\", sep=\" | \")\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Now: errors that Python does **not** report\n", "\n", "The following programs run successfully.\n", "\n", "The question is now:\n", "\n", "> **Does the program compute what the programmer intended?**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 7 — Average of two grades\n", "\n", "We want to calculate the average of grades `12` and `18`.\n", "\n", "Run the code and decide whether the result is correct." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "grade1 = 12\n", "grade2 = 18\n", "\n", "average = grade1 + grade2 / 2\n", "\n", "print(\"Average:\", average)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Logical error.\n", "\n", "Python reports no error because the expression is valid. Division has higher precedence than addition, so Python evaluates:\n", "\n", "```text\n", "grade1 + (grade2 / 2)\n", "```\n", "\n", "instead of:\n", "\n", "```text\n", "(grade1 + grade2) / 2\n", "```\n", "\n", "Correct version:\n", "\n", "```python\n", "average = (grade1 + grade2) / 2\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example 8 — Area of a circle\n", "\n", "The intended formula is `A = pi * r^2`.\n", "\n", "Does this program implement that formula?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "radius = 4\n", "pi = 3.14159\n", "\n", "area = pi * radius\n", "\n", "print(\"Area:\", area)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Instructor notes / solution\n", "\n", "**Category:** Logical error.\n", "\n", "The program runs correctly from Python's point of view, but the implemented formula is wrong.\n", "\n", "Correct version:\n", "\n", "```python\n", "area = pi * radius ** 2\n", "```\n", "\n", "> A program can be **valid Python** and still be **wrong**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Final discussion\n", "\n", "Classify each situation:\n", "\n", "| Situation | Syntax / pre-execution | Runtime | Logical |\n", "|---|:---:|:---:|:---:|\n", "| Missing closing `)` | ✓ | | |\n", "| Division by zero | | ✓ | |\n", "| Using an unknown variable name | | ✓ | |\n", "| Wrong mathematical formula | | | ✓ |\n", "| Missing quotation mark | ✓ | | |\n", "| Invalid value for `print(sep=...)` | | ✓ | |\n", "\n", "### Discussion questions\n", "\n", "1. Which errors prevent execution from starting?\n", "2. Which errors appear only when a particular instruction is reached?\n", "3. Which errors can Python **not** identify for us?\n", "4. Why are logical errors often the most difficult to find?\n", "5. What can a programmer do to detect logical errors?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Take-away\n", "\n", "**Syntax error** → Python cannot correctly understand the written program.\n", "\n", "**Runtime error** → Python understands the instruction, but something goes wrong while executing it.\n", "\n", "**Logical error** → Python executes the program successfully, but the program does the wrong thing.\n", "\n", "A useful habit:\n", "\n", "> **Predict → Run → Read the error → Locate the cause → Correct → Run again**" ] } ], "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": 5 }