{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cDsCpe_IODXy"
      },
      "source": [
        "EE 4521/5521, Fall 2026\n",
        "\n",
        "Topic 1\n",
        "\n",
        "Professor Jarvis Haupt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Z85UfMV1KDkd"
      },
      "source": [
        "# Let's Learn Some Python (and Markdown)!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vDYs4kFK4GUz"
      },
      "source": [
        "One nice thing about Colab notebooks is that they allow us to interleave text descriptions (with $\\LaTeX$ equation editing and its nice styling, as needed...more on that later!) with code.\n",
        "\n",
        "There are two types of boxes -- code boxes and text boxes.  Clearly we are using a text box here.  An empty code box appears below:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "sqxSgZ7T5Frv"
      },
      "source": [],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Wnvj0JfK5HN1"
      },
      "source": [
        "Text boxes are quite flexible, and can be used for simple text, *stylized* text,\n",
        "\n",
        "*   Bullet\n",
        "*   Point\n",
        "*   Lists\n",
        "\n",
        "\n",
        "\n",
        "1.   Numbered\n",
        "2.   Lists\n",
        "\n",
        "\n",
        "\n",
        "and so on.  \n",
        "\n",
        "---\n",
        "\n",
        "The style for doing this is called [*markdown*](https://daringfireball.net/projects/markdown/) language. For those of you who are active on GitHub, this is similar [language](https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/quickstart-for-writing-on-github) used to create the `readme.md` files there.\n",
        "\n",
        "---\n",
        "\n",
        "\n",
        "\n",
        "If you notice above the text input area, there are a number of hotkeys that automatically modify the formatting for you, so you don't really need to learn markdown from scratch.\n",
        "\n",
        "That said, let's proceed with the programming!\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IJ73jwS7KLWb"
      },
      "source": [
        "# Printing, Strings, and Indexing in Python"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_4ZCtbNb4ghJ"
      },
      "source": [
        "Python has easy syntax for input and output.  Let's learn via a few examples.\n",
        "\n",
        "We've already seen one example embedded into the slides (an easter egg!). To print simple statements, you can do things like this:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "jhmevvTf4FdF",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "090a6097-8317-40ba-8eaf-1e520758b4e6"
      },
      "source": [
        "print(\"Hello World\")"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Hello World\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pOQ5EMBU45GP"
      },
      "source": [
        "You can execute (run) the code above by clicking on the \"play\" button to the left of the code snippet when you mouse on top of it. The output is displayed just below the snippet.\n",
        "\n",
        "Sometimes you may wish to describe a snippet of code in a text box.  These won't be executable directly, of course, but you can make them look like code by using this decorator:\n",
        "\n",
        "```\n",
        "print(\"Hello World\")\n",
        "```\n",
        "This can also be inline: `print(\"Hello World\")`.\n",
        "\n",
        "Sometimes this will be useful to call out specific instructions or segments during our discussion.  Other times we will use comment blocks in the code to describe individual segments, as below."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gmVFQkFd9ZJi",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "92e2d8c2-443a-43ba-e223-d679914fae93"
      },
      "source": [
        "# You can use single or double quotes in the print statements...\n",
        "print('Hello World')\n",
        "print(\"Hello World\")\n",
        "\n",
        "# The main difference is that you need to use escape sequences properly\n",
        "# depending on which you choose...\n",
        "print('The computer said \"Hello World\"')\n",
        "\n",
        "# But this wouldn't work...uncomment it and try it!\n",
        "# print(\"The computer said \"Hello World\"\")\n",
        "\n",
        "# To make the above work, you need to use an escape character\n",
        "# (uncomment and try!)\n",
        "print(\"The computer said \\\"Hello World\\\"\")"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Hello World\n",
            "Hello World\n",
            "The computer said \"Hello World\"\n",
            "The computer said \"Hello World\"\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yjEOjfez1g9B"
      },
      "source": [
        "We can also concatenate different words in a print statement"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Q6RUHvQF8Zyw",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "68c5d64a-31f4-4861-9089-09b54c75aa31"
      },
      "source": [
        "print(\"Hello \" + \"World, \" + \"I am Learning Python!\")\n",
        "print(\"Hello\", \"World\")\n",
        "# Spaces are important!"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Hello World, I am Learning Python!\n",
            "Hello World\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oyq7RKjL1pSF"
      },
      "source": [
        "Sometimes it's useful to print the values of numbers..."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "pzDMDsne1pnf",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "275ac01e-f218-4608-d4bf-4a5f7a40df51"
      },
      "source": [
        "# Sometimes it's useful to print the values of numbers\n",
        "x = 3.14\n",
        "print(x)\n",
        "\n",
        "# If we want to have this mingling with text,\n",
        "# we need to cast the variable as a string...\n",
        "print(\"Pi to 2 decimal places is \" + str(x))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "3.14\n",
            "Pi to 2 decimal places is 3.14\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "auc_wnTY-WRf"
      },
      "source": [
        "In the above examples, we see how Python can flexibly print different data types, using one simple print statement (as long as we mind the syntax).  Let's look at a few more sophisticated examples."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1pBwE18F8ffD",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f24f919b-fd61-4278-ab76-72bf374bd577"
      },
      "source": [
        "# Libraries are a key component of Python usage.\n",
        "# We'll see further examples of this later, but for now,\n",
        "# let's consider this example.\n",
        "from math import pi\n",
        "print(pi)\n",
        "\n",
        "# the 'math' library contains many built in constants and functions\n",
        "# see: https://docs.python.org/3/library/math.html\n",
        "\n",
        "# As to printing, we can tell Python how many\n",
        "# digits to print of pi via\n",
        "print('Pi to 5 decimal places is %0.5f' % pi)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "3.141592653589793\n",
            "Pi to 5 decimal places is 3.14159\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XeI5nPplAxe2"
      },
      "source": [
        "In the above examples we sometimes printed numbers by casting them as strings.  Sometimes we can use string casted numbers to extract useful segments.  \n",
        "\n",
        "Now, let's extract some digits of $\\pi$. Technically speaking, if we executed the instructions above before executing this,\n",
        " then the constants are already loaded in and we don't need to import again.  So...let's force it to look like a new workspace"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "wc_n8EQSA_uH",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f1dc5944-fbd3-4aef-e746-ff7f0a6409d0"
      },
      "source": [
        "# This should reset the workspace\n",
        "%reset -f\n",
        "\n",
        "from math import pi\n",
        "print(pi)\n",
        "\n",
        "# get a string with 15 pi decimal digits\n",
        "pi_string = str('%0.15f' % pi)\n",
        "print(pi_string)\n",
        "print(len(pi_string))\n",
        "# the length is 17 because of the '3' and the '.'"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "3.141592653589793\n",
            "3.141592653589793\n",
            "17\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wdiz_zXkCv4R"
      },
      "source": [
        "Now let's index this string we created (`pi_string`) a bit to see how it works.  It's different than in some other common languages..."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "s63npN5EC3W0",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "bebf67bf-3daf-467c-8a68-9ea55221f0e1"
      },
      "source": [
        "# Print the whole string\n",
        "print(pi_string[:])\n",
        "\n",
        "# Print the first 3 characters\n",
        "print(pi_string[0:3])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "3.141592653589793\n",
            "3.1\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dLY_jXT7DDQz"
      },
      "source": [
        "The indexing in python starts at 0 (like C/C++, but unlike Matlab!).\n",
        "\n",
        "Notice the other strange thing -- the final index was exclusive; in other words, the index range [0:3] printed the characters at indices 0, 1, and 2 (but NOT 3).  The starting index, in contrast, is inclusive."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "SQZ8hw8mDXyP",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a5040866-9b5a-4d43-9cec-0fed0aec5f74"
      },
      "source": [
        "# Some more indexing\n",
        "# The actual answer:\n",
        "print('Pi to 7 decimal digits is (approximately!) %0.7f' % pi)\n",
        "print('The first 7 decimal digits of pi are ' + pi_string[2:9])\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Pi to 7 decimal digits is (approximately!) 3.1415927\n",
            "The first 7 decimal digits of pi are 1415926\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "phpZ-kHhD9XZ"
      },
      "source": [
        "Note that the first instruction did *rounding* by default, while the second took the exact digits.  This is a simple example to show that we need to know what's going on \"under the hood\" in each of these routines to become good programmers!\n",
        "\n",
        "Let's look at a few more indexing examples..."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1KjqytRSH0Ta",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "68db7f16-8a65-41bf-dd80-64864691f0ad"
      },
      "source": [
        "# A familiar string\n",
        "alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n",
        "\n",
        "# Last element\n",
        "print(alphabet[-1])\n",
        "\n",
        "# Last 3 elements\n",
        "print(alphabet[-3:])\n",
        "\n",
        "# Every other element starting with A\n",
        "print(alphabet[0::2])\n",
        "# This does the same thing\n",
        "# print(alphabet[::2])\n",
        "\n",
        "# Every other element starting with B\n",
        "print(alphabet[1::2])\n",
        "\n",
        "# Backwards\n",
        "print(alphabet[::-1])\n",
        "\n",
        "# Every other element working backwards, starting with Z\n",
        "back_alphabet = alphabet[::-1]\n",
        "print(back_alphabet[::2])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Z\n",
            "XYZ\n",
            "ACEGIKMOQSUWY\n",
            "BDFHJLNPRTVXZ\n",
            "ZYXWVUTSRQPONMLKJIHGFEDCBA\n",
            "ZXVTRPNLJHFDB\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "N2IeV0djFDvV"
      },
      "source": [
        "Now let's see some examples of how we can acquire and process inputs from users in python.\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XkyGtmuIKSBC"
      },
      "source": [
        "# Input/Output"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "avTlZp3-FULu",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "051d20b6-5072-4efb-fe47-ccf8acf24e84"
      },
      "source": [
        "%reset -f\n",
        "\n",
        "# User inputs!\n",
        "# print(\"What is your name?\")\n",
        "# your_name = input()\n",
        "your_name = input(\"What is your name? \")\n",
        "print(\"Hello \" + your_name + \"!\")\n",
        "\n",
        "# Let's write a cute little program...\n",
        "from math import pi\n",
        "\n",
        "# The escape sequence \\n prints a new line\n",
        "# and the \\ is line continuation (to break commands over multiple lines)\n",
        "print(\"\\nHow many decimal digits of pi should I print?\\n(Enter an \" +\n",
        "      \"integer < 15 - I'm not checking inputs for formatting and correctness!)\")\n",
        "num_digits = input()\n",
        "\n",
        "pi_string = str('%0.15f' % pi)\n",
        "start_index = 2\n",
        "\n",
        "# Inputs are STRINGS! Need to cast it as an integer to make it work here\n",
        "end_index = int(num_digits)+2\n",
        "print('Here\\'s the answer: ' + pi_string[start_index:end_index])\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "What is your name? Jarvis\n",
            "Hello Jarvis!\n",
            "\n",
            "How many decimal digits of pi should I print?\n",
            "(Enter an integer < 15 - I'm not checking inputs for formatting and correctness!)\n",
            "4\n",
            "Here's the answer: 1415\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "The `%` prefix indicates to the kernel that you're using so-called \"[magic commands](https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/01.03-Magic-Commands.ipynb).\" At a high level, you can think of these as shell-type commands (or something you might run in a terminal).  Here is a list of the magic commands:"
      ],
      "metadata": {
        "id": "5Y4OBLRAlb5X"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "%lsmagic"
      ],
      "metadata": {
        "id": "i-7C5O-pl4hY",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 1000
        },
        "outputId": "f0b6092c-9323-475f-e9d3-da1a85130cfa"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "Available line magics:\n",
              "%alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cat  %cd  %clear  %colors  %conda  %config  %connect_info  %cp  %debug  %dhist  %dirs  %doctest_mode  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %lf  %lk  %ll  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %lx  %macro  %magic  %man  %matplotlib  %mkdir  %more  %mv  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %rep  %rerun  %reset  %reset_selective  %rm  %rmdir  %run  %save  %sc  %set_env  %shell  %store  %sx  %system  %tb  %tensorflow_version  %time  %timeit  %unalias  %unload_ext  %who  %who_ls  %whos  %xdel  %xmode\n",
              "\n",
              "Available cell magics:\n",
              "%%!  %%HTML  %%SVG  %%bash  %%bigquery  %%bqsql  %%capture  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%shell  %%spanner_graph  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n",
              "\n",
              "Automagic is ON, % prefix IS NOT needed for line magics."
            ],
            "application/json": {
              "line": {
                "automagic": "AutoMagics",
                "autocall": "AutoMagics",
                "alias_magic": "BasicMagics",
                "lsmagic": "BasicMagics",
                "magic": "BasicMagics",
                "page": "BasicMagics",
                "pprint": "BasicMagics",
                "colors": "BasicMagics",
                "xmode": "BasicMagics",
                "quickref": "BasicMagics",
                "doctest_mode": "BasicMagics",
                "gui": "BasicMagics",
                "precision": "BasicMagics",
                "notebook": "BasicMagics",
                "save": "CodeMagics",
                "pastebin": "CodeMagics",
                "loadpy": "CodeMagics",
                "load": "CodeMagics",
                "edit": "KernelMagics",
                "config": "ConfigMagics",
                "prun": "ExecutionMagics",
                "pdb": "ExecutionMagics",
                "debug": "ExecutionMagics",
                "tb": "ExecutionMagics",
                "run": "ExecutionMagics",
                "timeit": "ExecutionMagics",
                "time": "ExecutionMagics",
                "macro": "ExecutionMagics",
                "load_ext": "ExtensionMagics",
                "unload_ext": "ExtensionMagics",
                "reload_ext": "ExtensionMagics",
                "history": "HistoryMagics",
                "recall": "HistoryMagics",
                "rerun": "HistoryMagics",
                "logstart": "LoggingMagics",
                "logstop": "LoggingMagics",
                "logoff": "LoggingMagics",
                "logon": "LoggingMagics",
                "logstate": "LoggingMagics",
                "pinfo": "NamespaceMagics",
                "pinfo2": "NamespaceMagics",
                "pdef": "NamespaceMagics",
                "pdoc": "NamespaceMagics",
                "psource": "NamespaceMagics",
                "pfile": "NamespaceMagics",
                "psearch": "NamespaceMagics",
                "who_ls": "NamespaceMagics",
                "who": "NamespaceMagics",
                "whos": "NamespaceMagics",
                "reset": "NamespaceMagics",
                "reset_selective": "NamespaceMagics",
                "xdel": "NamespaceMagics",
                "alias": "OSMagics",
                "unalias": "OSMagics",
                "rehashx": "OSMagics",
                "pwd": "OSMagics",
                "cd": "OSMagics",
                "env": "OSMagics",
                "set_env": "OSMagics",
                "pushd": "OSMagics",
                "popd": "OSMagics",
                "dirs": "OSMagics",
                "dhist": "OSMagics",
                "sc": "OSMagics",
                "sx": "OSMagics",
                "system": "OSMagics",
                "bookmark": "OSMagics",
                "pycat": "OSMagics",
                "pip": "Other",
                "conda": "PackagingMagics",
                "matplotlib": "PylabMagics",
                "pylab": "PylabMagics",
                "killbgscripts": "ScriptMagics",
                "autoawait": "AsyncMagics",
                "ed": "Other",
                "hist": "Other",
                "rep": "Other",
                "clear": "KernelMagics",
                "less": "KernelMagics",
                "more": "KernelMagics",
                "man": "KernelMagics",
                "connect_info": "KernelMagics",
                "qtconsole": "KernelMagics",
                "autosave": "KernelMagics",
                "store": "StoreMagics",
                "shell": "Other",
                "tensorflow_version": "Other",
                "mkdir": "Other",
                "rmdir": "Other",
                "mv": "Other",
                "rm": "Other",
                "cp": "Other",
                "cat": "Other",
                "ls": "Other",
                "ll": "Other",
                "lf": "Other",
                "lk": "Other",
                "ldir": "Other",
                "lx": "Other"
              },
              "cell": {
                "js": "DisplayMagics",
                "javascript": "DisplayMagics",
                "latex": "DisplayMagics",
                "svg": "DisplayMagics",
                "html": "DisplayMagics",
                "markdown": "DisplayMagics",
                "prun": "ExecutionMagics",
                "debug": "ExecutionMagics",
                "timeit": "ExecutionMagics",
                "time": "ExecutionMagics",
                "capture": "ExecutionMagics",
                "sx": "OSMagics",
                "system": "OSMagics",
                "!": "OSMagics",
                "writefile": "OSMagics",
                "script": "ScriptMagics",
                "sh": "Other",
                "bash": "Other",
                "perl": "Other",
                "ruby": "Other",
                "python": "Other",
                "python2": "Other",
                "python3": "Other",
                "pypy": "Other",
                "SVG": "Other",
                "HTML": "Other",
                "file": "Other",
                "bqsql": "Other",
                "bigquery": "Other",
                "spanner_graph": "NetworkVisualizationMagics",
                "shell": "Other"
              }
            }
          },
          "metadata": {},
          "execution_count": 13
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "LdWCr5M6Y_RV"
      },
      "source": [
        "# Advanced I/O"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GAJvPh74ZFSp"
      },
      "source": [
        "For our last topic of this lesson, let's take a (quick) look at some advanced input/output capabilities in Python.\n",
        "\n",
        "First, Python has the ability to print so-called *formatted string literal* outputs using the `f` command. It's probably easiest to see this via example:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "rLFwiMOjZeU9",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ca295a3c-9375-4841-d1bf-9875dfcde7e4"
      },
      "source": [
        "# Printing formatted outputs\n",
        "from math import pi\n",
        "\n",
        "print(f'The value of pi is approximately {pi}')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The value of pi is approximately 3.141592653589793\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_Kt8fElXZ9tO"
      },
      "source": [
        "In the above, the part in brakets `{}` is essentially Python code.\n",
        "\n",
        "You can likewise control the number of digits using formatting statements, as well as spacings.  Let's see some examples."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "1H5y1Zbwfkjh",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b2b4bd36-2ea4-4cef-bad8-13b61bdb9f00"
      },
      "source": [
        "# Spacings and formatting for literals\n",
        "\n",
        "# formatting\n",
        "from math import pi\n",
        "print(f'The value of pi to 3 decimal digits is approximately {pi:0.3f}')\n",
        "\n",
        "# spacing - here the parameter '10' after the colon dictates the output width\n",
        "print('\\n')\n",
        "import math\n",
        "constants = ['pi', 'e']\n",
        "print(f'The value of {constants[0]:10} is {math.pi:10.3f}')\n",
        "print(f'The value of {constants[1]:10} is {math.e:10.3f}\\n')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The value of pi to 3 decimal digits is approximately 3.142\n",
            "\n",
            "\n",
            "The value of pi         is      3.142\n",
            "The value of e          is      2.718\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2rDwaVHBjOyC"
      },
      "source": [
        "There are many other string formatting tools (`str.rjust`, `str.ljust`, `str.center`, `str.format`, etc.).  Online documentation (from a number of various sources) is a useful aid!"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Q4hwLgRJh_vz"
      },
      "source": [
        "The last topic for today concerns file inputs and outputs.  This is a rich topic, to be sure, and nuanced implementations can be assisted via clever search engine use.  But, let's look at a simple example that writes formatted data to a file and reads it back again."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "a2-64E_-jnx-",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "27a0354c-c7f9-48eb-9f09-d989ea364a86"
      },
      "source": [
        "# file writing and reading\n",
        "\n",
        "# open a (here, new) file and write some data\n",
        "f = open('myfile','w')\n",
        "f.write('This is the first line\\n')\n",
        "f.write('This is the second line\\n')\n",
        "f.close()\n",
        "print(f.closed)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "True\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "I4yUJBjXlW7c",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1d28962e-f56d-4b3f-cd7d-9626f425a23e"
      },
      "source": [
        "# read the whole file\n",
        "g = open('myfile','r')\n",
        "print(g.read())\n",
        "g.close()\n",
        "print(g.closed)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "This is the first line\n",
            "This is the second line\n",
            "\n",
            "True\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BiGH-L44mZyP",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "64436b85-4ca5-4386-8b6f-7d7137b9aa51"
      },
      "source": [
        "# read from the file one line at a time\n",
        "g = open('myfile','r')\n",
        "\n",
        "for line in g:\n",
        "  # this prints the line and forces the last character to *not* be a newline\n",
        "  # to avoid adding an extra newline character\n",
        "  print(line,end='')\n",
        "g.close()\n",
        "print(g.closed)\n"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "This is the first line\n",
            "This is the second line\n",
            "True\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "slCB8jWZm53M"
      },
      "source": [
        "Suffice it to say, this simple structure can be useful when tabulating data from an experiment, and reading it again for processing.  "
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# JavaScript Object Notation (JSON)"
      ],
      "metadata": {
        "id": "U1k61QLagRDr"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "It's natural to ask what should be the \"format\" that we use to store data in files.  While this can be somewhat arbitrary for any application for which you're creating and reading your own data files, it's probaby a good habit to become familiar with standard methods for data storage and exchange.  Among these, perhaps the most common format is JavaScript Object Notation, or [JSON](https://www.json.org/json-en.html).\n",
        "\n",
        "Among its (many?) virtues are the facts that JSON is widely used, well-supported, and perhaps most comfortingly, human readable.  At its essence, the JSON standard prescribes storing data in name/value pairs separated by a colon `:`.  A set of such pairs (separated by commas `,`) is called an *object*, and in data files each object is delineated using \"curly braces\" `{}`.\n",
        "\n",
        "Below is an example of a JSON object describing a student's course schedule.  One could imagine this being the content of a JSON file named, for instance, `FavoriteFall2025Course.json`.  Note that I'm displaying the contents of the file here by putting the text into a Code box, but that's just to make the formatting *nice*, and this code is definitely not executable!"
      ],
      "metadata": {
        "id": "bmBkMhjJgSTd"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "{\"Course Name\": \"Intro to Machine Learning and Data Science for Electrical and Computer Engineers\", \"Course Department\": \"ECE\",\n",
        "\"Course Number\": 4521, \"Grade\": null}"
      ],
      "metadata": {
        "id": "Opk9VjmggXJp"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Notice here that the \"values\" (the quantity after the colon for each name) can be of different types.  Above we used the \"String,\" \"Number,\" and \"null\" types, but you can also use \"Boolean\" (`true` or `false`) values.  In fact, the values can even themselves be objects (delimited, again, with curly braces), or even arrays (of values, objects, or other arrays) delimited with brackets `[]`.\n",
        "\n",
        "The JSON Number format is fairly flexible, allowing (positive or negative) integers, decimal values, and even floating point values expressed using the \"e\" or \"E\" exponential notation.  For example, one could write a (truncated) version of Avogadro's number ($N_A\\approx6.022 \\times 10^{23}$ particles per mole) as `6.022e23` or `6.022E23` in the value field of a JSON file.  It's important to note that this format assumes the exponent is positive, though we can also express very small numbers (like the elementary charge $e\\approx 1.602 \\times 10^{-19}$ Coulombs) as `1.602e-19` in JSON.\n",
        "\n",
        "Here's an example of a more elaborate JSON file from the [Wikipedia JSON page](https://en.wikipedia.org/wiki/JSON):"
      ],
      "metadata": {
        "id": "yvgEQjlAgZrk"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "{\n",
        "  \"first_name\": \"John\",\n",
        "  \"last_name\": \"Smith\",\n",
        "  \"is_alive\": true,\n",
        "  \"age\": 27,\n",
        "  \"address\": {\n",
        "    \"street_address\": \"21 2nd Street\",\n",
        "    \"city\": \"New York\",\n",
        "    \"state\": \"NY\",\n",
        "    \"postal_code\": \"10021-3100\"\n",
        "  },\n",
        "  \"phone_numbers\": [\n",
        "    {\n",
        "      \"type\": \"home\",\n",
        "      \"number\": \"212 555-1234\"\n",
        "    },\n",
        "    {\n",
        "      \"type\": \"office\",\n",
        "      \"number\": \"646 555-4567\"\n",
        "    }\n",
        "  ],\n",
        "  \"children\": [\n",
        "    \"Catherine\",\n",
        "    \"Thomas\",\n",
        "    \"Trevor\"\n",
        "  ],\n",
        "  \"spouse\": null\n",
        "}"
      ],
      "metadata": {
        "id": "EhNNIoO6gcxJ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Notice, in particular, how the value associated with the \"address\" name is an object, the \"phone numbers\" value is an array of objects, and the \"children\" value is an array of strings.  Notice, also, that the entire file consists of one object (all enclosed in `{}`).\n",
        "\n",
        "A few other considerations:\n",
        "* Strictly speaking, the JSON standard doesn't allow comments, though you could always include a comment entry in an object if needed.\n",
        "* Indentation enhances readability, but unlike Python, whitespace and indentation in JSON files is ignored essentially everywhere except inside strings.\n",
        "* Perhaps most importantly for our purposes, there exist easy-to-use Python packages for reading, writing, and utilizing data stored in JSON format.\n",
        "\n",
        "Let's see a quick example.  For that, we'll turn the example above into a JSON file (called `reading_example.json`) and use Python to read the contents in.  For fun, let's also add in another name/value pair indicating the person's height, and let's use a floating point number for that (something like `\"height\": 1.8`)."
      ],
      "metadata": {
        "id": "JgwNcoZtgfKu"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# JSON Example\n",
        "import json\n",
        "\n",
        "file = open('reading_example.json', 'r')\n",
        "file_contents = json.load(file)\n",
        "file.close()\n",
        "# Don't forget to close files!!\n",
        "\n",
        "# Display the output\n",
        "print(file_contents)\n",
        "print(type(file_contents))\n"
      ],
      "metadata": {
        "id": "VV_FjtCwghP8",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "667a74be-deae-4c9e-d2c9-3767e57aa7a8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'first_name': 'John', 'last_name': 'Smith', 'is_alive': True, 'age': 27, 'height': 1.8, 'address': {'street_address': '21 2nd Street', 'city': 'New York', 'state': 'NY', 'postal_code': '10021-3100'}, 'phone_numbers': [{'type': 'home', 'number': '212 555-1234'}, {'type': 'office', 'number': '646 555-4567'}], 'children': ['Catherine', 'Thomas', 'Trevor'], 'spouse': None}\n",
            "<class 'dict'>\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "The output isn't as human-readable as we might hope (becuase the data runs in\n",
        "one long line).  Let's try to fix that."
      ],
      "metadata": {
        "id": "VLN9TXq5gmbq"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import pprint\n",
        "# This is \"pretty print\" and it works well with Python dictionaries...\n",
        "\n",
        "# Here's how to call it:\n",
        "pprint.pprint(file_contents, sort_dicts = False)"
      ],
      "metadata": {
        "id": "l_LYwKtjgp4t",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "bf19fdf0-4be6-4fe4-d170-05ee43993e58"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "{'first_name': 'John',\n",
            " 'last_name': 'Smith',\n",
            " 'is_alive': True,\n",
            " 'age': 27,\n",
            " 'height': 1.8,\n",
            " 'address': {'street_address': '21 2nd Street',\n",
            "             'city': 'New York',\n",
            "             'state': 'NY',\n",
            "             'postal_code': '10021-3100'},\n",
            " 'phone_numbers': [{'type': 'home', 'number': '212 555-1234'},\n",
            "                   {'type': 'office', 'number': '646 555-4567'}],\n",
            " 'children': ['Catherine', 'Thomas', 'Trevor'],\n",
            " 'spouse': None}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "It's interesting to note here that the data type returned by the `json.load` command is `dict`.  In Python, dictionaries are conceptually similar to JSON objects themselves, in that they represent a collection of key/value pairs.  If you know the names of the keys, you can access the values."
      ],
      "metadata": {
        "id": "88ZFtF-ZgsZY"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "print(file_contents['first_name'])\n",
        "print(file_contents['phone_numbers'])\n",
        "\n",
        "# We can try to \"pretty print\" the second one for readability too\n",
        "pprint.pprint(file_contents['phone_numbers'], sort_dicts = False)\n",
        "\n",
        "\n",
        "# Note that we used single quotes here to describe the name values\n",
        "# because that works within Python syntax.  But, strictly speaking, JSON\n",
        "# names should all be strings in double quotes! Fortunately we could use\n",
        "# double quotes in Python too, without any issue.\n",
        "print(file_contents[\"first_name\"])"
      ],
      "metadata": {
        "id": "2ELBJBcsguqZ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3e10a1df-b85c-48a5-d7ca-65cd5eac93fb"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "John\n",
            "[{'type': 'home', 'number': '212 555-1234'}, {'type': 'office', 'number': '646 555-4567'}]\n",
            "[{'type': 'home', 'number': '212 555-1234'},\n",
            " {'type': 'office', 'number': '646 555-4567'}]\n",
            "John\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "It's even easy enough to index into more complicated elements of the dictionary."
      ],
      "metadata": {
        "id": "vQG6YuBfgw8K"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# We'll use some empty print statements -- like print() -- to format the output\n",
        "\n",
        "my_data = file_contents['phone_numbers']\n",
        "print(type(my_data))\n",
        "print(my_data)\n",
        "# We see that this value is actually a Python list, so we can treat it as such\n",
        "\n",
        "# Let's print the first element of the list\n",
        "print(my_data[0])\n",
        "print()\n",
        "\n",
        "# If you want, you can also be a bit more terse with the code\n",
        "# and accomplish the same objective\n",
        "print(file_contents['phone_numbers'][0])\n",
        "print()\n",
        "\n",
        "# and even do more sub-indexing...in this case extracting the phone number\n",
        "# as a string\n",
        "print(file_contents['phone_numbers'][0]['number'])\n",
        "print(type(file_contents['phone_numbers'][0]['number']))\n",
        "print()\n",
        "\n",
        "# Let's also take a look at the types of the age and height values, to see\n",
        "# that Python correctly parsed them\n",
        "print(type(file_contents['age']))\n",
        "print(type(file_contents['height']))\n"
      ],
      "metadata": {
        "id": "t-Tec_bjgzTa",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "6c0d91ab-75e9-4fd6-af16-2c756674a2ad"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "<class 'list'>\n",
            "[{'type': 'home', 'number': '212 555-1234'}, {'type': 'office', 'number': '646 555-4567'}]\n",
            "{'type': 'home', 'number': '212 555-1234'}\n",
            "\n",
            "{'type': 'home', 'number': '212 555-1234'}\n",
            "\n",
            "212 555-1234\n",
            "<class 'str'>\n",
            "\n",
            "<class 'int'>\n",
            "<class 'float'>\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "As you probably imagined, we can also easily write data into a JSON file from Python.  Here's a quick example of that."
      ],
      "metadata": {
        "id": "XiDoIBXLg2on"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# JSON Example\n",
        "import json\n",
        "\n",
        "# Open a file for writing\n",
        "file = open('writing_example.json', 'w')\n",
        "\n",
        "# Synthesize some data, express it as a dictionary\n",
        "my_data = {\"x_values\": [1,2,3,4,5,7.1], \"y_values\": [1,4,9,16,25,50.41]}\n",
        "\n",
        "# Then write (dump) it to a JSON file\n",
        "json.dump(my_data,file)\n",
        "\n",
        "# Don't forget to close the file!\n",
        "file.close()"
      ],
      "metadata": {
        "id": "8X-oF8Rzg4zq"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Further Reading"
      ],
      "metadata": {
        "id": "nTCeABLcspiO"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "You can read some more about Python style (and philosophy) [here](https://peps.python.org/pep-0000/)."
      ],
      "metadata": {
        "id": "oRs2Mb2Csqvt"
      }
    }
  ]
}