Skip to content

Instantly share code, notes, and snippets.

@ostrowr
Last active February 24, 2016 04:58
Show Gist options
  • Save ostrowr/fd9bd7227247b2ae59f8 to your computer and use it in GitHub Desktop.
Save ostrowr/fd9bd7227247b2ae59f8 to your computer and use it in GitHub Desktop.
Python Review Session
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#Welcome to the wonderful world of Python!"
]
},
{
"cell_type": "code",
"execution_count": 231,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/html": [
"<img src=\"https://imgs.xkcd.com/comics/python.png\"/>"
],
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"execution_count": 231,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"from IPython.display import Image\n",
"Image(url='https://imgs.xkcd.com/comics/python.png') "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Other notes:\n",
" \n",
"* Remember to include `__init__.py` in packages\n",
"* Some keywords, like `in`, have different runtimes for different data structures. For example, `key in set` is O(1), while `key in list` is O(n).\n",
"* Duck typing can be really useful, but be careful\n",
"* Try/except: make sure you only catch the exception that you're expecting\n",
"* Docstrings!"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###First, and most importantly: Documentation"
]
},
{
"cell_type": "code",
"execution_count": 232,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"\"\\nThis is a multiline comment (but it's also a string!)\\n\""
]
},
"execution_count": 232,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# This is a comment\n",
"\n",
"\"\"\"\n",
"This is a multiline comment (but it's also a string!)\n",
"\"\"\"\n",
"\n",
"# make sure your whitespace is consistent! I recommend 4 spaces."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Arithmetic\n",
"####Most implementations of Python are *interpreted*, not *compiled*\n",
"####I'm using an [IPython Notebook](http://ipython.org/notebook.html)"
]
},
{
"cell_type": "code",
"execution_count": 233,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n"
]
}
],
"source": [
"# adding 1 + 1\n",
"print 1 + 1"
]
},
{
"cell_type": "code",
"execution_count": 234,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n"
]
}
],
"source": [
"# By default, Python does integer division\n",
"print 1 / 2"
]
},
{
"cell_type": "code",
"execution_count": 235,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.5\n",
"0.5\n",
"0.5\n"
]
}
],
"source": [
"# But include a float, and it will be automatically coerced\n",
"print 1 / 2.0\n",
"print 1 / 2.\n",
"print 1 / float(2)"
]
},
{
"cell_type": "code",
"execution_count": 236,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"16\n"
]
}
],
"source": [
"# Exponentiate using **\n",
"print 2**4"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###Variables"
]
},
{
"cell_type": "code",
"execution_count": 237,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Robbie\n"
]
}
],
"source": [
"# No need to declare a type\n",
"name = \"Robbie\"\n",
"print name"
]
},
{
"cell_type": "code",
"execution_count": 238,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"42\n"
]
}
],
"source": [
"# Variables of one \"type\" can be redeclared, no problem\n",
"name = 42\n",
"print name"
]
},
{
"cell_type": "code",
"execution_count": 239,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'11'"
]
},
"execution_count": 239,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Operators work as expected on non-traditional types. \n",
"# see \"magic methods\" below.\n",
"'1' * 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###Common [Built-in types](https://docs.python.org/2/library/types.html)"
]
},
{
"cell_type": "code",
"execution_count": 240,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"single, double, triple quotes, doesn't matter.\n",
"[1, 2, 3]\n"
]
}
],
"source": [
"# string (immutable)\n",
"print ('single, ' \"double, \" \n",
" \"\"\"triple quotes, \"\"\" \"doesn't matter.\")\n",
"\n",
"print str([1, 2, 3])"
]
},
{
"cell_type": "code",
"execution_count": 241,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"114813069527425452423283320117768198402231770208869520047764273682576626139237031385665948631650626991844596463898746277344711896086305533142593135616665318539129989145312280000688779148240044871428926990063486244781615463646388363947317026040466353970904996558162398808944629605623311649536164221970332681344168908984458505602379484807914058900934776500429002716706625830522008132236281291761267883317206598995396418127021779858404042159853183251540889433902091920554957783589672039160081957216630582755380425583726015528348786419432054508915275783882625175435528800822842770817965453762184851149029376\n",
"2\n"
]
}
],
"source": [
"# int/long (arbitrary size, limited by memory, automatic promotion)\n",
"print 2**2000\n",
"print int('2')"
]
},
{
"cell_type": "code",
"execution_count": 242,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3]\n",
"[1, 2, 3, 4]\n",
"[1, 2, 3]\n"
]
}
],
"source": [
"# mutable objects point to the same object after assignment!\n",
"# (unless copied)\n",
"# (or deepcopied (copied recursively))\n",
"\n",
"import copy\n",
"a = [1, 2, 3]\n",
"print a\n",
"b = copy.copy(a)\n",
"b.append(4)\n",
"print b\n",
"print a"
]
},
{
"cell_type": "code",
"execution_count": 243,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.0\n"
]
},
{
"data": {
"text/plain": [
"2.49"
]
},
"execution_count": 243,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# float \n",
"\n",
"print float('2')\n",
"\n",
"2.490"
]
},
{
"cell_type": "code",
"execution_count": 244,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"True\n"
]
}
],
"source": [
"# bool\n",
"\n",
"print bool(1)"
]
},
{
"cell_type": "code",
"execution_count": 245,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"False\n",
"True\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 245,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# None (Python's NULL)\n",
"\n",
"# Compare to none with `is`\n",
"print 0 is None\n",
"print None is None\n",
"\n",
"bool([0])"
]
},
{
"cell_type": "code",
"execution_count": 246,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"set([])\n",
"set([1, 2, 3, 4])\n"
]
}
],
"source": [
"# set (unique elements, O(1) membership)\n",
"\n",
"print set()\n",
"print {1, 2, 3, 4}\n"
]
},
{
"cell_type": "code",
"execution_count": 247,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n",
"5\n"
]
}
],
"source": [
"# dict (key-value store, O(1) lookup)\n",
"# (keys must be immutable and hashable)\n",
"\n",
"d = {\n",
" 1: 4, \n",
" 'a': 5\n",
"}\n",
"\n",
"print d[1]\n",
"\n",
"print d['a']"
]
},
{
"cell_type": "code",
"execution_count": 248,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# data structures can hold any combination of types\n",
"l = [1, '1', {1, 2, 3}, {'a': 4}, [35, 90]]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Importing modules/packages"
]
},
{
"cell_type": "code",
"execution_count": 249,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# you can import from the current directory, \n",
"# or from anywhere on your PYTHONPATH\n",
"\n",
"# all Python modules can be imported!\n",
"# but don't forget the \n",
"# if __name__ == \"__main__\": \n",
"# guard.\n",
"\n",
"# import mathematics (current dir on my computer)\n",
"import math # now, the math object holds all the functions/objects in math\n"
]
},
{
"cell_type": "code",
"execution_count": 250,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['__doc__',\n",
" '__file__',\n",
" '__name__',\n",
" '__package__',\n",
" 'acos',\n",
" 'acosh',\n",
" 'asin',\n",
" 'asinh',\n",
" 'atan',\n",
" 'atan2',\n",
" 'atanh',\n",
" 'ceil',\n",
" 'copysign',\n",
" 'cos',\n",
" 'cosh',\n",
" 'degrees',\n",
" 'e',\n",
" 'erf',\n",
" 'erfc',\n",
" 'exp',\n",
" 'expm1',\n",
" 'fabs',\n",
" 'factorial',\n",
" 'floor',\n",
" 'fmod',\n",
" 'frexp',\n",
" 'fsum',\n",
" 'gamma',\n",
" 'hypot',\n",
" 'isinf',\n",
" 'isnan',\n",
" 'ldexp',\n",
" 'lgamma',\n",
" 'log',\n",
" 'log10',\n",
" 'log1p',\n",
" 'modf',\n",
" 'pi',\n",
" 'pow',\n",
" 'radians',\n",
" 'sin',\n",
" 'sinh',\n",
" 'sqrt',\n",
" 'tan',\n",
" 'tanh',\n",
" 'trunc']"
]
},
"execution_count": 250,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dir(math)"
]
},
{
"cell_type": "code",
"execution_count": 251,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3.14159265359\n",
"Create portable serialized representations of Python objects.\n",
"\n",
"See module cPickle for a (much) faster implementation.\n",
"See module copy_reg for a mechanism for registering custom picklers.\n",
"See module pickletools source for extensive comments.\n",
"\n",
"Classes:\n",
"\n",
" Pickler\n",
" Unpickler\n",
"\n",
"Functions:\n",
"\n",
" dump(object, file)\n",
" dumps(object) -> string\n",
" load(file) -> object\n",
" loads(string) -> object\n",
"\n",
"Misc variables:\n",
"\n",
" __version__\n",
" format_version\n",
" compatible_formats\n",
"\n",
"\n"
]
}
],
"source": [
"# other syntaxes\n",
"\n",
"# import a single function\n",
"from math import pi\n",
"print pi\n",
"\n",
"# from multiplication import * # don't do this! It clutters the namespace.\n",
"\n",
"import pickle as pkl\n",
"print pkl.__doc__"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###Functions"
]
},
{
"cell_type": "code",
"execution_count": 252,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5.0\n",
"6.0\n",
"2.5\n",
"2.5\n",
"3.0\n"
]
}
],
"source": [
"def mean(a=6, b=4): # default arguments\n",
" \"\"\"Return the mean of 2 numbers.\"\"\" # docstring\n",
" return (a + b) / 2.\n",
"\n",
"print mean()\n",
"print mean(a=8)\n",
"print mean(2, 3)\n",
"print mean(a=2, b=3)\n",
"\n",
"#override mean\n",
"def mean(ls):\n",
" \"\"\"Return the mean of an iterable.\"\"\"\n",
" return float(sum(ls)) / len(ls)\n",
"\n",
"print mean([1, 2, 3, 4, 5])"
]
},
{
"cell_type": "code",
"execution_count": 253,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"433494437"
]
},
"execution_count": 253,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def fibo(n):\n",
" \"\"\"Returns the nth fibonacci number.\"\"\"\n",
" cache = {}\n",
" def fibo_recursive(n): # nested functions are sometimes useful\n",
" if n == 1 or n == 2:\n",
" return 1\n",
" prev = cache[n - 1] if n - 1 in cache else fibo_recursive(n - 1)\n",
" ante_prev = cache[n - 2] if n - 2 in cache else fibo_recursive(n - 2)\n",
" cache[n] = prev + ante_prev\n",
" return prev + ante_prev\n",
" return fibo_recursive(n)\n",
"\n",
"fibo(43)"
]
},
{
"cell_type": "code",
"execution_count": 254,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7\n",
"4\n"
]
},
{
"data": {
"text/plain": [
"9"
]
},
"execution_count": 254,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# careful with scope!\n",
"\n",
"a = 4\n",
"def hello(a):\n",
" print a\n",
" \n",
"hello(7)\n",
"a = 6\n",
"hello(4)\n",
"\n",
"if 1: # 1 is \"truthy\".\n",
" b = 9\n",
"\n",
"b\n",
" "
]
},
{
"cell_type": "code",
"execution_count": 255,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0.0,\n",
" 1.0,\n",
" 1.4142135623730951,\n",
" 1.7320508075688772,\n",
" 2.0,\n",
" 2.23606797749979,\n",
" 2.449489742783178,\n",
" 2.6457513110645907,\n",
" 2.8284271247461903,\n",
" 3.0]"
]
},
"execution_count": 255,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# generators\n",
"def gen_squares(start, finish=None):\n",
" if finish is None:\n",
" while True:\n",
" yield start**2\n",
" start += 1\n",
" else:\n",
" while start < finish:\n",
" yield start**2\n",
" start += 1\n",
" \n",
"# functions are first-class objects \n",
"def gen_f(f, inputs):\n",
" for i in inputs:\n",
" yield f(i)\n",
" \n",
"list(gen_f(math.sqrt, range(10)))"
]
},
{
"cell_type": "code",
"execution_count": 256,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Ada\n",
"1\n",
"Hello, Babbage\n",
"2\n",
"Hello, Church\n",
"3\n"
]
}
],
"source": [
"# decorators\n",
"def counted(f):\n",
" def wrapped(*args, **kwargs):\n",
" wrapped.calls += 1\n",
" return f(*args, **kwargs)\n",
" wrapped.calls = 0\n",
" return wrapped\n",
"\n",
"@counted\n",
"def say_hello(name):\n",
" print \"Hello, {}\".format(name)\n",
"\n",
"say_hello(\"Ada\")\n",
"print say_hello.calls\n",
"say_hello(\"Babbage\")\n",
"print say_hello.calls\n",
"say_hello(\"Church\")\n",
"print say_hello.calls"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"###Classes"
]
},
{
"cell_type": "code",
"execution_count": 257,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from copy import deepcopy\n",
"import random\n",
"\n",
"class CS161():\n",
" \"\"\"CS161 is a class!\"\"\"\n",
" def __init__(self, students=set(), topics=[], algorithms=[]):\n",
" \"\"\"Initialize a CS161 object.\"\"\"\n",
" self.students = deepcopy(students)\n",
" self.topics = deepcopy(topics)\n",
" \n",
" # don't do this, because you might\n",
" # overwrite other attrs and it's not particularly\n",
" # self-documenting. Instead, it's better to have \n",
" # an attribute self.algorithms such that\n",
" # self.algorithms['fibo'] = fibo\n",
" # so calling self.algorithms['fibo'](3) == 2\n",
" for algorithm in algorithms:\n",
" setattr(self, algorithm.__name__, algorithm)\n",
" \n",
" # magic methods\n",
" def __len__(self):\n",
" \"\"\"Return the number of students in the class.\n",
" \n",
" Defines the `len` function\"\"\"\n",
" return len(self.students)\n",
" \n",
" def __str__(self):\n",
" \"\"\"Describe this object as a string\n",
" \n",
" Defines the `str` function\"\"\"\n",
" description = \"nothing!\"\n",
" if self.topics:\n",
" description = ', '.join(self.topics[:-1]) + \" and \" + self.topics[-1] + '!'\n",
" return \"CS161 is a class about {}\".format(description)\n",
" \n",
" \n",
" def __eq__(self, other):\n",
" \"\"\"Two CS161 classes are the same if all \n",
" the students are the same.\n",
" \"\"\"\n",
" return self.students == other.students\n",
" \n",
" @counted\n",
" def ask_question(self, question):\n",
" print question\n",
" \n",
" def count_questions_asked(self):\n",
" return self.ask_question.calls\n",
" \n",
" def assign_grades(self):\n",
" # dict comprehension!\n",
" self.grades = {student: random.choice('ABCDF') for student in students}\n",
"\n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": 258,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"algorithms = {mean, fibo}\n",
"students = [\"Ada\", \"Babbage\", \"Church\"]\n",
"topics = [\"Red-Black trees\", \"More red-black trees\"]"
]
},
{
"cell_type": "code",
"execution_count": 259,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"our_class = CS161(students=students, topics=topics, algorithms=algorithms)"
]
},
{
"cell_type": "code",
"execution_count": 260,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"CS161 is a class about Red-Black trees and More red-black trees!\n"
]
}
],
"source": [
"print our_class"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": 261,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"What's the best algorithm?\n",
"1\n",
"What's the worst algorithm?\n",
"2\n"
]
}
],
"source": [
"our_class.ask_question(\"What's the best algorithm?\")\n",
"print our_class.ask_question.calls\n",
"our_class.ask_question(\"What's the worst algorithm?\")\n",
"print our_class.ask_question.calls"
]
},
{
"cell_type": "code",
"execution_count": 262,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# list comprehension\n",
"student = [student.lower() for student in our_class.students]"
]
},
{
"cell_type": "code",
"execution_count": 263,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{1: 4, 2: 5, 3: 6}"
]
},
"execution_count": 263,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# using zip\n",
"dict(zip([1, 2, 3], [4, 5, 6]))"
]
},
{
"cell_type": "code",
"execution_count": 264,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"our_class.assign_grades()"
]
},
{
"cell_type": "code",
"execution_count": 265,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{'Ada': 'B', 'Babbage': 'C', 'Church': 'A'}"
]
},
"execution_count": 265,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"our_class.grades"
]
},
{
"cell_type": "code",
"execution_count": 266,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[(0, 1),\n",
" (0, 2),\n",
" (0, 3),\n",
" (0, 4),\n",
" (1, 2),\n",
" (1, 3),\n",
" (1, 4),\n",
" (2, 3),\n",
" (2, 4),\n",
" (3, 4)]"
]
},
"execution_count": 266,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# useful packages: itertools and numpy\n",
"import itertools\n",
"\n",
"list(itertools.combinations(range(5), 2))"
]
},
{
"cell_type": "code",
"execution_count": 267,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 268,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"array([1, 2, 3, 4])"
]
},
"execution_count": 268,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.array([1, 2, 3, 4])"
]
},
{
"cell_type": "code",
"execution_count": 269,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a = \"hello\"\n",
"b = \"goodbye\""
]
},
{
"cell_type": "code",
"execution_count": 270,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'hello'"
]
},
"execution_count": 270,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a"
]
},
{
"cell_type": "code",
"execution_count": 271,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'goodbye'"
]
},
"execution_count": 271,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b"
]
},
{
"cell_type": "code",
"execution_count": 272,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a, b = b, a"
]
},
{
"cell_type": "code",
"execution_count": 273,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'goodbye'"
]
},
"execution_count": 273,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a"
]
},
{
"cell_type": "code",
"execution_count": 274,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'hello'"
]
},
"execution_count": 274,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b"
]
},
{
"cell_type": "code",
"execution_count": 275,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# automatic unpacking\n",
"\n",
"def return_a_lot():\n",
" return (1, 2, 3)"
]
},
{
"cell_type": "code",
"execution_count": 276,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"a, b, c = return_a_lot()"
]
},
{
"cell_type": "code",
"execution_count": 277,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 277,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a"
]
},
{
"cell_type": "code",
"execution_count": 278,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 278,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b"
]
},
{
"cell_type": "code",
"execution_count": 279,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 279,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"c"
]
},
{
"cell_type": "code",
"execution_count": 280,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"# throw away values you don't need with _\n",
"a, _, c = return_a_lot()"
]
},
{
"cell_type": "code",
"execution_count": 281,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 281,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"a"
]
},
{
"cell_type": "code",
"execution_count": 282,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[True, True, True, True]\n",
"[False, False, False, False]\n",
"truthy values are true\n",
"falsy values are false\n"
]
}
],
"source": [
"truthy = [1, [0], {0}, {0: 0}]\n",
"\n",
"falsy = [0, [], {}, set()]\n",
"\n",
"print [bool(t) for t in truthy]\n",
"\n",
"print [bool(f) for f in falsy]\n",
"\n",
"if all(truthy):\n",
" print \"truthy values are true\"\n",
" \n",
"if not any(falsy):\n",
" print \"falsy values are false\""
]
},
{
"cell_type": "code",
"execution_count": 283,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Can't divide by 0\n"
]
},
{
"ename": "ZeroDivisionError",
"evalue": "integer division or modulo by zero",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-283-b446cecc0c23>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 9\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mIndexError\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m# this errors out still, because we don't expect ZeroDivisionError\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0;34m\"Can't divide by 0\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mZeroDivisionError\u001b[0m: integer division or modulo by zero"
]
}
],
"source": [
"# exceptions\n",
"try:\n",
" 1/0\n",
"except ZeroDivisionError: # only catch errors you're expecting\n",
" print \"Can't divide by 0\"\n",
" \n",
"try:\n",
" 1/0\n",
"except IndexError: # this errors out still, because we don't expect ZeroDivisionError\n",
" print \"Can't divide by 0\""
]
}
],
"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.10"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment