{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Jupyter Notebooks\n", "\n", "This book focuses on coding Python using jupyter ntoebooks.\n", "They are extremely practical and common when using\n", "Python to solve problems in other disciplines.\n", "The purpose of this jupyter notebook is to allow you to become\n", "more familiar with jupyter notebooks and their different components,\n", "introduce you to the idea of comments,\n", "and to encourage thoroughly describing your code via surrounding\n", "text or comments as appropriate." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jupyter Notebooks\n", "\n", "Jupyter notebooks are made up of \"cells\". Cells have various types,\n", "but the two most common (by far) are:\n", "\n", "* Code - a cell containing code (for our class Python, but jupyter notebooks\n", " are also used with other langauges like R)\n", "* Markdown - a cell with formatted text. Markdown is what's known as a\n", " markup language that allows you to write in plain text, but using\n", " simple notation that will be displayed in a formatted manner. This\n", " cell is a markdown cell.\n", "\n", "The currently selected cell\n", "can be \"run\" using the play icon (right-pointing triangle).\n", "What happens when you run a cell depends on its type. For a code\n", "cell, it simply runs the code in the cell. For a markdown cell,\n", "run means to display the formatted text. \n", "\n", "Later cells will illustrate the basic features of markdown, but first\n", "we'll look at a few code cells.\n", "\n", "### Code Cells\n", "\n", "#### Running Code Cells\n", "Select the below cell and run. You'll notice that the originally\n", "empty brackets on the left now have a number. For a long running\n", "cell, those brackets would first go to an \\* which turns into a\n", "number once the cell finishes running.\n", "\n", "Now try running the 2nd code cell. Note that that cell has a\n", "number in brackets that is 1 greater than the previously run\n", "cell -- the numbering will always go up in the order you run\n", "them. Rerunning a cell will update the number in brackets \n", "(to make sure the numbers in brackets always reflect the\n", "order in which the cells have been run).\n", "\n", "**Note:** notebooks do not by default run all cells. So,\n", "if you open a notebook and jump to the end and try to run\n", "a cell, it will error if it depends on previous cells that\n", "had not been run yet. \n", "\n", "There are a few options to run multiple cells without\n", "having to click and run each individually. If you go to \"Cell\"\n", "(if running in traditional jupyter notebooks) or \"Runtime\" (if running on Google Colab)\n", "in the menu bar at the top, there should be:\n", "\n", "* \"Run all\" - this will run all of the cells in the notebook\n", " in order from top to bottom\n", "* \"Run all above\" - this will run all of the cells in the notebook\n", " above the currently selected cell. This can be helpful when you\n", " want to jump in to programming in the middle of a longer notebook.\n", "* \"Run all below\" - this will run all of the cells in the notebook\n", " below the currently selected cell. This can be helpful if you need\n", " to change something in the middle and recompute all the results\n", " after with that change.\n", " \n", "#### Stopping a Running Cell\n", "Sometimes, a cell may run for far longer than anticipated (sometimes\n", "this happens if you have a bug in your code), you can\n", "always stop the running of cells with the stop button (the black square).\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 5\n", "y = 8" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "z = x+y\n", "print(z)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(x)\n", "print(y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "w = x + y + z" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(w)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Clearing Cell Output\n", "The output of the code cell will naturally persist, even if you close the\n", "notebook. This is really helpful if you are creating a report, but\n", "sometimes you may want to remove it (for instance if you'd like to follow\n", "along with the lecture notebooks). You have two options to remove output:\n", "\n", "* \"Clear output\" - this removes the output for the currently selected\n", " cell\n", " * By clicking \"Cell\" at the top if running as a traditional jupyter notebook\n", " * By clicking the three dots at the far right of the cell on Google's\n", " Colab\n", "* \"Clear all output\" - this removes the output for all cells in the\n", " notebook\n", " * By clicking \"Cell\" at the top if running as a traditional jupyter notebook\n", " * By clicking \"Runtime\" at the top on Google's Colab\n", " \n", "#### Variable State\n", "One interesting thing about Jupyter notebooks, in comparison to\n", "a simple python script is the idea that the variable state can\n", "change more because you can rerun cells.\n", "\n", "Consider the following code cells. Run the first one multiple\n", "times. What happens?\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "z += 1\n", "print(z)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "z += 2\n", "print(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We see that the value of `z` keeps incrementing by one. This\n", "makes sense because it's what we are telling it to do, but in\n", "a python script we don't have this concept of rerunning the same\n", "line of code (we'd have to copy it).\n", "\n", "**Why does this matter?** In Jupyter notebooks, we need to be careful\n", "to understand the idea variable state, which persists throughout\n", "the notebook, regardless of whether it was changed below the current\n", "cell. Try running the second cell above, followed by the first cell.\n", "Notice how the first cell added 1 to the result of the second cell, even\n", "though the second cell comes physically after? \n", "\n", "**So what?** Sometimes we want to basically start fresh. We have 2\n", "options:\n", "\n", "* Restarting the whole kernel - Note, this does not clear\n", " output -- even though there is output, you'd need to rerun cells\n", " before using a variable.\n", " * Google Colab: under the \"Runtime\" heading click \"Restart runtime\"\n", " * Traditional jupyter notebooks: under the \"Kernel\" heading at top click\n", " \"Restart kernel\" or by pressing\n", " the refresh button (circle with arrows). \n", "* \"Restart and run all\" - restarts kernel and reruns all of the cells\n", " * Google Colab: under the \"Runtime\" heading\n", " * Traditional jupyter notebooks: under the \"Kernel\" heading or the button that\n", " resembles fast-forward. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Markdown Cells\n", "\n", "This is an example of a markdown cell. Markdown allows you to\n", "easily have headings to separate sections, **bold** text, *italic* text,\n", "lists, tables, images, block quotes, math (latex). See the\n", "[jupyter markdown documentation](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Working%20With%20Markdown%20Cells.html)\n", "and [markdown cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)\n", "for examples of everything you can do in markdown, but\n", "double clicking this cell (to see the markdown \"source\"\n", "will give you a few examples).\n", "\n", "Using these cells can be very helpful for a few reasons, but the\n", "primary use is that it allows a self-contained report-like document\n", "where you can describe all aspects including the problem itself, any\n", "data, any equations, relevant images, links to other resources\n", "or the data sources, etc. Because of this, Jupyter notebooks are\n", "extremely popular and a great tool for applied computing.\n", "\n", "\n", "#### Math Example\n", "This is just plain old latex:\n", "$$V = \\frac{4}{3}\\pi r^3$$\n", "\n", "#### Lists Example - this line is a heading\n", "Can have multiple levels of nested combos of ordered and unordered:\n", "\n", "* list item\n", " 1. sublist item 1\n", " 2. sublist item 2\n", "* list item\n", " * nested bullet\n", " * nested bullet\n", "* list item\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Commenting Code\n", "\n", "One of the reasons we write code is to automate a process that needs\n", "to be done frequently or is to tedious/difficult to do manually. \n", "We want to make sure that our code is:\n", "\n", "* understandable - to us and to others who may use it\n", "* maintainable - in good shape without a bunch of extra\n", " unused code\n", "\n", "We've already shown how the choice of descriptive variable names\n", "can make a big difference. Another important technique is the\n", "idea of \"commenting\".\n", "\n", "The idea is to add written comments (ignored by the program) that\n", "describe what the code is doing.\n", "With our simple uses of code so far, these may seem\n", "unnecessary, but imagine having hundreds of lines of code, leaving\n", "it for 6 months, then trying to come back and modify without any\n", "sort of description of what the code does -- it won't go well!\n", "\n", "In Jupyter notebooks, heavy use of markdown cells often eliminates\n", "the need for many of the comments. However, in scripts they are crucial\n", "and they are still often used within cells with large amounts of\n", "code.\n", "\n", "Single-line comments in python are lines beginning with \\#.\n", "These lines are completely ignored by python. Typically comments\n", "go immediately above line (or few lines) of code they apply to.\n", "For comments that apply to only one line, you can have the\n", "comment at the end of the line after code." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# computes volume of sphere\n", "diam = 6\n", "vol = (4/3)*3.14159*(diam/2)**3 # approximates pi" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes you want to have longer comments (multiple lines).\n", "This is less common in Jupyter notebooks (if you are thinking\n", "you need a multiline comment, in reality you should probably\n", "consider a markdown cell instead). But, since they are common\n", "in scripts, you can create one use triple quotes, i.e." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'''\n", "This is a multiline comment\n", "Below is a random line of code w\n", "'''\n", "q = 6 " ] } ], "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.6" } }, "nbformat": 4, "nbformat_minor": 4 }