Last active
December 23, 2015 23:39
-
-
Save anandology/6711800 to your computer and use it in GitHub Desktop.
Python Training - September 26-28, 2013
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"metadata": { | |
"name": "" | |
}, | |
"nbformat": 3, | |
"nbformat_minor": 0, | |
"worksheets": [ | |
{ | |
"cells": [ | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"# Python Training - Day 3" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"**Problem** Write a program `countpy.py` to print filename and number of lines for each python file in the current directory.\n", | |
"\n", | |
"This is should import `linecount` function from wc.py.\n", | |
"\n", | |
" import wc\n", | |
" \n", | |
" def find_py_files():\n", | |
" \"\"\"Returns all the .py files in the\n", | |
" current directory.\n", | |
" \"\"\"\n", | |
" # TODO\n", | |
" return []\n", | |
" \n", | |
" def main():\n", | |
" files = find_py_files()\n", | |
" for f in files:\n", | |
" print f, wc.linecount(f)\n", | |
" \n", | |
" if __name__ == \"__main__\":\n", | |
" main()" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"## Installing pip\n", | |
"\n", | |
"pip is a program to install third-party modules in Python.\n", | |
"\n", | |
"\n", | |
"* Install setuptools first by downloading and running [ez_setup.py](https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py).\n", | |
"\n", | |
"* Install pip by downloading and running [get-pip.py](https://raw.github.com/pypa/pip/master/contrib/get-pip.py)\n", | |
"\n", | |
"**Ubuntu/Debian Linux**\n", | |
"\n", | |
" $ sudo apt-get install python-pip\n", | |
" \n", | |
"For more instructions look at <http://www.pip-installer.org/en/latest/installing.html>" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Once `pip` is installed, try to install a third-party module using the following module.\n", | |
"\n", | |
" pip install tablib" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"On windows, if that didn't work, please try:\n", | |
"\n", | |
" C:\\Python27\\Scripts\\pip.exe install tablib" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Python maintains list of third-party packages at https://pypi.python.org/\n", | |
"\n", | |
"When we install a package using `pip install`, it downloads it from there and installs it." | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"import tablib\n" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 3 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"data = tablib.Dataset()\n", | |
"data.append([\"A\", 1])\n", | |
"data.append([\"B\", 2])\n", | |
"data.append([\"C,D\", 3])\n", | |
"print data.csv" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"A,1\r\n", | |
"B,2\r\n", | |
"\"C,D\",3\r\n", | |
"\n" | |
] | |
} | |
], | |
"prompt_number": 5 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"f = open(\"a.csv\", \"w\")\n", | |
"f.write(data.csv)\n", | |
"f.close()\n", | |
"print \"saved data as a.csv\"" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"saved data as a.csv\n" | |
] | |
} | |
], | |
"prompt_number": 6 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!cat a.csv" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"A,1\r", | |
"\r\n", | |
"B,2\r", | |
"\r\n", | |
"\"C,D\",3\r", | |
"\r\n" | |
] | |
} | |
], | |
"prompt_number": 7 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# lets try saving the data as xls\n", | |
"\n", | |
"# use wb when you are saving binary files.\n", | |
"# this is very important, esp. on windows\n", | |
"f = open(\"a.xls\", \"wb\")\n", | |
"f.write(data.xls)\n", | |
"f.close()\n", | |
"print \"saved data as a.xls\"\n" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"saved data as a.xls\n" | |
] | |
} | |
], | |
"prompt_number": 9 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"**Problem** Improve the previously written `countpy.py` to write the counts to an excel file instead of printing.\n", | |
"\n", | |
"\n", | |
"Note: The tablib.Dataset append method takes a list as argument, like this:\n", | |
"\n", | |
"<pre>\n", | |
"data.append([\"foo\", \"bar\"])\n", | |
"</pre>\n", | |
"\n", | |
"not like this:\n", | |
"\n", | |
"<pre>\n", | |
"data.append(\"foo\", \"bar\")\n", | |
"</pre>\n", | |
"\n", | |
"\n" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"%%file countpy.py\n", | |
"import wc\n", | |
"import os\n", | |
"import tablib\n", | |
" \n", | |
"def find_py_files():\n", | |
" \"\"\"Returns all the .py files in the\n", | |
" current directory.\n", | |
" \"\"\"\n", | |
" return [f for f in os.listdir(\".\") \n", | |
" if f.endswith(\".py\")]\n", | |
"\n", | |
"def main():\n", | |
" files = find_py_files()\n", | |
" \n", | |
" # create a dataset\n", | |
" data = tablib.Dataset()\n", | |
" \n", | |
" for f in files:\n", | |
" # append each row to the dataset\n", | |
" row = [f, wc.linecount(f)]\n", | |
" data.append(row)\n", | |
" \n", | |
" # saving it as csv. \n", | |
" # You can save as xls if you want\n", | |
" f = open(\"countpy.csv\", \"wb\")\n", | |
" f.write(data.csv)\n", | |
" f.close()\n", | |
" print \"saved the counts as countpy.csv\"\n", | |
" \n", | |
"if __name__ == \"__main__\":\n", | |
" main()" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Overwriting countpy.py\n" | |
] | |
} | |
], | |
"prompt_number": 13 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python countpy.py" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"saved the counts as countpy.csv\r\n" | |
] | |
} | |
], | |
"prompt_number": 14 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Lets try to email this generated csv/xls file to someone.\n", | |
"\n", | |
"There is a nice third-party library called `envelops` for sending emails.\n", | |
"\n", | |
"Lets install that using:\n", | |
"\n", | |
" pip install envelopes\n" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
" # sample program to send email from Python\n", | |
" from envelopes import Envelope\n", | |
" \n", | |
" envelope = Envelope(\n", | |
" from_addr=\"[email protected]\",\n", | |
" to_addr=\"[email protected]\",\n", | |
" subject=\"Hello from Python\",\n", | |
" text_body=\"Hello Envelope\"\n", | |
" )\n", | |
" \n", | |
" #password = open(\"pw-file.txt\").read().strip()\n", | |
" pw = \"secret\"\n", | |
" \n", | |
" # or ask for the password\n", | |
" import getpass\n", | |
" pw = getpass.getpass()\n", | |
" \n", | |
" envelope.send('smtp.googlemail.com', \n", | |
" login='[email protected]',\n", | |
" password=pw,\n", | |
" tls=True)\n", | |
" \n" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"## The `urllib` module" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# The urllib module allows downloading stuff\n", | |
"# from the web\n", | |
"import urllib\n", | |
"\n", | |
"response = urllib.urlopen(\"http://python.org/\")" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 18 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"contents = response.read()" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 21 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"len(contents)" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"metadata": {}, | |
"output_type": "pyout", | |
"prompt_number": 22, | |
"text": [ | |
"20728" | |
] | |
} | |
], | |
"prompt_number": 22 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"contents[:400]" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"metadata": {}, | |
"output_type": "pyout", | |
"prompt_number": 24, | |
"text": [ | |
"'<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\\n\\n\\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\\n\\n<head>\\n <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" />\\n <title>Python Programming Language – Official Website</title>\\n <meta name=\"keywords\" content=\"python programming langua'" | |
] | |
} | |
], | |
"prompt_number": 24 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"print response.headers" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Date: Sat, 28 Sep 2013 08:31:25 GMT\r\n", | |
"Server: Apache/2.2.16 (Debian)\r\n", | |
"Last-Modified: Fri, 27 Sep 2013 23:36:44 GMT\r\n", | |
"ETag: \"105800d-50f8-4e765f589bb00\"\r\n", | |
"Accept-Ranges: bytes\r\n", | |
"Content-Length: 20728\r\n", | |
"Vary: Accept-Encoding\r\n", | |
"Connection: close\r\n", | |
"Content-Type: text/html\r\n", | |
"\n" | |
] | |
} | |
], | |
"prompt_number": 27 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"**Problem:** Write a program `wget.py` to download the given URL. The program should take the URL as command line argument, download it and save it with the basename of the URL. If the URL ends with `/`, then it should save it as `index.html`.\n", | |
"\n", | |
"<pre>\n", | |
"$ python wget.py http://docs.python.org/tutorial/interpreter.html\n", | |
"saving http://docs.python.org/tutorial/interpreter.html as interpreter.html.\n", | |
"\n", | |
"$ python wget.py http://python.org/\n", | |
"saving http://python.org/ as index.html\n", | |
"\n", | |
"$ python wget.py http://python.org/images/python-logo.gif\n", | |
"saving http://python.org/images/python-logo.gif as python-logo.gif\n", | |
"</pre>" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"## Classes and Objects" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"We've already used objects a lot." | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"x = \"hello\"\n", | |
"print x.upper()" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"HELLO\n" | |
] | |
} | |
], | |
"prompt_number": 28 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"print len(x.upper())" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"5\n" | |
] | |
} | |
], | |
"prompt_number": 29 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"x.upper().endswith(\"O\")" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"metadata": {}, | |
"output_type": "pyout", | |
"prompt_number": 31, | |
"text": [ | |
"True" | |
] | |
} | |
], | |
"prompt_number": 31 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"f = open(\"a.txt\")" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 32 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"f" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"metadata": {}, | |
"output_type": "pyout", | |
"prompt_number": 33, | |
"text": [ | |
"<open file 'a.txt', mode 'r' at 0x1057b7780>" | |
] | |
} | |
], | |
"prompt_number": 33 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"f.readline()" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"metadata": {}, | |
"output_type": "pyout", | |
"prompt_number": 34, | |
"text": [ | |
"'first line \\n'" | |
] | |
} | |
], | |
"prompt_number": 34 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"**Example: Bank Account**" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"%%file bank1.py\n", | |
"\n", | |
"balance = 0\n", | |
"\n", | |
"def deposit(amount):\n", | |
" global balance\n", | |
" balance = balance + amount\n", | |
"\n", | |
"def withdraw(amount):\n", | |
" global balance\n", | |
" balance = balance - amount\n", | |
"\n", | |
"deposit(100)\n", | |
"print balance\n", | |
"\n", | |
"withdraw(10)\n", | |
"print balance" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Writing bank1.py\n" | |
] | |
} | |
], | |
"prompt_number": 35 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python bank1.py" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"100\r\n", | |
"90\r\n" | |
] | |
} | |
], | |
"prompt_number": 36 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"%%file bank2.py\n", | |
"\n", | |
"class BankAccount:\n", | |
" def __init__(self):\n", | |
" self.balance = 0\n", | |
" \n", | |
" def deposit(self, amount):\n", | |
" self.balance = self.balance + amount\n", | |
"\n", | |
" def withdraw(self, amount):\n", | |
" self.balance = self.balance - amount\n", | |
" \n", | |
"x = BankAccount()\n", | |
"y = BankAccount()\n", | |
"\n", | |
"x.deposit(100)\n", | |
"\n", | |
"# in a sense, \n", | |
"# x.deposit(100) is same as \n", | |
"# BankAcount.deposit(x, 100)\n", | |
"\n", | |
"y.deposit(50)\n", | |
"\n", | |
"x.withdraw(10)\n", | |
"y.withdraw(20)\n", | |
"\n", | |
"print x.balance, y.balance\n" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Overwriting bank2.py\n" | |
] | |
} | |
], | |
"prompt_number": 45 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python bank2.py" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"90 30\r\n" | |
] | |
} | |
], | |
"prompt_number": 46 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"**Problem: Timer**" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# Lets say we want to measure time taken by a function.\n", | |
"import time\n", | |
"\n", | |
"def f():\n", | |
" for i in range(1000):\n", | |
" g()\n", | |
" h()\n", | |
" \n", | |
"def g():\n", | |
" sum = 0\n", | |
" for i in range(1000):\n", | |
" sum = sum + i * i\n", | |
" return sum\n", | |
"\n", | |
"def h():\n", | |
" sum = 0\n", | |
" for i in range(1000):\n", | |
" sum = sum + i ** 2\n", | |
" return sum\n", | |
"\n", | |
"def main():\n", | |
" t0 = time.time()\n", | |
" f()\n", | |
" t1 = time.time()\n", | |
" print \"time taken\", t1-t0\n", | |
" \n", | |
"main()" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"time taken 0.291068077087\n" | |
] | |
} | |
], | |
"prompt_number": 48 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# Now lets say we want to measure time taken \n", | |
"# by each function separately. How to do that?\n", | |
"# We create a Timer class.\n", | |
"\n", | |
"class Timer:\n", | |
" def __init__(self):\n", | |
" self.t0 = 0\n", | |
" self.elapsed = 0\n", | |
" self.count = 0\n", | |
" \n", | |
" def start(self):\n", | |
" # remember when the timer is started\n", | |
" self.t0 = time.time()\n", | |
" \n", | |
" def stop(self):\n", | |
" # time when the timer is stopped\n", | |
" t1 = time.time()\n", | |
" \n", | |
" # find the difference\n", | |
" dt = t1 - self.t0\n", | |
" \n", | |
" self.elapsed += dt\n", | |
" self.count += 1 \n", | |
" \n", | |
" def avgtime(self):\n", | |
" # average time taken by each \n", | |
" # start-stop cycle\n", | |
" return self.elapsed / self.count\n", | |
" \n", | |
"def f():\n", | |
" tf.start()\n", | |
" for i in range(1000):\n", | |
" g()\n", | |
" h()\n", | |
" tf.stop()\n", | |
" \n", | |
"def g():\n", | |
" tg.start()\n", | |
" sum = 0\n", | |
" for i in range(1000):\n", | |
" sum = sum + i * i\n", | |
" tg.stop()\n", | |
" return sum\n", | |
"\n", | |
"def h():\n", | |
" th.start()\n", | |
" sum = 0\n", | |
" for i in range(1000):\n", | |
" sum = sum + i ** 2\n", | |
" th.stop()\n", | |
" return sum\n", | |
"\n", | |
"tf = Timer()\n", | |
"tg = Timer()\n", | |
"th = Timer()\n", | |
"\n", | |
"def main():\n", | |
" f()\n", | |
" print \"time taken by f\", tf.elapsed\n", | |
" print \"time taken by g\", tg.elapsed, tg.avgtime()\n", | |
" print \"time taken by h\", th.elapsed, th.avgtime()\n", | |
" \n", | |
"main()" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"time taken by f 0.335296869278\n", | |
"time taken by g 0.141316652298 0.000141316652298\n", | |
"time taken by h 0.18944478035 0.00018944478035\n" | |
] | |
} | |
], | |
"prompt_number": 52 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"## Exceptions" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"foo" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"ename": "NameError", | |
"evalue": "name 'foo' is not defined", | |
"output_type": "pyerr", | |
"traceback": [ | |
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", | |
"\u001b[0;32m<ipython-input-53-d3b07384d113>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mfoo\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", | |
"\u001b[0;31mNameError\u001b[0m: name 'foo' is not defined" | |
] | |
} | |
], | |
"prompt_number": 53 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"open(\"foo.txt\") # opening a file which is not there" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"ename": "IOError", | |
"evalue": "[Errno 2] No such file or directory: 'foo.txt'", | |
"output_type": "pyerr", | |
"traceback": [ | |
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mIOError\u001b[0m Traceback (most recent call last)", | |
"\u001b[0;32m<ipython-input-54-55b95bede01e>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"foo.txt\"\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# opening a file which is not there\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", | |
"\u001b[0;31mIOError\u001b[0m: [Errno 2] No such file or directory: 'foo.txt'" | |
] | |
} | |
], | |
"prompt_number": 54 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"\n" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"# Sometimes we may want to handle these errors\n", | |
"\n", | |
"def read_config():\n", | |
" \"\"\"Looks at config.txt in the current\n", | |
" directory and load the configuration.\n", | |
" \"\"\"\n", | |
" try:\n", | |
" f = open(\"config.txt\")\n", | |
" value = f.read()\n", | |
" except IOError:\n", | |
" print \"no configuration found. ignoring...\"\n", | |
" except SomeOtherError:\n", | |
" pass\n", | |
" \n", | |
" \n" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [], | |
"prompt_number": 61 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"%%file csvsum.py\n", | |
"\"\"\"Example: Find sum of values in the third\n", | |
"column of a CSV file.\n", | |
"\"\"\"\n", | |
"import sys\n", | |
"\n", | |
"def parse_csv(filename):\n", | |
" return [line.strip().split(\",\") \n", | |
" for line in open(filename).readlines()]\n", | |
"\n", | |
"def safeint(value):\n", | |
" try:\n", | |
" return int(value)\n", | |
" except ValueError:\n", | |
" print \"WARNING: bad number\", value\n", | |
" return 0\n", | |
"\n", | |
"def find_sum(filename):\n", | |
" \"\"\"Finds sum of the third column in given\n", | |
" filename\"\"\"\n", | |
" rows = parse_csv(filename)\n", | |
" col3 = [safeint(row[2]) for row in rows]\n", | |
" return sum(col3)\n", | |
"\n", | |
"def main():\n", | |
" try:\n", | |
" filename = sys.argv[1]\n", | |
" except IndexError:\n", | |
" print \"USAGE: python csvsum.py input.csv\"\n", | |
" return\n", | |
" \n", | |
" try:\n", | |
" print find_sum(filename)\n", | |
" except IOError:\n", | |
" print \"file not found:\", filename\n", | |
"\n", | |
"if __name__ == \"__main__\":\n", | |
" main()" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Overwriting csvsum.py\n" | |
] | |
} | |
], | |
"prompt_number": 82 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python csvsum.py foo.csv" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"file not found: foo.csv\r\n" | |
] | |
} | |
], | |
"prompt_number": 68 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"%%file col3.csv\n", | |
"a,aa,1\n", | |
"b,bb,2\n", | |
"c,cc,N/A\n", | |
"d,dd,4" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Overwriting col3.csv\n" | |
] | |
} | |
], | |
"prompt_number": 86 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python csvsum.py col3.csv" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"WARNING: bad number N/A\r\n", | |
"7\r\n" | |
] | |
} | |
], | |
"prompt_number": 87 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python csvsum.py " | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"USAGE: python csvsum.py input.csv\r\n" | |
] | |
} | |
], | |
"prompt_number": 83 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"The case of rows with less than 3 columns is not handled. Can you try fixing that?" | |
] | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"**Defining our own exceptions**" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"%%file bank3.py\n", | |
"\n", | |
"class InsufficientBalanceError(Exception):\n", | |
" pass\n", | |
"\n", | |
"class BankAccount:\n", | |
" def __init__(self):\n", | |
" self.balance = 0\n", | |
" \n", | |
" def deposit(self, amount):\n", | |
" self.balance = self.balance + amount\n", | |
"\n", | |
" def withdraw(self, amount):\n", | |
" if self.balance < amount:\n", | |
" raise InsufficientBalanceError(\"low balance\")\n", | |
" self.balance = self.balance - amount\n", | |
" \n", | |
"if __name__ == \"__main__\":\n", | |
" x = BankAccount()\n", | |
" x.deposit(100)\n", | |
" x.withdraw(40)\n", | |
" x.withdraw(70)\n", | |
" print x.balance\n" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Overwriting bank3.py\n" | |
] | |
} | |
], | |
"prompt_number": 92 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python bank3.py" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Traceback (most recent call last):\r\n", | |
" File \"bank3.py\", line 21, in <module>\r\n", | |
" x.withdraw(70)\r\n", | |
" File \"bank3.py\", line 14, in withdraw\r\n", | |
" raise InsufficientBalanceError(\"low balance\")\r\n", | |
"__main__.InsufficientBalanceError: low balance\r\n" | |
] | |
} | |
], | |
"prompt_number": 93 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"## Writing Unittests" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"%%file test_bank3.py\n", | |
"\n", | |
"import unittest\n", | |
"from bank3 import BankAccount\n", | |
"\n", | |
"class TestBankAccount(unittest.TestCase):\n", | |
" def setUp(self):\n", | |
" print \"setUp: before each test\"\n", | |
"\n", | |
" def tearDown(self):\n", | |
" print \"tearDown: after each test\"\n", | |
" \n", | |
" def test_initial(self):\n", | |
" print \"test_initial\"\n", | |
" b = BankAccount()\n", | |
" self.assertEquals(b.balance, 0)\n", | |
"\n", | |
" def test_deposit(self):\n", | |
" print \"test_deposit\" \n", | |
" b = BankAccount()\n", | |
" b.deposit(100)\n", | |
" self.assertEquals(b.balance, 101)\n", | |
"\n", | |
" \n", | |
"if __name__ == \"__main__\":\n", | |
" unittest.main()\n" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"Overwriting test_bank3.py\n" | |
] | |
} | |
], | |
"prompt_number": 104 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python test_bank3.py" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"setUp: before each test\r\n", | |
"test_deposit\r\n", | |
"FtearDown: after each test\r\n", | |
"setUp: before each test\r\n", | |
"test_initial\r\n", | |
"tearDown: after each test\r\n", | |
".\r\n", | |
"======================================================================\r\n", | |
"FAIL: test_deposit (__main__.TestBankAccount)\r\n", | |
"----------------------------------------------------------------------\r\n", | |
"Traceback (most recent call last):\r\n", | |
" File \"test_bank3.py\", line 21, in test_deposit\r\n", | |
" self.assertEquals(b.balance, 101)\r\n", | |
"AssertionError: 100 != 101\r\n", | |
"\r\n", | |
"----------------------------------------------------------------------\r\n", | |
"Ran 2 tests in 0.000s\r\n", | |
"\r\n", | |
"FAILED (failures=1)\r\n" | |
] | |
} | |
], | |
"prompt_number": 105 | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [ | |
"!python test_bank3.py -v" | |
], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"output_type": "stream", | |
"stream": "stdout", | |
"text": [ | |
"test_deposit (__main__.TestBankAccount) ... ok\r\n", | |
"test_initial (__main__.TestBankAccount) ... ok\r\n", | |
"\r\n", | |
"----------------------------------------------------------------------\r\n", | |
"Ran 2 tests in 0.000s\r\n", | |
"\r\n", | |
"OK\r\n" | |
] | |
} | |
], | |
"prompt_number": 101 | |
}, | |
{ | |
"cell_type": "markdown", | |
"metadata": {}, | |
"source": [ | |
"Things to discuss in the mailing list:\n", | |
"\n", | |
"* bangpypers - [email protected] - http://mail.python.org/mailman/listinfo/bangpypers\n", | |
"* Parsing XML\n", | |
"* Using modules globally\n", | |
"* urllib with login\n", | |
"* parsing HTML\n", | |
"* Django\n", | |
"* Regular Expressions\n", | |
"* matplotlib\n", | |
"* handling unicode\n", | |
"* py.test\n", | |
"* iterators\n", | |
"* More problems to solve" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"collapsed": false, | |
"input": [], | |
"language": "python", | |
"metadata": {}, | |
"outputs": [] | |
} | |
], | |
"metadata": {} | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment