{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Core Python Language #\n", "\n", "Mostly copied from the [official python tutorial](https://docs.python.org/3/tutorial/)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Invoking Python ##\n", "\n", "There are three main ways to use python.\n", "\n", "1. By running a python file, e.g. `python myscript.py`\n", "1. Through an interactive console (python interpreter or ipython shell)\n", "1. In an interactive iPython notebook\n", "\n", "We will be using the iPython notebook." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python Versions ##\n", "\n", "There are two versions of the python language out there: python 2 and python 3. Python 2 is more common in the wild but is depracated. The community is moving to python 3. As new python learners, you should learn python 3. But it is important to be aware that python 2 exists. It is possible that a package you want to use is only supported in python 2. In general, it is pretty easy to switch between then.\n", "\n", "Some of the main changes in python 3 are:\n", "\n", "* ``print`` is a function\n", "* Integer division returns a float\n", "* Iterators behave differently\n", "* Unicode is used for encoding code\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic Variables: Numbers and String ##" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# comments are anything that comes after the \"#\" symbol\n", "a = 1 # assign 1 to variable a\n", "b = \"hello\" # assign \"hello\" to variable b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:\n", "\n", " False class finally is return\n", " None continue for lambda try\n", " True def from nonlocal while\n", " and del global not with\n", " as elif if or yield\n", " assert else import pass\n", " break except in raise\n", " \n", "Additionally, the following a built in functions which are always available in your namespace once you open a python interpreter\n", "\n", " abs() dict() help() min() setattr() all() dir() hex() next() slice() any()\n", " divmod() id() object() sorted() ascii() enumerate() input() oct() staticmethod()\n", " bin() eval() int() open() str() bool() exec() isinstance() ord() sum() bytearray()\n", " filter() issubclass() pow() super() bytes() float() iter() print() tuple()\n", " callable() format() len() property() type() chr() frozenset() list() range()\n", " vars() classmethod() getattr() locals() repr() zip() compile() globals() map()\n", " reversed() __import__() complex() hasattr() max() round() delattr() hash()\n", " memoryview() set()\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# how to we see our variables?\n", "print(a)\n", "print(b)\n", "print(a,b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All variables are objects. Every object has a type (class). To find out what type your variables are" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(type(a))\n", "print(type(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# as a shortcut, iPython notebooks will automatically print whatever is on the last line\n", "type(b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# we can check for the type of an object\n", "print(type(a) is int)\n", "print(type(a) is str)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Different objects attributes and methods, which can be accessed via the syntax ``variable.method``\n", "\n", "IPython will autocomplete if you press ```` to show you the methods available." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# this returns the method itself\n", "b.capitalize" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# this calls the method\n", "b.capitalize()\n", "# there are lots of other methods" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# binary operations act differently on different types of objects\n", "c = 'World'\n", "print(b + c)\n", "print(a + 2)\n", "print(a + b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Math ##\n", "\n", "Basic arithmetic and boolean logic is part of the core python library." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# addition / subtraction\n", "1+1-5" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# multiplication\n", "5 * 10" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# division\n", "1/2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# that was automatically converted to a float\n", "type(1/2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# exponentiation\n", "2**4" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# rounding\n", "round(9/10)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# built in complex number support\n", "(1+2j) / (3-4j)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# logic\n", "True and True" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "True and False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "True or True" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "(not True) or (not False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditionals ##\n", "\n", "The first step to programming. Plus an intro to python syntax." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 100\n", "if x > 0:\n", " print('Positive Number')\n", "elif x < 0:\n", " print('Negative Number')\n", "else:\n", " print ('Zero!')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# indentation is MANDATORY\n", "# blocks are closed by indentation level\n", "if x > 0:\n", " print('Positive Number')\n", " if x >= 100:\n", " print('Huge number!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## More Flow Control ##" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# make a loop \n", "count = 0\n", "while count < 10:\n", " # bad way\n", " # count = count + 1\n", " # better way\n", " count += 1\n", "print(count)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# use range\n", "for i in range(5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Important point__: in python, we always count from 0!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# what is range?\n", "type(range)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "range?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# iterate over a list we make up\n", "for pet in ['dog', 'cat', 'fish']:\n", " print(pet, len(pet))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What is the thing in brackets? __A list!__ Lists are one of the core python data structures.\n", "\n", "## Lists ##" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l = ['dog', 'cat', 'fish']\n", "type(l)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# list have lots of methods\n", "l.sort()\n", "l" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# we can convert a range to a list\n", "r = list(range(5))\n", "r" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "while r:\n", " p = r.pop()\n", " print('p:', p)\n", " print('r:', r)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are many different ways to interact with lists. Exploring them is part of the fun of python.\n", "\n", "__list.append(x)__ Add an item to the end of the list. Equivalent to a[len(a):] = [x].\n", "\n", "__list.extend(L)__ \n", "Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L.\n", "\n", "__list.insert(i, x)__ Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).\n", "\n", "__list.remove(x)__ Remove the first item from the list whose value is x. It is an error if there is no such item.\n", "\n", "__list.pop([i])__ Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)\n", "\n", "__list.clear()__ Remove all items from the list. Equivalent to del a[:].\n", "\n", "__list.index(x)__ Return the index in the list of the first item whose value is x. It is an error if there is no such item.\n", "\n", "__list.count(x)__ Return the number of times x appears in the list.\n", "\n", "__list.sort()__ Sort the items of the list in place.\n", "\n", "__list.reverse()__ Reverse the elements of the list in place.\n", "\n", "__list.copy()__ Return a shallow copy of the list. Equivalent to a[:].\n", "\n", "\n", "Don't assume you know how list operations work!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# \"add\" two lists\n", "x = list(range(5))\n", "y = list(range(10,15))\n", "z = x + y\n", "z" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# access items from a list\n", "print('first', z[0])\n", "print('last', z[-1])\n", "print('first 3', z[:3])\n", "print('last 3', z[-3:])\n", "print('middle, skipping every other item', z[5:10:2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__MEMORIZE THIS SYNTAX!__ It is central to so much of python and often proves confusing for users coming from other languages.\n", "\n", "In terms of set notation, python indexing is _left inclusive_, _right exclusive_. If you remember this, you will never go wrong." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# that means we get an error from the following\n", "N = len(z)\n", "z[N]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# this index notation also applies to strings\n", "name = 'Ryan Abernathey'\n", "print(name[:4])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# you can also test for the presence of items in a list\n", "5 in z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists are not meant for math! They don't have a datatype." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "z[4] = 'fish'\n", "z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python is full of tricks for iterating and working with lists" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# a cool python trick: list comprehension\n", "squares = [n**2 for n in range(5)]\n", "squares" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# iterate over two lists together uzing zip\n", "for item1, item2 in zip(x,y):\n", " print('first:', item1, 'second:', item2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Other Data Structures ##\n", "\n", "We are almost there. We have the building blocks we need to do basic programming. But python has some other data structures we need to learn about.\n", "\n", "## Tuples ##\n", "\n", "Tuples are similar to lists, but they are _immutable_—they can't be extended or modified. What is the point of this? Generally speaking: to pack together inhomogeneous data. Tuples can then be unpacked and distributed by other parts of your code.\n", "\n", "Tuples may seem confusing at first, but with time you will come to appreciate them." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# tuples are created with parentheses, or just commas\n", "a = ('Ryan', 33, True)\n", "b = 'Takaya', 25, False\n", "type(b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# can be indexed like arrays\n", "print(a[1]) # not the first element!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# and they can be unpacked\n", "name, age, status = a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries ##\n", "\n", "This is an extremely useful data structure. It maps __keys__ to __values__.\n", "\n", "Dictionaries are unordered!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# different ways to create dictionaries\n", "d = {'name': 'Ryan', 'age': 33}\n", "e = dict(name='Takaya', age=25)\n", "e" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# access a value\n", "d['name']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Square brackets ``[...]`` are python for \"get item\" in many different contexts." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# test for the presence of a key\n", "print('age' in d)\n", "print('height' in e)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# try to access a non-existant key\n", "d['height']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# add a new key\n", "d['height'] = (5,11) # a tuple\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# keys don't have to be strings\n", "d[99] = 'ninety nine'\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# iterate over keys\n", "for k in d:\n", " print(k, d[k])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# better way\n", "### python 2\n", "### for key, val in d.iteritems()\n", "for key, val in d.items():\n", " print(key, val)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions ##\n", "\n", "Functions are a central part of advanced python programming. You should try to write and use your own functions as often as possible." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# define a function\n", "def say_hello():\n", " \"\"\"Return the word hello.\"\"\"\n", " return 'Hello'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# functions are also objects\n", "type(say_hello)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# this doesnt call\n", "say_hello?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# this does\n", "say_hello()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# assign the result to something\n", "res = say_hello()\n", "res" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# take some arguments\n", "def say_hello_to(name):\n", " \"\"\"Return a greeting to `name`\"\"\"\n", " return 'Hello ' + name" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# intended usage\n", "say_hello_to('World')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "say_hello_to(10)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# redefine the function\n", "def say_hello_to(name):\n", " \"\"\"Return a greeting to `name`\"\"\"\n", " return 'Hello ' + str(name)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "say_hello_to(10)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# take an optional keyword argument\n", "def say_hello_or_hola(name, spanish=False):\n", " \"\"\"Say hello in multiple languages.\"\"\"\n", " if spanish:\n", " greeting = 'Hola '\n", " else:\n", " greeting = 'Hello '\n", " return greeting + name" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(say_hello_or_hola('Ryan'))\n", "print(say_hello_or_hola('Juan', spanish=True))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# flexible number of arguments\n", "def say_hello_to_everyone(*args):\n", " return ['hello ' + str(a) for a in args]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "say_hello_to_everyone('Ryan', 'Juan', 'Takaya')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We could spend the rest of the day talking about functions, but we have to move on." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Individual Exercises #" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fibonacci Sequence ##\n", "\n", "The Fibonacci sequence is the 1,1,2,3,5,8..., the sum of each number with the preceding one. Write a function to compute the Fibonacci sequence of length n. (Hint, use some list methods.)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def fib(n):\n", " l = [1,1]\n", " for i in range(n-2):\n", " l.append(l[-1] + l[-2])\n", " return l" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fib(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add and Multiply Lists Item by Item ##\n", "\n", "Write functions to add and multiply each item in a list." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def add(x,y):\n", " return [a + b for a,b in zip(x,y)]\n", "\n", "def multiply(x,y):\n", " return [a * b for a,b in zip(x,y)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "add(range(10), range(10))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "multiply(range(5), [9,3,2,5,3])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "N = 100000\n", "%timeit multiply(range(N), range(N))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "%timeit np.arange(N) * np.arange(N)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "On to numpy" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "gist_info": { "gist_id": null, "gist_url": null }, "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }