{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Introduction to Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A few high-level notes on Python\n",
"\n",
"- Python is an intepreted language, meaning there is no linking or compiling necessary of (pure Python) programs. You can execute Python code interactively using a REPL (Read-Eval-Print Loop)\n",
"\n",
"- Python allows you to split a program over modules that can be reused in other Python programs.\n",
"\n",
"- Statement grouping is done via indentation rather than brackets or braces."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from __future__ import braces"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Variable and argument declarations are not needed."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"That is, you don't have to do things like this that you have in C.\n",
"\n",
" int i;\n",
" for (i = 0; i < 10; i ++){\n",
" ...\n",
" }\n",
"\n",
"In Python, it's simply\n",
"\n",
" for i in range(10):\n",
" ..."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- Python is extensible. For example, if you know how to program in C, you can write speed critical code in C and make them available to Python. Or if you have a legacy library in Fortran, with a small amount of work you can use this library from Python."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modules"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A module is a file that contains Python definitions and statements. The file will end with `.py`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You might fire up your favorite editor and create a file called `hurricane_simulation.py`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" #! /usr/bin/python\n",
" \"\"\"\n",
" Simulate a category-5 tropical storm to 100-km accuracy\n",
" Author: Skipper Seabold\n",
" Created: January 14, 2013\n",
" \"\"\"\n",
" \n",
" import numpy as np\n",
" # ..."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Getting Help"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The lines in triple-quotes are referred to as the module docstring. This is how code is documented in Python."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(range.__doc__)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In IPython/Jupyter, you can use `?` to get the docstring."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"range?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Self Help"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Comments begin with a `#` in Python. Comment your code liberally."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# this is a comment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Displaying"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can use the print functions to display strings"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"Hello, world.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can print variables as part of strings"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"name = \"Skipper\"\n",
"print(\"Hello, world. My name is {}\".format(name))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can print numbers too."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"2 + 2 =\", 4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"2 + 2 = {:d}\".format(4))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(\"2 + 2 = {:05d}\".format(4))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Numbers and Arithmetic Operations"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Scalar multiplication is indicated by an asterisk (\\*), or \"star.\" Addition, subtraction, and division operators are `+`, `-`, and `/`. Exponentiation is done by two asterisks."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"2 * (5.0 / 8.0 - 1.25)**2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Python 3, the division operators is float division. To force explicit integer division, use `//`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"5 / 8"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"5 // 8"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"5.0 // 8.0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The modulo operator is `%`. This gives the remainder after dividing two numbers."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"8 % 5"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"5.5 % 8"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Variables and Assignments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Assignment is done through the equals operators `=`. Variable names are case-sensitive."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"length_of_bridge = 15"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For the assertion operator use the usual `==`, `<`, `>`, `!=`, etc."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"length_of_bridge == 15"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"length_of_bridge >= 15"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"length_of_bridge != 15"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Getting rid of a variable."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"del length_of_bridge"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: For now, it's best to think of del as a way to clean up the namespace rather than as the equivalent of `free` in C, i.e., a memory-management tool. You can read some more about garbage collection in CPython [here](http://docs.python.org/3/library/gc.html), if you're interested."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can find out what variables are declared in the local or global namespace, by using the dictionaries locals() and globals()."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = 12"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"locals()['x']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"del x"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"locals().get('x', 'not here')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can increment and decrement variables in-place using += and -=."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = 12\n",
"x += 1\n",
"print x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Built-in types: iterables"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Lists** are constructed with square brackets separating items with commas. Lists are mutable, meaning they can be changed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"heights = [21.6, 22.5, 19.8, 20.5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"All Python iterables are zero-indexed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(heights[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can use negative indexing."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(heights[-1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lists are mutable, so we can change an item."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"heights[2] = 12"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Be careful. `a` is a reference to the list we created. Python passes this *same* reference on assignment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = [21.6, 22.5, 19.8, 20.5]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = a\n",
"b[2] = 32.1\n",
"print(a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"id(a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"id(b)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Taking a slice, however, does copy."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = a[1:3]\n",
"print(b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b[0] = 22.16\n",
"print(b)\n",
"print(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can use the copy-on-slice syntax to copy the whole list."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = a[:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Or use the list constructor explicitly, after all, explicit is better than implicit."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"b = list(a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(id(a))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(id(b))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can place any objects in a list."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = [1, 2, [10, 11]]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(a[0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(a[-1])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can quickly create list(-like object) with the range function."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"years = range(1996, 2013)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(years)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can given offset to range."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"years = range(1996, 2013, 4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(years)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Tuples** are much like lists; however, they are immutable and, therefore, [hashable](http://docs.python.org/2/glossary.html#term-hashable). You instantiate a tuple using parantheses () and separate items using a comma."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = (1, 2, 3)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in a:\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a[1] = 12"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" 1/1.\n",
" print 'ok'\n",
"except ZeroDivisionError:\n",
" print \"You can't divide by zero!\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Strings** are also an iterables. However, it may surprise you that strings are immutable unlike in C."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = 'abcdef'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in a:\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(a[2])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a[2] = 'q'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A **dictionary** is a mapping type. It maps [hashable](http://docs.python.org/2/glossary.html#term-hashable) keys to arbitrary objects. Hashable simply means that mutable objects cannot be used as keys to a dictionary. I.e., since lists and dictionaries are mutable, they can't be keys of a dictionary. Dictionaries can be instantiated in a number of ways. The most common is through curly brackets and using `dict`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d = {\n",
" 1: 'I am a value', \n",
" 'key': 'Another value', \n",
" '2': [1, 2, 3]\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can get that values associated with a key like so"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d[1]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d['2']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d['key']"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d.get(12)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also use the `dict` constructor."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d = dict(key=12, other_key=[1, 2, 3])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d['other_key']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Or create a dictionary from an iterable."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"key_value_pairs = [('key', [1, 2, 3]), ('other', 12), (12, 'value')]\n",
"d = dict(key_value_pairs)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can find out much more about built-in types and operators in the Python documentation [here](http://docs.python.org/3/library/stdtypes.html)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Some useful functions for working with sequences."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = range(1, 100, 12)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"len(a)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"13 in a"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"15 in a"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"15 not in a"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The following will give the methods and/or attributes available for any object."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dir(a)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Or use the Jupyter Notebook's tab-completion."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" In [1]: a.