Skip to content

Instantly share code, notes, and snippets.

@karanluthra
Created June 2, 2016 14:48
Show Gist options
  • Save karanluthra/e8480687ee2f4e3d99bc5a7427f7313f to your computer and use it in GitHub Desktop.
Save karanluthra/e8480687ee2f4e3d99bc5a7427f7313f to your computer and use it in GitHub Desktop.
Python 101 Notebook
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Python 101"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Language Basics "
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Notes about Language - interpreter, bytecode\n",
"# python being a spec, cpython, ironpython etc are implementations\n",
"# python syntax relying on indentation for blocks/scope\n",
"# syntax aims at being very readable -- as in reads like natural language\n",
"# for item in items, print \"Correct\" if True else \"Incorrect\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This was imp"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello World\n",
"hello world\n",
"What's up?\n",
"What\"s up?\n",
"\\0/\n",
"Foo \"Cool\" Bar\n"
]
}
],
"source": [
"print \"Hello World\"\n",
"print 'hello world'\n",
"print \"What's up?\"\n",
"print \"What\\\"s up?\"\n",
"print \"\\\\0/\"\n",
"print 'Foo \"Cool\" Bar'"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"my name is khan\n"
]
}
],
"source": [
"name = \"khan\"\n",
"print \"my name is %s\" %(name)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"my name is khan\n"
]
}
],
"source": [
"print \"my name is {}\".format(name)"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"my name is khan and kha\n"
]
}
],
"source": [
"print \"my name is {} and {}\".format(name, name[:3])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More cool stuff at the PyFormat page: https://pyformat.info/"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"my name is khan and kha\n",
"..........\n"
]
}
],
"source": [
"intro = \"my name is {} and {}\".format(name, name[:3])\n",
"print intro\n",
"print \".\" * 10"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# create a new file called cli.py and put the following in it\n",
"script_contents = '''\n",
"from sys import argv\n",
"\n",
"script, first, second, third = argv\n",
"\n",
"print \"The script is called:\", script\n",
"print \"Your first variable is:\", first\n",
"print \"Your second variable is:\", second\n",
"print \"Your third variable is:\", third\n",
"'''\n",
"# execute the script from command line using python, passing it 3 args\n",
"# $ python cli.py foo bar baz"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# single line comment"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"'''\n",
"multiple lines of comment??\n",
"This is not the prefered way.\n",
"This syntax is rather the prefered way of writing doc strings.\n",
"For multiple line comment, select the multiple lines\n",
"and let your editer handle toggling of commenting\n",
"read https://www.python.org/dev/peps/pep-0008/#block-comments for more information\n",
"'''\n",
"# Do not use this ^ syntax to achieve the purpose of commenting."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# multiple lines of comment\n",
"# line 2\n",
"# line 3\n",
"# endling line"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"30\n",
"97\n",
"False\n",
"True\n",
"True\n",
"False\n",
"False\n",
"True\n"
]
}
],
"source": [
"print 25 + 30 / 6\n",
"# answer?\n",
"print 100 - 25 * 3 % 4\n",
"# answer?\n",
"print 3 + 2 < 5 - 7\n",
"# answer?\n",
"print 5 > -2\n",
"# answer?\n",
"print 5 >= -2\n",
"# answer?\n",
"print 5 <= -2\n",
"# answer?\n",
"print 5 != 5\n",
"print 5 == 5"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"1.75\n"
]
}
],
"source": [
"print 7/4\n",
"print 7.0/4.0"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n",
"2.4\n",
"1.8\n",
"4\n"
]
}
],
"source": [
"print 7%4\n",
"# what is the remainder when I divide 7 by 4? (4n + r = 7)\n",
"print 7.0%4.6\n",
"# what is the remainder when I divide 7 by 4.6? (4.6n + r =7)\n",
"print 7.0%2.6\n",
"# what is the remainder when I divide 7 by 4.6? (2.6n + r =7)\n",
"# n would be 2 in this case\n",
"\n",
"print 4%7"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"x = 1\n",
"# x++\n",
"# x+=1\n",
"print x"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"False\n"
]
}
],
"source": [
"print True\n",
"print not True"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n",
"True\n",
"False\n"
]
}
],
"source": [
"print True or False\n",
"print False or True\n",
"print False and True"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello\n"
]
}
],
"source": [
"is_beginning = True\n",
"print \"hello\" if is_beginning else \"bye\""
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n"
]
}
],
"source": [
"print False and (\"hello\" if True else \"bye\") and True"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello\n"
]
}
],
"source": [
"print True and (\"hello\" if True else \"bye\")"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<type 'bool'>\n",
"<type 'str'>\n"
]
}
],
"source": [
"bool_expr_1 = False and (\"hello\" if True else \"bye\") and True\n",
"print type(bool_expr_1)\n",
"\n",
"bool_expr_2 = True and (\"hello\" if True else \"bye\")\n",
"print type(bool_expr_2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Control Structures"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Good afternoon\n"
]
}
],
"source": [
"is_morning = False\n",
"is_afternoon = True\n",
"is_evening = False\n",
"is_night = False\n",
"if (is_morning):\n",
" print \"Good morning\"\n",
"elif (is_afternoon):\n",
" print \"Good afternoon\"\n",
"elif (is_evening):\n",
" print \"Good evening\"\n",
"elif (is_night):\n",
" print \"Good night\"\n",
"else:\n",
" print \"Wish you a good time\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# Switch Cases?\n",
"# Python doesn't have switch cases and expects you to put \n",
"# each condition through an if-else structure"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n"
]
}
],
"source": [
"for i in range(10):\n",
" print i"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
"[0, 2, 4, 6, 8]\n",
"[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]\n"
]
}
],
"source": [
"print range(10)\n",
"print range(0,10)\n",
"print range(0,10,2)\n",
"print range(10,0,-1)"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"list"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(range(10))"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"i at entering: 0\n",
"i at end: 1\n",
"i at entering: 1\n",
"i at end: 2\n",
"i at entering: 2\n",
"i at end: 3\n",
"i at entering: 3\n",
"i at end: 4\n",
"i at entering: 4\n",
"i at end: 5\n",
"i at entering: 5\n",
"i at end: 6\n"
]
}
],
"source": [
"i = 0\n",
"while i < 6:\n",
" print \"i at entering: \", i\n",
" i += 1\n",
" print \"i at end: \", i"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* For loops iterate over a collection of things\n",
"* While loops can do any kind of iteration you want"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Data Structures"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Lists"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Mon', 'Tue', 'Wed', 'Thu', 'Fri']\n",
"Wed\n",
"Thu\n"
]
}
],
"source": [
"weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']\n",
"print weekdays\n",
"print weekdays[2]\n",
"print weekdays[-2]\n",
"# If the negative index is confusing to you, think of it this way: \n",
"# li[-n] == li[len(li) - n]. \n",
"# So in this list, li[-3] == li[5 - 3] == li[2].\n",
"\n",
"# the infamous \"out of bound\" exception\n",
"# print weekdays[-9]\n",
"# print weekdays[7]"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Mon', 'Tue', 'Wed', 'Thu', 'Fri']\n",
"['Mon', 'Tue', 'Wed']\n",
"['Mon', 'Tue']\n",
"['Thu', 'Fri']\n",
"['Tue', 'Wed', 'Thu']\n"
]
}
],
"source": [
"print weekdays[:]\n",
"print weekdays[0:3]\n",
"print weekdays[:2]\n",
"print weekdays[3:]\n",
"print weekdays[1:-1]\n",
"# Called List Splicing"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
}
],
"source": [
"print weekdays == weekdays[:3] + weekdays[3:]"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"weekdays[:] == weekdays"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"weekdays[:] is weekdays"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a = 5\n",
"b = int(5)\n",
"a is b"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"days_of_week = weekdays\n",
"days_of_week is weekdays"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n",
"True\n"
]
}
],
"source": [
"x = [1,2,3]\n",
"y = [1,2,3]\n",
"print x is y\n",
"print x == y"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Before: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']\n",
"After: ['Fri', 'Thu', 'Wed', 'Tue', 'Mon']\n",
"Original: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']\n"
]
}
],
"source": [
"# so weekdays[:] is a shorthand for creating a copy of the list \n",
"# lets assign it to another variable to play with it\n",
"copy_weekdays = weekdays[:]\n",
"print \"Before:\" , copy_weekdays\n",
"copy_weekdays.reverse()\n",
"print \"After:\", copy_weekdays\n",
"print \"Original:\", weekdays"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Fri', 'Thu', 'Wed', 'Tue', 'Mon', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri']\n",
"['Fri', 'Thu', 'Fri', 'Thu', 'Fri', 'Thu']\n",
"5\n",
"True\n",
"True\n"
]
}
],
"source": [
"# operators with lists\n",
"print copy_weekdays + weekdays\n",
"print copy_weekdays[:2] * 3\n",
"print len(weekdays)\n",
"print \"Wed\" in weekdays\n",
"print \"Sun\" not in weekdays"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Mon', 'Tue', 'Wed', 'Thu', 'Sat', 'Sat', 'Sat', 'Sat', 'Sat', 'Sat', 'Sun', 'Sun']\n",
"['Mon', 'Tue', 'Wed', 'Thu', 'Sat', 'Sat', 'Sat', 'Sat', 'Sat', 'Sat', 'Sun', 'Sun']\n"
]
}
],
"source": [
"# Methods on lists\n",
"# insert\n",
"# weekdays.insert(5, \"Sat\")\n",
"# append\n",
"# weekdays.append(\"Sun\")\n",
"# index\n",
"# print weekdays.index(\"Thu\")\n",
"# remove\n",
"# weekdays.remove(\"Fri\")\n",
"# pop\n",
"print weekdays\n",
"# weekdays.pop()\n",
"# clear\n",
"# weekdays.clear()\n",
"print weekdays"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Fri', 'Thu', 'Wed', 'Tue', 'Mon']\n",
"['Fri', 'Thu', 'Wed', 'Tue', 'Mon']\n",
"['thu', 'tue']\n"
]
}
],
"source": [
"# List Comprehensions\n",
"weekdays = copy_weekdays\n",
"print weekdays\n",
"print [day for day in weekdays]\n",
"print [day.lower() for day in weekdays if day.startswith(\"T\")]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# ** Lists are mutable (whereas strings are not)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dictionaries"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'first_name': 'James', 'last_name': 'Bond'}\n",
"James\n"
]
}
],
"source": [
"# Hashed key-value pairs.\n",
"person = {\"first_name\":\"James\", \"last_name\":\"Bond\"}\n",
"print person\n",
"print person['first_name']"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'first_name': 'James', 'last_name': 'Pond'}\n"
]
}
],
"source": [
"# change value at key to some new value [replaces the older value]\n",
"person['last_name'] = \"Pond\"\n",
"print person\n",
"# so we cannot have duplicate keys in dictionaries"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# add new key with value anytime\n",
"person['nickname'] = \"007\"\n",
"print person"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'first_name': 'James', 'last_name': 'Pond', 'age': 37}\n"
]
}
],
"source": [
"# dictionaries can hold values of different datatypes\n",
"person['age'] = 37\n",
"print person"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'first_name': 'James', 'last_name': 'Pond', 'age': 37, 'vehicles': ['Aston Martin DB5', 'AMC Hornet X', 'Lotus Espirit']}\n"
]
}
],
"source": [
"person['vehicles'] = ['Aston Martin DB5', 'AMC Hornet X', 'Lotus Espirit']\n",
"print person"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# dictionaries can hold objects or even other dictionaries"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'first_name': 'James', 'last_name': 'Pond', 'age': 37}\n"
]
}
],
"source": [
"# deleting an item from dictionary\n",
"del(person['vehicles'])\n",
"print person"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"if 'vehicles' in person:\n",
" del(person['vehicles'])"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{}\n"
]
}
],
"source": [
"# clear() deletes all items from the dictionary\n",
"person.clear()\n",
"print person"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Tuples\n",
"A tuple is an immutable list. A tuple can not be changed in any way once it is created."
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('a', 'b', 'mpilgrim', 'z', 'example')\n"
]
}
],
"source": [
"t = (\"a\", \"b\", \"mpilgrim\", \"z\", \"example\")\n",
"# notice the parentheses instead of square brackets\n",
"print t"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a\n",
"example\n",
"('b', 'mpilgrim')\n"
]
}
],
"source": [
"# Accessing works exactly like lists\n",
"print t[0]\n",
"print t[-1]\n",
"\n",
"# even splicing works the same way\n",
"print t[1:3]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### You can't do a lot of stuff with tuples\n",
"* You can't add elements to a tuple. Tuples have no append or extend method.\n",
"* You can't remove elements from a tuple. Tuples have no remove or pop method.\n",
"* You can't find elements in a tuple. Tuples have no index method.\n",
"\n",
"* You can, however, use in to see if an element exists in the tuple."
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n",
"True\n"
]
}
],
"source": [
"print t.index('example')\n",
"print 'example' in t"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Tuples are Immutibles\n",
"* \"If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.\"\n",
"* Immutables can be dictionary keys (we had seen string keys, but we can have integers and immutible tuples too)"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Aston Martin DB5', 'AMC Hornet X', 'Lotus Espirit']\n",
"<type 'list'>\n"
]
}
],
"source": [
"# Tuples and Lists\n",
"bond_cars = ['Aston Martin DB5', 'AMC Hornet X', 'Lotus Espirit']\n",
"print bond_cars\n",
"print type(bond_cars)"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('Aston Martin DB5', 'AMC Hornet X', 'Lotus Espirit')\n",
"<type 'tuple'>\n"
]
}
],
"source": [
"bond_cars = tuple(bond_cars)\n",
"print bond_cars\n",
"print type(bond_cars)"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<type 'list'>\n"
]
}
],
"source": [
"bond_cars = list(bond_cars)\n",
"print type(bond_cars)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**tuple _freezes_ a list, and list _thaws_ a tuple**"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a b e\n"
]
}
],
"source": [
"# assigning multiple values at once\n",
"v = ('a', 'b', 'e')\n",
"(x, y, z) = v\n",
"print x, y, z"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"out of memory\n"
]
}
],
"source": [
"# This comes really handy when a function wants to return more than one thing.\n",
"def my_error_prone_func():\n",
" return 1, \"out of memory\"\n",
"\n",
"error_code, error_message = my_error_prone_func()\n",
"if error_code != 0:\n",
" print error_message\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exceptions and File Handling"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"ename": "IOError",
"evalue": "[Errno 2] No such file or directory: '/notthere'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mIOError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-71-9fe08700c54d>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mfsock\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"/notthere\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"r\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mIOError\u001b[0m: [Errno 2] No such file or directory: '/notthere'"
]
}
],
"source": [
"fsock = open(\"/notthere\", \"r\")"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[Errno 2] No such file or directory: '/notthere'\n"
]
}
],
"source": [
"try:\n",
" fsock = open(\"/notthere\", \"r\")\n",
"except IOError as e:\n",
" print e"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[Errno 2] No such file or directory: '/notthere'\n",
"things are normal again\n"
]
}
],
"source": [
"try:\n",
" fsock = open(\"/notthere\", \"r\")\n",
"except IOError as e:\n",
" print e\n",
"else:\n",
" print \"successfully opened file\"\n",
"finally:\n",
" print \"things are normal again\""
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "MyException",
"evalue": "I am a grumpy kid",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mMyException\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-74-6d17eb19abdc>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m__str__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[1;34m\"I am a grumpy kid\"\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mMyException\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mMyException\u001b[0m: I am a grumpy kid"
]
}
],
"source": [
"# You can create your own custom exceptions by sub classing Exception. \n",
"# You can then trigger or \"raise\" that exception in suitable exceptional situations.\n",
"class MyException(Exception):\n",
" def __str__(self):\n",
" return \"I am a grumpy kid\"\n",
"raise MyException"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"f = open(\"sample.txt\", \"w\")\n",
"text = '''Hello World!\n",
"This is a multiline text\n",
"Desperate to be written out to a file.\n",
"'''\n",
"f.write(text)\n",
"f.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Aside:\n",
"The power of ```__doc__```"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"open(name[, mode[, buffering]]) -> file object\n",
"\n",
"Open a file using the file() type, returns a file object. This is the\n",
"preferred way to open a file. See file.__doc__ for further information.\n"
]
}
],
"source": [
"print open.__doc__"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello World!\n",
"This is a multiline text\n",
"Desperate to be written out to a file.\n",
"\n"
]
}
],
"source": [
"f = open(\"sample.txt\", \"r\")\n",
"print f.read()\n",
"f.close()"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello World!\n",
"\n",
"----\n",
"This is a \n",
"----\n",
"multiline \n",
"----\n",
"<type 'list'>\n",
"['text\\n', 'Desperate to be written out to a file.\\n']\n"
]
}
],
"source": [
"f = open(\"sample.txt\", \"r\")\n",
"print f.readline()\n",
"print \"----\"\n",
"print f.read(10)\n",
"print \"----\"\n",
"print f.read(10)\n",
"print \"----\"\n",
"lines = f.readlines()\n",
"print type(lines)\n",
"print lines\n",
"f.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Another way of opening files\n",
"```python\n",
"with open() as f:\n",
" # do stuff\n",
"````"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"with open(\"sample.txt\", \"r\") as f:\n",
" for line in f:\n",
" print line\n",
"\n",
"print f.closed"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Functions in Python"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def greet(name):\n",
" return \"Hello, \" + name + \"!\"\n",
"\n",
"# doesn't need a declaration (like C++ et al)\n",
"# doesn't define a return type (but always returns)\n",
"# if there isnt a return statement, it returns None, the python equivalent of null\n",
"# doesn't need argument types"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python is a __dynamically typed__ language\n",
"- the data are discovered at execution time, i.e. when you assign a value\n",
"- this is opposite of statically typed (as in C, Java)\n",
"\n",
"Python is a __strongly typed__ language\n",
"- types are enforced\n",
"- if you have an integer, you can't treat it like a string without explicitly converting it"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# doc strings\n",
"def greet(name):\n",
" '''\n",
" says a Hello to the name passed as argument\n",
" \n",
" returns string\n",
" '''\n",
" return \"Hello, \" + name + \"!\""
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
" says a Hello to the name passed as argument\n",
" \n",
" returns string\n",
" \n"
]
}
],
"source": [
"print greet.__doc__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"__ Everything in Python is an object, and almost everything has attributes and methods. __"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<function greet at 0x7fdbdce17c08>\n"
]
}
],
"source": [
"# are functions also objects?\n",
"print greet"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<type 'function'>\n"
]
}
],
"source": [
"print type(greet)"
]
},
{
"cell_type": "code",
"execution_count": 85,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']\n"
]
}
],
"source": [
"print dir(greet)"
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Bond!\n"
]
}
],
"source": [
"print greet(\"Bond\")"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, James Bond\n"
]
}
],
"source": [
"# passing args by keywords in python\n",
"def full_name_greet(first_name, last_name):\n",
" return \"Hello, \" + first_name + \" \" + last_name\n",
"\n",
"print full_name_greet(last_name=\"Bond\", first_name=\"James\")"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<type 'tuple'>\n",
"Hey, Mr. Guido van Rossum!\n"
]
}
],
"source": [
"# passing any number of arguments\n",
"def complicated_name_greet(greet, *args):\n",
" print type(args)\n",
" return greet + \", \" + \" \".join(args) + \"!\"\n",
" \n",
"print complicated_name_greet(\"Hey\", \"Mr.\", \"Guido\", \"van\", \"Rossum\") "
]
},
{
"cell_type": "code",
"execution_count": 92,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<type 'tuple'>\n",
"<type 'dict'>\n",
"Hello, Mr. Guido van Rossum, the author of python\n"
]
}
],
"source": [
"# passing any number of keyworded arguments\n",
"def complicated_name_prop_greet(greet, *args, **kwargs):\n",
" print type(args)\n",
" print type(kwargs)\n",
" property_string = \", the \" + kwargs['property_name'] + kwargs['property_value']\n",
" return greet + \", \" + \" \".join(args) + property_string\n",
"\n",
"guido_prop = {\"property_name\":\"author of \",\"property_value\":\"python\"}\n",
"print complicated_name_prop_greet(\"Hello\", \"Mr.\", \"Guido\",\n",
" \"van\", \"Rossum\", **guido_prop)"
]
},
{
"cell_type": "code",
"execution_count": 90,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Karan Luthra\n"
]
}
],
"source": [
"# another great usage of kwargs\n",
"name = {\"first_name\":\"Karan\",\"last_name\":\"Luthra\"}\n",
"print full_name_greet(**name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Modules"
]
},
{
"cell_type": "code",
"execution_count": 94,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"csv\n",
"----\n",
"CSV parsing and writing.\n",
"\n",
"This module provides classes that assist in the reading and writing\n",
"of Comma Separated Value (CSV) files, and implements the interface\n",
"described by PEP 305. Although many CS\n"
]
}
],
"source": [
"# modules are objects too!\n",
"import csv\n",
"print csv.__name__\n",
"print '----'\n",
"print csv.__doc__[:200]"
]
},
{
"cell_type": "code",
"execution_count": 95,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['1', '2', '3', '4']\n",
"['5', '6', '7', '8']\n",
"['9', '10', '11', '12']\n"
]
}
],
"source": [
"import csv\n",
"with open('data.csv') as f:\n",
" for row in csv.reader(f):\n",
" print row"
]
},
{
"cell_type": "code",
"execution_count": 96,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['1', '2', '3', '4']\n",
"['5', '6', '7', '8']\n",
"['9', '10', '11', '12']\n"
]
}
],
"source": [
"# Using the from module import syntax\n",
"from csv import reader\n",
"\n",
"with open('data.csv') as f:\n",
" for row in reader(f):\n",
" print row"
]
},
{
"cell_type": "code",
"execution_count": 97,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['1', '2', '3', '4']\n",
"['5', '6', '7', '8']\n",
"['9', '10', '11', '12']\n"
]
}
],
"source": [
"# import AS name\n",
"from csv import reader as csvreader\n",
"\n",
"with open('data.csv') as f:\n",
" for row in csvreader(f):\n",
" print row"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Regular Expressions\n",
"\n",
"Regular expressions are a powerful language for matching text patterns. \n",
"Python reference: https://docs.python.org/2/howto/regex.html"
]
},
{
"cell_type": "code",
"execution_count": 98,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Support for regular expressions (RE).\n",
"\n",
"This module provides regular expression matching operations similar to\n",
"those found in Perl. It supports both 8-bit and Unicode strings; both\n",
"the pattern and the strings being processed can contain null bytes and\n",
"characters outside the US ASCII range.\n",
"\n",
"Regular expressions can contain both special and ordinary characters.\n",
"Most ordinary characters, like \"A\", \"a\", or \"0\", are the simplest\n",
"regular expressions; they simply match themselves. You can\n",
"concatenate ordinary characters, so last matches the string 'last'.\n",
"\n",
"The special characters are:\n",
" \".\" Matches any character except a newline.\n",
" \"^\" Matches the start of the string.\n",
" \"$\" Matches the end of the string or just before the newline at\n",
" the end of the string.\n",
" \"*\" Matches 0 or more (greedy) repetitions of the preceding RE.\n",
" Greedy means that it will match as many repetitions as possible.\n",
" \"+\" Matches 1 or more (greedy) repetitions of the preceding RE.\n",
" \"?\" Matches 0 or 1 (greedy) of the preceding RE.\n",
" *?,+?,?? Non-greedy versions of the previous three special characters.\n",
" {m,n} Matches from m to n repetitions of the preceding RE.\n",
" {m,n}? Non-greedy version of the above.\n",
" \"\\\\\" Either escapes special characters or signals a special sequence.\n",
" [] Indicates a set of characters.\n",
" A \"^\" as the first character indicates a complementing set.\n",
" \"|\" A|B, creates an RE that will match either A or B.\n",
" (...) Matches the RE inside the parentheses.\n",
" The contents can be retrieved or matched later in the string.\n",
" (?iLmsux) Set the I, L, M, S, U, or X flag for the RE (see below).\n",
" (?:...) Non-grouping version of regular parentheses.\n",
" (?P<name>...) The substring matched by the group is accessible by name.\n",
" (?P=name) Matches the text matched earlier by the group named name.\n",
" (?#...) A comment; ignored.\n",
" (?=...) Matches if ... matches next, but doesn't consume the string.\n",
" (?!...) Matches if ... doesn't match next.\n",
" (?<=...) Matches if preceded by ... (must be fixed length).\n",
" (?<!...) Matches if not preceded by ... (must be fixed length).\n",
" (?(id/name)yes|no) Matches yes pattern if the group with id/name matched,\n",
" the (optional) no pattern otherwise.\n",
"\n",
"The special sequences consist of \"\\\\\" and a character from the list\n",
"below. If the ordinary character is not on the list, then the\n",
"resulting RE will match the second character.\n",
" \\number Matches the contents of the group of the same number.\n",
" \\A Matches only at the start of the string.\n",
" \\Z Matches only at the end of the string.\n",
" \\b Matches the empty string, but only at the start or end of a word.\n",
" \\B Matches the empty string, but not at the start or end of a word.\n",
" \\d Matches any decimal digit; equivalent to the set [0-9].\n",
" \\D Matches any non-digit character; equivalent to the set [^0-9].\n",
" \\s Matches any whitespace character; equivalent to [ \\t\\n\\r\\f\\v].\n",
" \\S Matches any non-whitespace character; equiv. to [^ \\t\\n\\r\\f\\v].\n",
" \\w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_].\n",
" With LOCALE, it will match the set [0-9_] plus characters defined\n",
" as letters for the current locale.\n",
" \\W Matches the complement of \\w.\n",
" \\\\ Matches a literal backslash.\n",
"\n",
"This module exports the following functions:\n",
" match Match a regular expression pattern to the beginning of a string.\n",
" search Search a string for the presence of a pattern.\n",
" sub Substitute occurrences of a pattern found in a string.\n",
" subn Same as sub, but also return the number of substitutions made.\n",
" split Split a string by the occurrences of a pattern.\n",
" findall Find all occurrences of a pattern in a string.\n",
" finditer Return an iterator yielding a match object for each match.\n",
" compile Compile a pattern into a RegexObject.\n",
" purge Clear the regular expression cache.\n",
" escape Backslash all non-alphanumerics in a string.\n",
"\n",
"Some of the functions in this module takes flags as optional parameters:\n",
" I IGNORECASE Perform case-insensitive matching.\n",
" L LOCALE Make \\w, \\W, \\b, \\B, dependent on the current locale.\n",
" M MULTILINE \"^\" matches the beginning of lines (after a newline)\n",
" as well as the string.\n",
" \"$\" matches the end of lines (before a newline) as well\n",
" as the end of the string.\n",
" S DOTALL \".\" matches any character at all, including the newline.\n",
" X VERBOSE Ignore whitespace and comments for nicer looking RE's.\n",
" U UNICODE Make \\w, \\W, \\b, \\B, dependent on the Unicode locale.\n",
"\n",
"This module also defines an exception 'error'.\n",
"\n",
"\n"
]
}
],
"source": [
"import re\n",
"print re.__doc__"
]
},
{
"cell_type": "code",
"execution_count": 99,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Return the string obtained by replacing the leftmost\n",
" non-overlapping occurrences of the pattern in string by the\n",
" replacement repl. repl can be either a string or a callable;\n",
" if a string, backslash escapes in it are processed. If it is\n",
" a callable, it's passed the match object and must return\n",
" a replacement string to be used.\n"
]
}
],
"source": [
"# Lets checkout re.sub()\n",
"print re.sub.__doc__"
]
},
{
"cell_type": "code",
"execution_count": 100,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"my_sample_file.txt\n"
]
}
],
"source": [
"# replace all - in a filename with a _\n",
"filename = \"my-sample-file.txt\"\n",
"pattern = r'-'\n",
"print re.sub(pattern, \"_\", filename)"
]
},
{
"cell_type": "code",
"execution_count": 101,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is string with a LOT of numbers -- etc\n",
"This is string with a LOT of numbers -- etc\n"
]
}
],
"source": [
"sentence = \"This is 1 string with a LOT of numbers -- 4 56 4 78 90 etc\"\n",
"# remove all numbers from a string\n",
"print re.sub(r'[0-9]', \"\", sentence)\n",
"print re.sub(r'\\d', \"\", sentence)"
]
},
{
"cell_type": "code",
"execution_count": 102,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This_is_1_string_with_a_LOT_of_numbers_--_4_56_4_78_90_etc\n"
]
}
],
"source": [
"# convert all spaces to underscores\n",
"print re.sub(r'\\s', \"_\", sentence)"
]
},
{
"cell_type": "code",
"execution_count": 103,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"???????????????????????????????????????--?????????????????\n"
]
}
],
"source": [
"# replace all non alpha numeric and spaces characters with a ?\n",
"print re.sub(r'[\\s0-9a-zA-Z]', \"?\", sentence)"
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is 1 string with a LOT of numbers ?? 4 56 4 78 90 etc\n"
]
}
],
"source": [
"print re.sub(r'[^\\s0-9a-zA-Z]', \"?\", sentence)"
]
},
{
"cell_type": "code",
"execution_count": 107,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"('This is 1 string with a LOT of numbers ?? 4 56 4 78 90 etc', 2)\n"
]
}
],
"source": [
"print re.subn(r'[^\\s0-9a-zA-Z]', \"?\", sentence)"
]
},
{
"cell_type": "code",
"execution_count": 108,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<_sre.SRE_Match object at 0x7fdbdcd64920>\n",
"02-June-2016\n"
]
}
],
"source": [
"# re.match()\n",
"# re.match(pattern, string, flags=0)\n",
"# This function attempts to match RE pattern to string with optional flags\n",
"datestring = '02-June-2016'\n",
"matches = re.match(r'\\d+-\\w+-\\d+', datestring)\n",
"if matches:\n",
" print matches\n",
" print matches.group()\n",
"# print matches.group(1)"
]
},
{
"cell_type": "code",
"execution_count": 109,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"02-June-2016\n",
"02\n",
"June\n",
"2016\n"
]
}
],
"source": [
"matches = re.match(r'(\\d+)-(\\w+)-(\\d+)', datestring)\n",
"if matches:\n",
" print matches.group()\n",
" print matches.group(1)\n",
" print matches.group(2)\n",
" print matches.group(3) "
]
},
{
"cell_type": "code",
"execution_count": 110,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"02-June-2016\n",
"02\n",
"June\n",
"2016\n"
]
}
],
"source": [
"matches = re.match(r'(?P<date>\\d+)-(?P<month>\\w+)-(?P<year>\\d+)', datestring)\n",
"if matches:\n",
" print matches.group()\n",
" print matches.group('date')\n",
" print matches.group('month')\n",
" print matches.group('year')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python's datetime and timedelta"
]
},
{
"cell_type": "code",
"execution_count": 111,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2016-06-02 19:10:33.476792\n",
"<type 'datetime.datetime'>\n"
]
}
],
"source": [
"from datetime import datetime as dt, timedelta as td\n",
"# reference: https://docs.python.org/2/library/datetime.html\n",
"\n",
"print dt.now()\n",
"print type(dt.now())"
]
},
{
"cell_type": "code",
"execution_count": 112,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n",
"\n",
"The year, month and day arguments are required. tzinfo may be None, or an\n",
"instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n",
"\n"
]
}
],
"source": [
"print dt.__doc__"
]
},
{
"cell_type": "code",
"execution_count": 113,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2016-06-01 00:00:00\n"
]
}
],
"source": [
"yesterday = dt(year=2016,month=06,day=01)\n",
"print yesterday"
]
},
{
"cell_type": "code",
"execution_count": 114,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2016-06-02 19:17:01.769600\n",
"2016-06-01 19:17:01.769600\n"
]
}
],
"source": [
"today = dt.today()\n",
"print today\n",
"yesterday = today - td(days=1)\n",
"print yesterday"
]
},
{
"cell_type": "code",
"execution_count": 115,
"metadata": {
"collapsed": false
},
"outputs": [
{
"ename": "TypeError",
"evalue": "unsupported operand type(s) for +: 'int' and 'str'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32m<ipython-input-115-9977ac1dccde>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mprint\u001b[0m \u001b[0mtoday\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mday\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;34m\"/\"\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mtoday\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmonth\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;34m\"/\"\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mtoday\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0myear\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'"
]
}
],
"source": [
"print today.day + \"/\" + today.month + \"/\" + today.year"
]
},
{
"cell_type": "code",
"execution_count": 116,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2/6/2016\n"
]
}
],
"source": [
"print str(today.day) + \"/\" + str(today.month) + \"/\" + str(today.year)"
]
},
{
"cell_type": "code",
"execution_count": 117,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"02/06/2016\n"
]
}
],
"source": [
"frmt=(\"%d/%m/%Y\")\n",
"print dt.today().strftime(frmt)\n",
"# refer http://strftime.org/ for quick ref"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Test Driven Development"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment