{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Workshop: Basic Introduction for Psychology Researchers\n", "\n", "---\n", "\n", "# INTRODUCTION\n", "\n", "* Introductions\n", " * Montr\u00e9al-Python\n", " * Speaker\n", " * Events: Monthly meetup (MP), project nights, sprints, workshops, PyCon 2014!\n", " * Workshops\n", " * Sponsors\n", " * And you?\n", " * Students?\n", " * Programmers?\n", " * Professors?\n", "\n", "* Objectives\n", " * **explore Python** through experimentation and introspection in the interpretor\n", " * **master basic notions** : types, functions, conditionals, iterations...\n", " * **write a script** that we will execute in the interpreter\n", " * **import** Python's power\n", "\n", "* Documentation\n", " * [http://www.python.org/doc/](http://www.python.org/doc/)\n", " * [http://docs.python.org/tutorial/](http://docs.python.org/tutorial/)\n", " * [http://docs.python.org/library/](http://docs.python.org/library/)\n", "\n", "* Environment\n", " * text editor\n", " * python interpreter: python, ipython\n", "\n", "----\n", "\n", "# I. THEORY (what)\n", "\n", "## Programming\n", "\n", "* data\n", " * typed, structured in variables\n", "* operations on data\n", " * functions transforming input data in output data\n", " * storing, retrieveing from files, database, Internet\n", "* formal language\n", " * syntax\n", "* object oriented\n", " * modeling the world\n", " * to group in one place the definition of the kinds of things in the world\n", " * to group in one place the variables and functions relevant to *objects* of the same *class* \n", "\n", "### Programming for psychology researchers\n", "\n", "* Data analysis (pandas)\n", "* Experiments, tasks (raw_input, Tk, web)\n", "* Publishing (web, print, LaTeX... ipython notebook)\n", "* Modeling\n", "\n", "## Python\n", "\n", "* interpreted\n", "* object oriented\n", "* dynamic\n", "* strongly typed\n", "* ... used (almost) everywhere\n", "\n", "* Python 2 vs Python 3\n", " \n", "## Programming in Python\n", "\n", "### Environment\n", "\n", "* Wes McKinney, *[Python for Data analysis](http://it-ebooks.info/book/1041/)*, O'Reilly, 2013, p.11\n", "* ... on Integrated Development Environments (IDEs)\n", "\n", " * *When asked about my standard development environment, I almost always say \"IPython plus a text editor\". I typically write a program and iteratively test and debug each piece of it in IPython. It is also useful to be able to play around with data interactively and visually verify that a particular set of data manipulations are doing the right thing. Libraries like pandas and NumPy are designed to be easy-to-use in the shell.*\n", "\n", "### Approach\n", "\n", "1. Explore in the interactive interpreter IPython\n", "2. Write in your script what works\n", "3. Search for the tools you need (pypi, Internet, community, books...)\n", "4. Import (may need to install first) these tools and build more complex scripts, programs\n", "5. Create your modules or program\n", "6. Share it and collaboratively create better tools\n", "7. Do better research, do better science\n", "\n", "### Interpreter\n", "\n", "* python: vanilla interpreter" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* ipython : interactivity / introspection" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ ipython" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Syntax\n", "\n", "* comments: #\n", "* variables: without $\n", "* statements: without ;\n", "* blocks: without {}\n", "* style: PEP 8\n", "[http://www.python.org/dev/peps/pep-0008/](http://www.python.org/dev/peps/pep-0008/\n", ")\n", "* line continuations: \\\\\n", "\n", "---\n", "\n", "# II. DEMO (how)\n", "\n", "## Exploring\n", "\n", "* data in basic variables : name, firstname, dob, has_psy, problems, treatments\n", "* transforming it with functions : age()\n", "* ... or methods (functions on objects) : name.upper()\n", " \n", "## Coding a script\n", "\n", "* create a complex data structure : a Person class\n", "* interact with user\n", " * a **psychology example** with an HEXACO self form\n", "* save data in a file\n", " \n", "## Import Python's power\n", "\n", "* going beyond with existing tools\n", " * importing from the standard library (shipped with Python) : datetime, csv\n", " * a **psychology example** with *pandas* library for data analysis on HEXACO data\n", "\n", "---\n", "\n", "# III. PRACTICE (hands-on : do-it)\n", "\n", "## Start\n", "\n", "* launch interpertor\n", "\n", "## Variables\n", "\n", "### Name, value, reference\n", "\n", "* variable names refers to values\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = 12\n", "b = a" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "id(a)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 2, "text": [ "142708844" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "id(b)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "142708844" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Types\n", "\n", "* dynamic types (no need to declare)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "n = None # NoneType: special value meaning... nothing\n", "b = True # bool: boolean... True or False (case sensitive)\n", "\n", "i = 15 # int: integer\n", "f = 15.5 # float: non-integer values\n", "\n", "s = \"string\" # str: strings, written with \"\" or ''\n", "u = u\"string\" # unicode: unicode string, writh with u\"\" or u''\n", "\n", "l = [] # list: list of objects (ordered)\n", "t = () # tuple: immutable list of objects (can't append to it)\n", "d = {} # dict: dictionary of data (unique, unordered)\n", "\n", "st = {} # set: a collection of objects (unique, unordered), set([])" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* unpacking" ] }, { "cell_type": "code", "collapsed": false, "input": [ "coord = (45.30, 73.34)\n", "lat, lon = coord" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* strongly typed (no implicit casting)\n", "* casting:\n", "\n", " str(), int(), float(), bool(), list(), tuple(), dict(), set()" ] }, { "cell_type": "code", "collapsed": false, "input": [ "float(a)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 6, "text": [ "12.0" ] } ], "prompt_number": 6 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Containers\n", "\n", "* nesting" ] }, { "cell_type": "code", "collapsed": false, "input": [ "l = [[1,2,3],[4,'ohai',6],[7,8,9]]\n", "d = {1611: {'lastname':u'Guti\u00e9rrez Hermoso', 'firstname':u'Jordi'},\n", " 123: {'lastname':u'Leduc-Hamel', 'firstname':u'Mathieu'}}" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 22 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* indexing" ] }, { "cell_type": "code", "collapsed": false, "input": [ "l[2]\n", "d[1611]\n", "l[1][1]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 23, "text": [ "'ohai'" ] } ], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* slicing" ] }, { "cell_type": "code", "collapsed": false, "input": [ "l[1:3]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 28, "text": [ "[[4, 'ohai', 6], [7, 8, 9]]" ] } ], "prompt_number": 28 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : variables\n", "\n", "1. create a list of official psychological problems, a pseudo DSM\n", "1. create a dictionary representing a person, with these data\n", " * name\n", " * firstname\n", " * sex (or gender)\n", " * year of birth\n", " * to know if he has a psy or not\n", " * a list of *his* diagnosed psychological problems (from the official list)\n", "\n", "## Functions\n", "\n", "### Function call\n", "\n", "* function name : open\n", "* function call : open()\n", "\n", "### Built-in functions\n", "\n", "* [http://docs.python.org/2/library/functions.html](http://docs.python.org/2/library/functions.html)\n", "\n", "type() # returns object's type
\n", "dir() # returns the object's attributes
\n", "help() # gives an object's documentation
\n", "callable() # whether an object is function-like...
\n", "
\n", "bool(), int(), str() # initialisation or casting
\n", "getattr()
\n", "
\n", "isinstance(object, Type)# test the class (or type) of an object
\n", "issubclass()
\n", "super()
\n", "
\n", "len()
\n", "min()
\n", "max()
\n", "
\n", "open()
\n", "range()
\n", "raw_input()
\n", "
\n", "enumerate()
\n", "zip()
\n", "sorted
\n", "reversed()
\n", "
\n", "print
\n", "del
\n", "\n", "### Declare a function\n", "\n", "* naming convention\n", "* output : None by default, one or many values\n", "* input : named or positional parameters\n", "* variables scope\n", "* \\*args, \\*\\*kwargs" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def my_function(param1, param2, param3=None, param4=0, *args, **kwards):\n", " \"\"\"This is my function.\"\"\"\n", " output = True\n", " return output" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : functions\n", "\n", "1. create a function that returns the age of someone in function of his year of birth\n", "\n", "## Namespaces\n", "\n", "### Objects\n", "\n", "* object : everything is an object\n", "* attribute = variable on an object\n", "* method = function on an object\n", "* object.attribute\n", "* object.method()\n", "* object.attribute.method()\n", "\n", "### Introspection\n", "\n", "* variable. [+ tab]\n", "* variable?\n", "\n", "* type()\n", "* dir()\n", "* help()\n", "\n", "* exploring the types\n", "\n", "### Exercice : namespaces\n", "\n", "1. add a problem to the list of problems\n", "1. count the total problems you have in your list\n", "1. create the fullname (from name and firstname) of your person but with its name in uppercase\n", "1. add on the person dictionary a new key for his treatments" ] }, { "cell_type": "code", "collapsed": false, "input": [ "name = u\"Jordi Guti\u00e9rrez Hermoso\"\n", "firstname, paternalname, maternalname = name.split()\n", "paternalname.upper()\n", "paternalname.lower()\n", "paternalname.ljust(30)\n", "name = [firstname.lower(), paternalname.lower(), maternalname.lower()]\n", "username = \".\".join(name)\n", "\n", "name = u\"Jordi Guti\u00e9rrez Hermoso\"\n", "username = \".\".join(name.split()).lower()\n", "\n", "users = []\n", "users.append(username)\n", "\n", "jordigh = {'firstname':u'Jordi', 'lastname':u'Guti\u00e9rrez Hermoso'}\n", "mathieu = {'firstname':u'Mathieu', 'lastname':u'Leduc-Hamel'}\n", "jp = {'firstname':u'Jean-Philippe', 'lastname':u'Caissy'}\n", "\n", "people = []\n", "people.append(jordigh)\n", "people.append(mathieu)\n", "people.append(jp)\n", "\n", "status = [\n", " (1, u'New'),\n", " (2, u'In progress'),\n", " (3, u'Rejected'),\n", " (4, u'Accepted'),\n", "]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Flow and control\n", "\n", "### Comparison and logical operators\n", "\n", "* false = False, 0, \"\", (), [], {}, None\n", "* and, or, not\n", "* < > <= >= == !=\n", "* x < y <= z\n", "* is, is not\n", "* in, not in\n", "\n", "### Conditional\n", "\n", "* if, elif, else" ] }, { "cell_type": "code", "collapsed": false, "input": [ "numlist = range(6)\n", "if 5 in numlist:\n", " print 'hooray 5'\n", "elif 4 in numlist:\n", " print 'hooray 4'\n", "else:\n", " print 'not hooray :-('" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "hooray 5\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* one-liner" ] }, { "cell_type": "code", "collapsed": false, "input": [ "'hooray 5' if 5 in numlist else 'not hooray :-('" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 3, "text": [ "'hooray 5'" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iteration\n", "\n", "* while" ] }, { "cell_type": "code", "collapsed": false, "input": [ "year = 2012\n", "while year <= 2015:\n", " print year\n", " year = year + 1 # year += 1" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "2012\n", "2013\n", "2014\n", "2015\n" ] } ], "prompt_number": 7 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* for" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for i in range(2012, 2016):\n", " print i" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "2012\n", "2013\n", "2014\n", "2015\n" ] } ], "prompt_number": 8 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : flow and control\n", "\n", "1. write a test to see if a problem is in the list of the person's problems\n", " * if so, add a proposed treatment (or measure) for this specific person's problem\n", " * the treament is not modifiable (we want to make sure that for *this* problem, we've done *that*)\n", " * if not, give him an advice (print it on screen)\n", "1. from all the problems that this person has, list only ones that didn't received a treatment yet\n", "\n", "## Scripts\n", "\n", "* sample file: [sup.py](http://bit.ly/1fDYZXO)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#! /usr/bin/env python\n", "# -*- encoding: utf-8 -*-\n", "\n", "def sup(name):\n", " return u\"Sup %s!\" % (name)\n", "\n", "if __name__ == '__main__':\n", " print u\"--------------------------------------------------\"\n", " print u\"START the script\"\n", " print u\"--------------------------------------------------\"\n", " name = raw_input(\"What is your name? \")\n", " print sup(name)\n", " print u\"-----------------------------------------------\"\n", " print u\"END the script\"\n", " print u\"-------------------------------------------------\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "--------------------------------------------------\n", "START the script\n", "--------------------------------------------------\n", "-----------------------------------------------\n", "END the script\n", "-------------------------------------------------\n" ] } ], "prompt_number": 18 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* shebang: #!/usr/bin/env python\n", "* encoding: # -\\*- encoding: utf-8 -\\*-\n", "* if \\_\\_name\\_\\_ == '\\_\\_main\\_\\_':\n", "* raw_input()\n", "\n", "* create a repository *project/contacts*\n", "* create in this repo a Python script called *form.py* which:\n", " * Asks the user their name, last name, and date of birth\n", " * Greets the user putting their full name in ALLCAPS\n", "\n", "* Execution in ipython:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "run script" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* execution with python: " ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ python script.py" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : scripts\n", "\n", "1. create a file called `lab.py`\n", "1. add your working code you typed in the interpertor\n", " * variable for the official psychological problems\n", " * function to calculate the age\n", "1. ask the user all the questions you need to get the data to store in your dictionary\n", "1. end your interaction with your user by telling him something relevant with its age and problems\n", "1. run your script\n", "1. interact with your script\n", "1. close the interpretor\n", "1. re-open the interpretor\n", "1. re-run the script\n", "\n", "## Classes\n", "\n", "### Declare a class" ] }, { "cell_type": "code", "collapsed": false, "input": [ "class Person(object):\n", " \n", " def __init__(self, name, firstname, dob=None):\n", " self.name = name\n", " self.firstname = firstname\n", " self.dob = dob\n", " \n", " def age(self):\n", " # TODO : compute in function of dob and now\n", " return self.dob" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create objects\n", "\n", "* objects (instances) of a Class" ] }, { "cell_type": "code", "collapsed": false, "input": [ "mathieu = Person(\"Leduc-Hamel\", \"Mathieu\")\n", "davin = Person(firstname=\"Davin\", name=\"Baragiotta\")" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : classes\n", "\n", "1. write a Person class in your script\n", "1. run the script\n", "1. create few persons objects (instances) from your Person class\n", "1. when everything's fine, replace your person dictionary and your age function with your Person class\n", "\n", "## Import\n", "\n", "* import module\n", "* from module import name\n", "* from module import name as my_name\n", "\n", "* built-in: no need to import\n", "* standard library (shipped with python): import without installation\n", "* pypi : lots of modules to install that are just begging to be imported\n", " * [http://pypi.python.org](http://pypi.python.org)\n", " * install with pip : _installation of modules covered in the virtualenv workshop_\n", "\n", "* importable if installed \"in the path\"\n", "\n", "### Standard library modules\n", "\n", "* http://docs.python.org/library/" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from datetime import date\n", "\n", "today = date.today()\n", "print today\n", "#year = ??" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "2014-03-18\n" ] } ], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "import sys\n", "sys.path" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 21, "text": [ "['',\n", " '/usr/lib/python2.7',\n", " '/usr/lib/python2.7/plat-linux2',\n", " '/usr/lib/python2.7/lib-tk',\n", " '/usr/lib/python2.7/lib-old',\n", " '/usr/lib/python2.7/lib-dynload',\n", " '/home/jordi/.local/lib/python2.7/site-packages',\n", " '/usr/local/lib/python2.7/dist-packages',\n", " '/usr/lib/python2.7/dist-packages',\n", " '/usr/lib/python2.7/dist-packages/PIL',\n", " '/usr/lib/python2.7/dist-packages/gst-0.10',\n", " '/usr/lib/python2.7/dist-packages/gtk-2.0',\n", " '/usr/lib/pymodules/python2.7',\n", " '/usr/lib/python2.7/dist-packages/IPython/extensions']" ] } ], "prompt_number": 21 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Examples\n", "\n", "* re\n", "* datetime\n", "* collections\n", "* pprint\n", "* decimal\n", "* os.path\n", "* pickle\n", "* sqlite3\n", "* zipfile\n", "* csv\n", "* email\n", "* json\n", "* htmllib\n", "* urllib2\n", "* Tkinter, ttk\n", "* pdb\n", "* sys\n", "\n", "#### Exercice : import from standard library\n", "\n", "1. import the date name from the datetime module of the standard library\n", "1. explore how to obtain the year out from a date\n", "1. upgrade your function calculating the age to compute based on date objects and no more with integers\n", "1. explore how to deal with days (you don't have the same age in the same year whether your birthday is past or to come)\n", "1. upgrade again your age function to use date deltas\n", "\n", "### Your own modules\n" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "__init__.py" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "__name__" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "__main__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* \\_\\_name\\_\\_ : Module name. It's the file name if imported, but it's \\_\\_main\\_\\_ if executed (useful for tests)\n", "* add the file \\_\\_init\\_\\_.py in a directory to turn it into a module" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercice : import your module\n", "\n", "1. create a directory called `inpsych`\n", "1. create a `__init__.py` file in it\n", "1. move your `lab.py` file in the `inpsych` directory\n", "1. in the interpretor, import the `age` function living in the `lab.py` file in order to test it\n", " * make sure that the `inpsych` directory is \"in the path\" for your interpretor\n", " * launching the interpretor in the parent directory of your module makes your module \"in the path\", reachable for the interpretor\n", "\n", "### Third party modules\n", "\n", "https://pypi.python.org/\n", "\n", "* pypi = python packaging index\n", "* modules that we import live in packages that we install on our system\n", "* find the right package (on pypi or talking with a Pythonista)\n", "\n", "#### Databases\n", "\n", "* DB : sqlite3, mysqldb, psycopg2\n", "* ORM : sqlalchemy\n", "\n", "#### Web development\n", "\n", "* django (+south)\n", "* pyramid\n", "* flask\n", "\n", "#### Science\n", "\n", "* numpy\n", "* matplotlib\n", "* pandas\n", "* scipy\n", "\n", "##### Psychology\n", "\n", "* psychopy\n", "\n", "#### System administration\n", "\n", "* fabric\n", "* celery\n", "* ...\n", "\n", "#### Natural language treatment\n", "\n", "* nltk\n", "* pattern\n", "\n", "* install with pip\n", "* pip = pip installs python\n", "\n", "#### Installation with pip\n", "\n", "* pip installs packages on your machine\n", "* for a better package management, use virtualenv (covered in an other workshop)" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ pip install packagename" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : import a third party module\n", "\n", "1. install psychopy on your (virtual) machine\n", " 1. close the Python interpretor (or open a new terminal)\n", " 1. install with pip\n", " 1. launch back the interpretor\n", "1. import psychopy\n", "1. explore psychopy\n", "\n", "## Files\n", "\n", "* open, manipulate, close\n", " * sample file : [python.txt](http://bit.ly/16gJUmB)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "f = open('python.txt')\n", "for line in f.readlines():\n", " print line,\n", "f.close()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Python is a language that I love\n", "and, it seems, its name comes from\n", "the Monty Python troupe of British comedians\n", "and not from the kind of snake called \"python\"\n", "\n" ] } ], "prompt_number": 15 }, { "cell_type": "code", "collapsed": false, "input": [ "f = open(\"python.txt\")\n", "lines = f.readlines()\n", "f.close()\n", "\n", "target = 'python'\n", "context = [line for line in lines if target in line]\n", "comments = [line for line in lines if line.startswith('#')]" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 16 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : files\n", "\n", "1. introspect the open function to see how to open in writing, reading or append mode... : w, r, a...\n", "1. create a list of strings\n", "1. write these strings in a file, e.g.: `test.txt`\n", "\n", "## Syntaxic sugar\n", "\n", "### List, dictionary and set comprehensions\n", "\n", "* Create a list, a dictionary or a set from an iterable using a one-liner" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "new_list = [v for v in old_list if v < 2]
\n", "new_dict = {k, v for k, v in old_dict.items() if k < 2}
\n", "new_set = {v for v in old_list if v < 2}
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### String formatting\n", "\n", "* substitution : %" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for n in range(10):\n", " print \"%d to the 3rd power is: %d\" % (n, n**3)\n", "\n", "for p in people:\n", " print \"Bonjour/Hello %s %s\" % (p['firstname'], p['lastname'].upper())" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0 to the 3rd power is: 0\n", "1 to the 3rd power is: 1\n", "2 to the 3rd power is: 8\n", "3 to the 3rd power is: 27\n", "4 to the 3rd power is: 64\n", "5 to the 3rd power is: 125\n", "6 to the 3rd power is: 216\n", "7 to the 3rd power is: 343\n", "8 to the 3rd power is: 512\n", "9 to the 3rd power is: 729\n", "Bonjour/Hello Jordi GUTI\u00c9RREZ HERMOSO\n", "Bonjour/Hello Mathieu LEDUC-HAMEL\n", "Bonjour/Hello Jean-Philippe CAISSY\n" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : string formatting\n", "\n", "1. use string formatting in the questions asked or feedback given to the user (e.g.: age)\n", "\n", "## Exceptions\n", "\n", "* try, except" ] }, { "cell_type": "code", "collapsed": false, "input": [ "try:\n", " 15/0\n", "except (ZeroDivisionError,), e:\n", " print \"Dividing by zero is bad, m'kay?\"\n", " print e" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercice : exception\n", "\n", "1. in your age function, return an explicit error message when the input is not a date\n", "\n", "## Data permanence\n", "\n", "* files\n", "* serialisation: import pickle" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import pickle\n", "\n", "f = open('pickles', 'w')\n", "pickle.dump(status, f)\n", "pickle.dump(people, f)\n", "f.close()\n", "\n", "exit()\n", "\n", "import pickle\n", "\n", "f = open('pickles')\n", "pickle.load(f)\n", "#objects = []\n", "#for obj in pickle.load(f):\n", "# objects.append(obj)\n", "f.close()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 23 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* in database?\n", "\n", "### Exercice\n", "\n", "1. in your `lab.py` program, store all the responses obtained from the users in a .csv file\n", " 1. import the csv module of the standard library\n", " 1. explore how to write a csv file with the csv module... csv.writer?\n", " 1. make sure your program writes in the file in append mode so we don't loose data after each use\n", "1. test your program multiple times, check that .csv file grows with data" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# CONCLUSION\n", "\n", "## Going further\n", "\n", "* Conferences\n", " * [PyCon](http://pycon.us), [PyCon.ca](http://pycon.ca)\n", " * [SciPy](http://scipy.org)\n", "* Videos\n", " * [PyVideo](http://pyvideo.org)\n", "* Psychology\n", " * [psychopy ?](http://www.psychopy.org/)\n", "* Data analysis\n", " * http://pydata.org, [pandas](http://pandas.pydata.org)\n", " * Wes McKinney, *[Python for Data analysis](http://it-ebooks.info/book/1041/)*, O'Reilly, 2013\n", "\n", "## What we've learned\n", "\n", "* import antigravity\n", "* documentation + interactivity + introspection\n", "* scripts + modules + import\n", "\n", "## Getting help\n", "\n", "* helpful community\n", "* Montr\u00e9al-Python:\n", " * join the community\n", " * upcoming events\n", "\n", "* enjoy!\n", "\n", "# EXERCISE\n", "\n", "## Objective\n", "\n", "Create a script *flux.py* that returns\n", "the 5 latest stories posted on the Montreal-Python-site:\n", "[http://montrealpython.org/fr/feed/](http://montrealpython.org/fr/feed/)\n", "\n", "## Approach\n", "\n", "1. use feedparser\n", " * pip install feedparser\n", "1. launch the interpreter and follow the docs:\n", " * ipython\n", " * http://packages.python.org/feedparser/\n", "1. introspect as needed (and print a dict to see its keys)\n", "1. code the script that will do the desired processing\n", "1. launch the script in the interpreter and confirm its proper execution\n", "1. serve cold\n", "\n", "## Algorithm\n", "\n", "* read the RSS feed from http://montrealpython.org\n", "* keep the number of desired items\n", "* process the kept items:\n", " * Create a unique string with the data of the last modified items (title, URL... and eventually the date of last modification)\n", "\n", "## Solution\n", "\n", "Take the time to code up the solution yourself...\n", "... then you can compare with [our solution](http://bit.ly/1bnRClq)\n", "\n", "As a hint, our solution only has 8 lines of Python.\n", "\n", "\n", "---" ] } ], "metadata": {} } ] }