Skip to content

Instantly share code, notes, and snippets.

@ony
Last active December 16, 2016 06:31
Show Gist options
  • Save ony/9bc2d3d5f8eb32aeb1fd434f36293aa0 to your computer and use it in GitHub Desktop.
Save ony/9bc2d3d5f8eb32aeb1fd434f36293aa0 to your computer and use it in GitHub Desktop.
Just review of python basic
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Variables, statements"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"47\n"
]
}
],
"source": [
"var1 = 42\n",
"var1 += var1 * 12 / 100 # in python3 will be float\n",
"print var1"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'var1' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-2-2ebe64d58721>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mdel\u001b[0m \u001b[0mvar1\u001b[0m\u001b[0;34m;\u001b[0m \u001b[0;32mprint\u001b[0m \u001b[0mvar1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'var1' is not defined"
]
}
],
"source": [
"del var1; print var1"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Builtin data types / collections"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"(int,\n",
" float,\n",
" complex,\n",
" str,\n",
" unicode,\n",
" 'Escaped \"string\"',\n",
" 'Raw \\\\\"string\\\\\"',\n",
" 'single quotes',\n",
" 'tripple quotes',\n",
" 'triple single quotes',\n",
" 16,\n",
" 8,\n",
" 2)"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(type(2), type(3.), type(3+1j), type(\"String\"), type(u\"Unicode string\"),\n",
" \"Escaped \\\"string\\\"\", r\"Raw \\\"string\\\"\", # escapes\n",
" 'single quotes', \"\"\"tripple quotes\"\"\", '''triple single quotes''',\n",
" 0x10, 0o10, 0b10 # numbers\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'loc': {'x': 1, 'y': 2},\n",
" 'people': [('John', 35), ('Henry', 40)],\n",
" 'tags': {'it', 'python'}}"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"{\"people\": [(\"John\", 35), (\"Henry\", 40)], # list of tuples\n",
" \"loc\": {\"x\":1, \"y\":2}, # dict\n",
" \"tags\": {\"it\", \"python\"} # set\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### List operations"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 2, 3, 4]\n",
"[1, 'a', 'b', 'c', 4]\n",
"[1, 'a', 'b', 'c']\n"
]
}
],
"source": [
"list1 = [1, 2, 3]\n",
"list1.append(4); print list1\n",
"list1[1:3] = \"abc\"; print list1\n",
"print list1[:-1]"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, 'a', 'b', 'c', 4, 0, 2, 4, 6, 8]\n"
]
}
],
"source": [
"list1.extend(range(0, 10, 2)); print list1"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Begin', 1, 'a', 'b', 'c', 4, 0, 2, 4, 6, 8, '-', '-']\n"
]
}
],
"source": [
"print [\"Begin\"] + list1 + [\"-\"]*2"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 1, 2, 4, 4, 6, 8, 'a', 'b', 'c']\n"
]
}
],
"source": [
"list1.sort(); print list1"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Dictionary operations"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 2, 'c': 4, 'b': 2}\n",
"2\n"
]
}
],
"source": [
"dict1 = {'a': 1, 'b': 2}\n",
"dict1['a'] = 2; dict1.setdefault('b', 3); dict1.setdefault('c', 4)\n",
"print dict1\n",
"print dict1['a']"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"ename": "KeyError",
"evalue": "'d'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-10-031bb2effc7f>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mprint\u001b[0m \u001b[0mdict1\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'd'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m: 'd'"
]
}
],
"source": [
"print dict1['d']"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"(None, 2)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"dict1.get('d'), dict1.get('a')"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Control-flow"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'a': 2, 'c': 4, 'b': 2}\n"
]
}
],
"source": [
"if dict1: print dict1\n",
"else:\n",
" print \"empty dict1\""
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"| 0 | 0 |\n",
"| 1 | 1 |\n",
"| 2 | 2 |\n",
"| 3 | 4 |\n",
"| 4 | 4 |\n",
"| 5 | 6 |\n",
"| 6 | 8 |\n",
"| 7 | 'a' |\n",
"| 8 | 'b' |\n",
"| 9 | 'c' |\n"
]
}
],
"source": [
"for i, x in enumerate(list1):\n",
" print \"| %4d | %-10r |\" % (i, x)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n",
"9\n"
]
}
],
"source": [
"i = 0\n",
"while i < 10:\n",
" i += 3\n",
" if (i % 2) == 0: continue\n",
" print i"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Functions"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"120"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def fact(n):\n",
" return 1 if n == 0 else n * fact(n-1)\n",
"fact(5)"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def fib(n, init=(1, 1)):\n",
" if n < 2: return init[n]\n",
" else: return fib(n-1, init=(init[1], sum(init)))\n",
"[fib(k) for k in range(10)]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Keyword global"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"ename": "UnboundLocalError",
"evalue": "local variable 'last_id' referenced before assignment",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mUnboundLocalError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-29-44cd0a45576c>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mlast_id\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mlast_id\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0mget_id\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-29-44cd0a45576c>\u001b[0m in \u001b[0;36mget_id\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mlast_id\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mget_id\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mlast_id\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mlast_id\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mget_id\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mUnboundLocalError\u001b[0m: local variable 'last_id' referenced before assignment"
]
}
],
"source": [
"last_id = 0\n",
"def get_id():\n",
" last_id += 1\n",
" return last_id\n",
"get_id()"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 5]"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def get_id():\n",
" global last_id\n",
" last_id += 1\n",
" return last_id\n",
"[get_id() for k in range(5)]"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## I/O\n",
"```python\n",
"def store(filepath, text):\n",
" \"\"\"Store text to file\n",
" \n",
" filepath path to file\n",
" text: content to store\n",
" \n",
" returns amount of actual bytes written to the file\"\"\"\n",
" with open(filepath, \"w\") as fp:\n",
" fp.write(text)\n",
" return fp.tell()\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"```python\n",
"def chunked_read(filepath, chunk_size=4096):\n",
" \"\"\"Generate stream of chunks read from file\"\"\"\n",
" with open(filepath, \"rb\") as fp:\n",
" while True:\n",
" chunk = fp.read(chunk_size)\n",
" if len(chunk) == 0: break # end of file\n",
" yield chunk\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### Filesystem example\n",
"```python\n",
"import os, os.path\n",
"for entry in os.listdir('.'):\n",
" if os.path.isdir(entry): t = 'd'\n",
" elif os.path.islink(entry): t = 'l'\n",
" else: t = '-'\n",
" print '%c %s' % (t, entry)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Exceptions"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"No such key 'abc'\n",
"Do this regardless of exceptions/returns/breaks\n"
]
}
],
"source": [
"try:\n",
" dict1['abc']\n",
"except KeyError as e:\n",
" print \"No such key %r\" % (e.args[0],)\n",
"finally:\n",
" print \"Do this regardless of exceptions/returns/breaks\""
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false,
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hi\n",
"there\n"
]
}
],
"source": [
"try:\n",
" print \"Hi\"\n",
"except: pass\n",
"else:\n",
" print \"there\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"celltoolbar": "Slideshow",
"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.11"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment