{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Hello Python and Jupyter\n", "\n", "In this notebook you will:\n", "\n", "* Learn how to use a Jupyter notebook such as this one\n", "* Get a very quick tour of Python syntax and scientific libraries\n", "* Learn some IPython features that we will use in later tutorials" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is this?\n", "\n", "This is Jupyter notebook running in a personal \"container\" just for you, stocked with example data, demos, and tutorials that you can run and modify. All of the software you'll need is already installed and ready to use." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Run some Python code!\n", "\n", "To run the code below:\n", "\n", "1. Click on the cell to select it.\n", "2. Press `SHIFT+ENTER` on your keyboard or press the button in the toolbar above (in the toolbar above!)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "1 + 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that you can edit a cell and re-run it." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The notebook document mixes executable code and narrative content. It supports text, links, embedded videos, and even typeset math: $\\int_{-\\infty}^\\infty x\\, d x = \\frac{x^2}{2}$" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Whirlwind Tour of Python Syntax\n", "\n", "### Lists" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stuff = [4, 'a', 8.3, True]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stuff[0] # the first element" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stuff[-1] # the last element" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dictionaries (Mappings)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d = {'a': 1, 'b': 2}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d['b']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d['c'] = 3" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**TIP:** For large or nested dictionaries, it is more convient to use `list()`. Often custom python objects can be interrogated in the same manner." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Functions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def f(a, b):\n", " return a + b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In IPython `f?` or `?f` display information about `f`, such as its arguments." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If the function includes inline documentation (a \"doc string\") then `?` displays that as well." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def f(a, b):\n", " \"Add a and b.\"\n", " return a + b" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f??" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Arguments can have default values." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def f(a, b, c=1):\n", " return (a + b) * c" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f(1, 2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f(1, 2, 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Any argument can be passed by keyword. This is slower to type but clearer to read later." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f(a=1, b=2, c=3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If using keywords, you don't have to remember the argument order." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "f(c=3, a=1, b=2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fast numerical computation using numpy\n", "\n", "For numerical computing, a numpy array is more useful and performant than a plain list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "\n", "a = np.array([1, 2, 3, 4])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.mean(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "np.sin(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll use the IPython `%%timeit` magic to measure the speed difference between built-in Python lists and numpy arrays." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%timeit\n", "\n", "big = list(range(10000)) # setup line, not timed\n", "sum(big) # timed" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%timeit\n", "\n", "big = np.arange(10000) # setup line, not timed\n", "np.sum(big) # timed" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If a single loops is desired for a longer computation, use `%time` on the desired line." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "big = np.arange(10000) # setup line, not timed\n", "%time np.sum(big) # timed" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Plotting using matplotlib\n", "\n", "In an interactive setting, this will show a canvas that we can pan and zoom. (Keep reading for what we can do in a non-interactive setting, such as the static web page version of this tutorial.)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# We just have to do this line once, before we do any plotting.\n", "%matplotlib widget\n", "import matplotlib.pyplot as plt\n", "\n", "plt.figure()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can plot some data like so. In an interactive setting, this will update the canvas above." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.plot([1, 1, 2, 3, 5, 8])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And we can show a noninteractive snapshot of the state of the figure at this point by display the figure itself." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.gcf()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Displaying `plt.gcf()` (or any `Figure`) shows a non-interactive snapshot of a figure. Displaying `plt.gcf().canvas` or any `Canvas` gives us another interactive, live-updating view of the figure." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Interrupting the IPython Kernel\n", "\n", "Run this cell, and then click the square 'stop' button in the notebook toolbar to interrupt the infinite loop.\n", "\n", "(This is equivalent to Ctrl+C in a terminal.)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# This runs forever -- hit the square 'stop' button in Jupyter to interrupt\n", "# The following is \"commented out\". Un-comment the lines below to run them.\n", "# while True:\n", "# continue" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## \"Magics\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The code entered here is interpreted by _IPython_, which extends Python by adding some conveniences that help you make the most out of using Python interactively. It was originally created by a physicist, Fernando Perez.\n", "\n", "\"Magics\" are special IPython syntax. They are not part of the Python language, and they should not be used in scripts or libraries; they are meant for interactive use.\n", "\n", "The `%run` magic executes a Python script." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%run scripts/hello_world.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When the script completes, any variables defined in that script will be dumepd into our namespace. For example (as we will see below), this script happens to define a variable named `message`. Now that we have `%run` the script, `message` is in our namespace." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "message" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This behavior can be confusing, in the sense that the reader has to do some digging to figure out where ``message`` was defined and what it is, but it has its uses. Throughout this tutorial, we will use the `%run` magic as a shorthand for running boilerplate configuration code and defining variables representing hardware." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `%load` magic copies the contents of a file into a cell but does not run it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%load scripts/hello_world.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Execute the cell a second time to actually run the code. Throughout this tutorial, we use the `%load` magic to load solutions to exercises." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## System Shell Access\n", "\n", "Any input line beginning with a `!` character is passed verbatim (minus the `!`, of course) to the underlying operating system." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!ls" ] } ], "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.9.13" } }, "nbformat": 4, "nbformat_minor": 4 }