{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Crash Course" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hello! This is a quick intro to programming in Python to help you hit the ground running with the _12 Steps to Navier–Stokes_. \n", "\n", "There are two ways to enjoy these lessons with Python:\n", "\n", "1. You can download and install a Python distribution on your computer. One option is the free [Anaconda Scientific Python](https://store.continuum.io/cshop/anaconda/) distribution. Another is [Canopy](https://www.enthought.com/products/canopy/academic/), which is free for academic use. Our recommendation is Anaconda.\n", "\n", "2. You can run Python in the cloud using [Wakari](https://wakari.io/) web-based data analysis, for which you need to create a free account. (No software installation required!)\n", "\n", "In either case, you will probably want to download a copy of this notebook, or the whole AeroPython collection. We recommend that you then follow along each lesson, experimenting with the code in the notebooks, or typing the code into a separate Python interactive session.\n", "\n", "If you decided to work on your local Python installation, you will have to navigate in the terminal to the folder that contains the .ipynb files. Then, to launch the notebook server, just type:\n", "ipython notebook\n", "\n", "You will get a new browser window or tab with a list of the notebooks available in that folder. Click on one and start working!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Libraries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python is a high-level open-source language. But the _Python world_ is inhabited by many packages or libraries that provide useful things like array operations, plotting functions, and much more. We can import libraries of functions to expand the capabilities of Python in our programs. \n", "\n", "OK! We'll start by importing a few libraries to help us out. First: our favorite library is **NumPy**, providing a bunch of useful array operations (similar to MATLAB). We will use it a lot! The second library we need is **Matplotlib**, a 2D plotting library which we will use to plot our results.\n", "The following code will be at the top of most of your programs, so execute this cell first:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# <-- comments in python are denoted by the pound sign, like this one\n", "\n", "import numpy # we import the array library\n", "from matplotlib import pyplot # import plotting library" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We are importing one library named `numpy` and we are importing a module called `pyplot` of a big library called `matplotlib`.\n", "To use a function belonging to one of these libraries, we have to tell Python where to look for it. For that, each function name is written following the library name, with a dot in between.\n", "So if we want to use the NumPy function [linspace()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html), which creates an array with equally spaced numbers between a start and end, we call it by writing:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 0. , 0.55555556, 1.11111111, 1.66666667, 2.22222222,\n", " 2.77777778, 3.33333333, 3.88888889, 4.44444444, 5. ])" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myarray = numpy.linspace(0, 5, 10)\n", "myarray" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we don't preface the `linspace()` function with `numpy`, Python will throw an error." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "ename": "NameError", "evalue": "name 'linspace' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmyarray\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mlinspace\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m5\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m10\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mNameError\u001b[0m: name 'linspace' is not defined" ] } ], "source": [ "myarray = linspace(0, 5, 10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The function `linspace()` is very useful. Try it changing the input parameters!\n", "\n", "**Import style:**\n", "\n", "You will often see code snippets that use the following lines\n", "```Python\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "```\n", "What's all of this import-as business? It's a way of creating a 'shortcut' to the NumPy library and the pyplot module. You will see it frequently as it is in common usage, but we prefer to keep out imports explicit. We think it helps with code readability.\n", "\n", "**Pro tip:**\n", "\n", "Sometimes, you'll see people importing a whole library without assigning a shortcut for it (like `from numpy import *`). This saves typing but is sloppy and can get you in trouble. Best to get into good habits from the beginning!\n", "\n", "\n", "To learn new functions available to you, visit the [NumPy Reference](http://docs.scipy.org/doc/numpy/reference/) page. If you are a proficient `Matlab` user, there is a wiki page that should prove helpful to you: [NumPy for Matlab Users](http://wiki.scipy.org/NumPy_for_Matlab_Users)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python doesn't require explicitly declared variable types like C and other languages. " ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = 5 #a is an integer 5\n", "b = 'five' #b is a string of the word 'five'\n", "c = 5.0 #c is a floating point 5 " ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(a)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(b)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that if you divide an integer by an integer that yields a remainder, the result will be converted to a float. (This is *different* from the behavior in Python 2.7, beware!)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Whitespace in Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python uses indents and whitespace to group statements together. To write a short loop in C, you might use:\n", "\n", " for (i = 0, i < 5, i++){\n", " printf(\"Hi! \\n\");\n", " }" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python does not use curly braces like C, so the same program as above is written in Python as follows:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hi \n", "\n", "Hi \n", "\n", "Hi \n", "\n", "Hi \n", "\n", "Hi \n", "\n" ] } ], "source": [ "for i in range(5):\n", " print(\"Hi \\n\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you have nested for-loops, there is a further indent for the inner loop." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 0\n", "0 1\n", "0 2\n", "This statement is within the i-loop, but not the j-loop\n", "1 0\n", "1 1\n", "1 2\n", "This statement is within the i-loop, but not the j-loop\n", "2 0\n", "2 1\n", "2 2\n", "This statement is within the i-loop, but not the j-loop\n" ] } ], "source": [ "for i in range(3):\n", " for j in range(3):\n", " print(i, j)\n", " \n", " print(\"This statement is within the i-loop, but not the j-loop\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Slicing Arrays" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In NumPy, you can look at portions of arrays in the same way as in `Matlab`, with a few extra tricks thrown in. Let's take an array of values from 1 to 5." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([1, 2, 3, 4, 5])" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myvals = numpy.array([1, 2, 3, 4, 5])\n", "myvals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python uses a **zero-based index**, so let's look at the first and last element in the array `myvals`" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(1, 5)" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myvals[0], myvals[4]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are 5 elements in the array `myvals`, but if we try to look at `myvals[5]`, Python will be unhappy, as `myvals[5]` is actually calling the non-existant 6th element of that array." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "ename": "IndexError", "evalue": "index 5 is out of bounds for axis 0 with size 5", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mIndexError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmyvals\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mIndexError\u001b[0m: index 5 is out of bounds for axis 0 with size 5" ] } ], "source": [ "myvals[5]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Arrays can also be 'sliced', grabbing a range of values. Let's look at the first three elements" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([1, 2, 3])" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myvals[0:3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note here, the slice is inclusive on the front end and exclusive on the back, so the above command gives us the values of `myvals[0]`, `myvals[1]` and `myvals[2]`, but not `myvals[3]`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assigning Array Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the strange little quirks/features in Python that often confuses people comes up when assigning and comparing arrays of values. Here is a quick example. Let's start by defining a 1-D array called $a$:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = numpy.linspace(1,5,5)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 1., 2., 3., 4., 5.])" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "OK, so we have an array $a$, with the values 1 through 5. I want to make a copy of that array, called $b$, so I'll try the following:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [], "source": [ "b = a" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 1., 2., 3., 4., 5.])" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Great. So $a$ has the values 1 through 5 and now so does $b$. Now that I have a backup of $a$, I can change its values without worrying about losing data (or so I may think!)." ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a[2] = 17" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 1., 2., 17., 4., 5.])" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, the 3rd element of $a$ has been changed to 17. Now let's check on $b$." ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 1., 2., 17., 4., 5.])" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And that's how things go wrong! When you use a statement like $a = b$, rather than copying all the values of $a$ into a new array called $b$, Python just creates an alias (or a pointer) called $b$ and tells it to route us to $a$. So if we change a value in $a$ then $b$ will reflect that change (technically, this is called *assignment by reference*). If you want to make a true copy of the array, you have to tell Python to copy every element of $a$ into a new array. Let's call it $c$. " ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [], "source": [ "c = a.copy()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we can try again to change a value in $a$ and see if the changes are also seen in $c$. " ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a[2] = 3" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 1., 2., 3., 4., 5.])" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "array([ 1., 2., 17., 4., 5.])" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "OK, it worked! If the difference between `a = b` and `a = b.copy()` is unclear, you should read through this again. This issue will come back to haunt you otherwise." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Learn More" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are a lot of resources online to learn more about using NumPy and other libraries. Just for kicks, here we use Jupyter's feature for embedding videos to point you to a short video on YouTube on using NumPy arrays." ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import YouTubeVideo\n", "# a short video about using NumPy arrays, from Enthought\n", "YouTubeVideo('vWkb7VahaXQ')" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.core.display import HTML\n", "def css_styling():\n", " styles = open(\"../styles/custom.css\", \"r\").read()\n", " return HTML(styles)\n", "css_styling()" ] } ], "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.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }