From 7749d69cb3f2b9733b28a648f664ca8505c7621c Mon Sep 17 00:00:00 2001 From: rasbt Date: Thu, 11 Jan 2018 23:00:18 -0500 Subject: [PATCH 1/8] fixing some language typos --- tutorials/multiprocessing_intro.ipynb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tutorials/multiprocessing_intro.ipynb b/tutorials/multiprocessing_intro.ipynb index 126f8c2..b3566c9 100644 --- a/tutorials/multiprocessing_intro.ipynb +++ b/tutorials/multiprocessing_intro.ipynb @@ -348,7 +348,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "**A simpler way to to maintain an ordered list of results is to use the `Pool.apply` and `Pool.map` functions which we will discuss in the next section.**" + "**A simpler way to maintain an ordered list of results is to use the `Pool.apply` and `Pool.map` functions which we will discuss in the next section.**" ] }, { @@ -379,7 +379,7 @@ "source": [ "Another and more convenient approach for simple parallel processing tasks is provided by the `Pool` class. \n", "\n", - "There are four methods that are particularly interesing:\n", + "There are four methods that are particularly interesting:\n", "\n", " - Pool.apply\n", " \n", @@ -451,7 +451,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The `Pool.map` and `Pool.apply` will lock the main program until all a process is finished, which is quite useful if we want to obtain resuls in a particular order for certain applications. \n", + "The `Pool.map` and `Pool.apply` will lock the main program until all processes are finished, which is quite useful if we want to obtain results in a particular order for certain applications. \n", "In contrast, the `async` variants will submit all processes at once and retrieve the results as soon as they are finished. \n", "One more difference is that we need to use the `get` method after the `apply_async()` call in order to obtain the `return` values of the finished processes." ] @@ -759,7 +759,7 @@ "source": [ "Below, we will set up benchmarking functions for our serial and multiprocessing approach that we can pass to our `timeit` benchmark function. \n", "We will be using the `Pool.apply_async` function to take advantage of firing up processes simultaneously: Here, we don't care about the order in which the results for the different window widths are computed, we just need to associate each result with the input window width. \n", - "Thus we add a little tweak to our Parzen-density-estimation function by returning a tuple of 2 values: window width and the estimated density, which will allow us to to sort our list of results later." + "Thus we add a little tweak to our Parzen-density-estimation function by returning a tuple of 2 values: window width and the estimated density, which will allow us to sort our list of results later." ] }, { @@ -1097,7 +1097,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.1" + "version": "3.6.3" } }, "nbformat": 4, From 5da40c30c01aeb5a45aeffcbe3446dd51ce42116 Mon Sep 17 00:00:00 2001 From: rasbt Date: Wed, 18 Apr 2018 09:47:16 -0400 Subject: [PATCH 2/8] fix cursor use --- tutorials/sqlite3_howto/README.md | 62 ++++++++++--------- tutorials/sqlite3_howto/code/print_db_info.py | 43 +++++++------ 2 files changed, 57 insertions(+), 48 deletions(-) diff --git a/tutorials/sqlite3_howto/README.md b/tutorials/sqlite3_howto/README.md index e5cccec..02e3e3c 100644 --- a/tutorials/sqlite3_howto/README.md +++ b/tutorials/sqlite3_howto/README.md @@ -682,53 +682,58 @@ convenient script to print a nice overview of SQLite database tables: import sqlite3 - + + def connect(sqlite_file): """ Make connection to an SQLite database file """ conn = sqlite3.connect(sqlite_file) c = conn.cursor() return conn, c - + + def close(conn): """ Commit changes and close connection to the database """ # conn.commit() conn.close() - + + def total_rows(cursor, table_name, print_out=False): """ Returns the total number of rows in the database """ - c.execute('SELECT COUNT(*) FROM {}'.format(table_name)) - count = c.fetchall() + cursor.execute('SELECT COUNT(*) FROM {}'.format(table_name)) + count = cursor.fetchall() if print_out: print('\nTotal rows: {}'.format(count[0][0])) return count[0][0] - + + def table_col_info(cursor, table_name, print_out=False): - """ - Returns a list of tuples with column informations: - (id, name, type, notnull, default_value, primary_key) - + """ Returns a list of tuples with column informations: + (id, name, type, notnull, default_value, primary_key) """ - c.execute('PRAGMA TABLE_INFO({})'.format(table_name)) - info = c.fetchall() - + cursor.execute('PRAGMA TABLE_INFO({})'.format(table_name)) + info = cursor.fetchall() + if print_out: print("\nColumn Info:\nID, Name, Type, NotNull, DefaultVal, PrimaryKey") for col in info: print(col) return info - + + def values_in_col(cursor, table_name, print_out=True): - """ Returns a dictionary with columns as keys and the number of not-null - entries as associated values. + """ Returns a dictionary with columns as keys + and the number of not-null entries as associated values. """ - c.execute('PRAGMA TABLE_INFO({})'.format(table_name)) - info = c.fetchall() + cursor.execute('PRAGMA TABLE_INFO({})'.format(table_name)) + info = cursor.fetchall() col_dict = dict() for col in info: col_dict[col[1]] = 0 for col in col_dict: - c.execute('SELECT ({0}) FROM {1} WHERE {0} IS NOT NULL'.format(col, table_name)) - # In my case this approach resulted in a better performance than using COUNT + c.execute('SELECT ({0}) FROM {1} ' + 'WHERE {0} IS NOT NULL'.format(col, table_name)) + # In my case this approach resulted in a + # better performance than using COUNT number_rows = len(c.fetchall()) col_dict[col] = number_rows if print_out: @@ -736,23 +741,22 @@ convenient script to print a nice overview of SQLite database tables: for i in col_dict.items(): print('{}: {}'.format(i[0], i[1])) return col_dict - - + + if __name__ == '__main__': - + sqlite_file = 'my_first_db.sqlite' table_name = 'my_table_3' - + conn, c = connect(sqlite_file) total_rows(c, table_name, print_out=True) table_col_info(c, table_name, print_out=True) - values_in_col(c, table_name, print_out=True) # slow on large data bases - + # next line might be slow on large databases + values_in_col(c, table_name, print_out=True) + close(conn) - -Download the script: [print_db_info.py](https://raw.github.com/rasbt/python_sq -lite_code/master/code/print_db_info.py) +Download the script: [print_db_info.py](code/print_db_info.py) ![8_sqlite3_print_db_info_1.png](../../Images/8_sqlite3_print_db_info_1.png) diff --git a/tutorials/sqlite3_howto/code/print_db_info.py b/tutorials/sqlite3_howto/code/print_db_info.py index 22b72a8..285a635 100644 --- a/tutorials/sqlite3_howto/code/print_db_info.py +++ b/tutorials/sqlite3_howto/code/print_db_info.py @@ -22,52 +22,57 @@ import sqlite3 + def connect(sqlite_file): """ Make connection to an SQLite database file """ conn = sqlite3.connect(sqlite_file) c = conn.cursor() return conn, c + def close(conn): """ Commit changes and close connection to the database """ - #conn.commit() + # conn.commit() conn.close() + def total_rows(cursor, table_name, print_out=False): """ Returns the total number of rows in the database """ - c.execute('SELECT COUNT(*) FROM {}'.format(table_name)) - count = c.fetchall() + cursor.execute('SELECT COUNT(*) FROM {}'.format(table_name)) + count = cursor.fetchall() if print_out: print('\nTotal rows: {}'.format(count[0][0])) return count[0][0] + def table_col_info(cursor, table_name, print_out=False): - """ - Returns a list of tuples with column informations: - (id, name, type, notnull, default_value, primary_key) - + """ Returns a list of tuples with column informations: + (id, name, type, notnull, default_value, primary_key) """ - c.execute('PRAGMA TABLE_INFO({})'.format(table_name)) - info = c.fetchall() - + cursor.execute('PRAGMA TABLE_INFO({})'.format(table_name)) + info = cursor.fetchall() + if print_out: print("\nColumn Info:\nID, Name, Type, NotNull, DefaultVal, PrimaryKey") for col in info: print(col) return info + def values_in_col(cursor, table_name, print_out=True): - """ Returns a dictionary with columns as keys and the number of not-null - entries as associated values. + """ Returns a dictionary with columns as keys + and the number of not-null entries as associated values. """ - c.execute('PRAGMA TABLE_INFO({})'.format(table_name)) - info = c.fetchall() + cursor.execute('PRAGMA TABLE_INFO({})'.format(table_name)) + info = cursor.fetchall() col_dict = dict() for col in info: col_dict[col[1]] = 0 for col in col_dict: - c.execute('SELECT ({0}) FROM {1} WHERE {0} IS NOT NULL'.format(col, table_name)) - # In my case this approach resulted in a better performance than using COUNT + c.execute('SELECT ({0}) FROM {1} ' + 'WHERE {0} IS NOT NULL'.format(col, table_name)) + # In my case this approach resulted in a + # better performance than using COUNT number_rows = len(c.fetchall()) col_dict[col] = number_rows if print_out: @@ -85,7 +90,7 @@ def values_in_col(cursor, table_name, print_out=True): conn, c = connect(sqlite_file) total_rows(c, table_name, print_out=True) table_col_info(c, table_name, print_out=True) - values_in_col(c, table_name, print_out=True) # slow on large data bases - - close(conn) + # next line might be slow on large databases + values_in_col(c, table_name, print_out=True) + close(conn) From a908a343afe1bd0eff420b15d93706dde9c123ea Mon Sep 17 00:00:00 2001 From: rasbt Date: Wed, 16 May 2018 01:06:58 -0400 Subject: [PATCH 3/8] get principal eigvec --- useful_scripts/principal_eigenvector.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 useful_scripts/principal_eigenvector.py diff --git a/useful_scripts/principal_eigenvector.py b/useful_scripts/principal_eigenvector.py new file mode 100644 index 0000000..913cf62 --- /dev/null +++ b/useful_scripts/principal_eigenvector.py @@ -0,0 +1,20 @@ +# Select a principal eigenvector via NumPy +# to be used as a template (copy & paste) script + +import numpy as np + +# set A to be your matrix +A = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + + +eig_vals, eig_vecs = np.linalg.eig(A) +idx = np.absolute(eig_vals).argsort()[::-1] # decreasing order +sorted_eig_vals = eig_vals[idx] +sorted_eig_vecs = eig_vecs[:, idx] + +principal_eig_vec = sorted_eig_vecs[:, 0] # eigvec with largest eigval + +normalized_pr_eig_vec = np.real(principal_eig_vec / np.sum(principal_eig_vec)) +print(normalized_pr_eig_vec) # eigvec that sums up to one From 82376a9b8b8776a3586c16246853ef88606123c1 Mon Sep 17 00:00:00 2001 From: rasbt Date: Thu, 7 Jun 2018 23:43:02 -0400 Subject: [PATCH 4/8] replace broken absolute links with relative links --- tutorials/sqlite3_howto/README.md | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/tutorials/sqlite3_howto/README.md b/tutorials/sqlite3_howto/README.md index 02e3e3c..ea2a357 100644 --- a/tutorials/sqlite3_howto/README.md +++ b/tutorials/sqlite3_howto/README.md @@ -123,7 +123,7 @@ there is more information about PRIMARY KEYs further down in this section). conn.close() -Download the script: [create_new_db.py](https://raw.github.com/rasbt/python_reference/master/tutorials/code/create_new_db.py) +Download the script: [create_new_db.py](https://github.com/rasbt/python_reference/blob/master/tutorials/sqlite3_howto/code/create_new_db.py) * * * @@ -207,7 +207,7 @@ Let's have a look at some code: conn.close() -Download the script: [add_new_column.py](https://raw.github.com/rasbt/python_reference/master/tutorials/code/add_new_column.py) +Download the script: [add_new_column.py](https://github.com/rasbt/python_reference/blob/master/tutorials/sqlite3_howto/code/add_new_column.py) @@ -270,8 +270,7 @@ But let us first have a look at the example code: conn.close() -Download the script: [update_or_insert_records.py](https://raw.github.com/rasb -t/python_sqlite_code/master/code/update_or_insert_records.py) +Download the script: [update_or_insert_records.py](code/update_or_insert_records.py) ![3_sqlite3_insert_update.png](../../Images/3_sqlite3_insert_update.png) @@ -335,8 +334,7 @@ drop the index, which is also shown in the code below. conn.close() -Download the script: [create_unique_index.py](https://raw.github.com/rasbt/pyt -hon_sqlite_code/master/code/create_unique_index.py) +Download the script: [create_unique_index.py](code/create_unique_index.py) ![4_sqlite3_unique_index.png](../../Images/4_sqlite3_unique_index.png) @@ -401,8 +399,7 @@ row entries for all or some columns if they match certain criteria. conn.close() -Download the script: [selecting_entries.py](https://raw.github.com/rasbt/pytho -n_sqlite_code/master/code/selecting_entries.py) +Download the script: [selecting_entries.py](code/selecting_entries.py) ![4_sqlite3_unique_index.png](../../Images/4_sqlite3_unique_index.png) @@ -542,8 +539,7 @@ that have been added xxx days ago. conn.close() -Download the script: [date_time_ops.py](https://raw.github.com/rasbt/python_sq -lite_code/master/code/date_time_ops.py) +Download the script: [date_time_ops.py](code/date_time_ops.py) @@ -645,8 +641,7 @@ column names): conn.close() -Download the script: [get_columnnames.py](https://raw.github.com/rasbt/python_ -sqlite_code/master/code/get_columnnames.py) +Download the script: [get_columnnames.py](code/get_columnnames.py) ![7_sqlite3_get_colnames_1.png](../../Images/7_sqlite3_get_colnames_1.png) From 764e1adf4a82387234727fe9b9e37ebcffe13f16 Mon Sep 17 00:00:00 2001 From: lacanlale Date: Sat, 9 Jun 2018 09:07:32 -0700 Subject: [PATCH 5/8] typo and grammar fixes to not_so_obv nb --- tutorials/not_so_obvious_python_stuff.ipynb | 1221 +++++++------------ 1 file changed, 434 insertions(+), 787 deletions(-) diff --git a/tutorials/not_so_obvious_python_stuff.ipynb b/tutorials/not_so_obvious_python_stuff.ipynb index 15569ba..2e733ed 100644 --- a/tutorials/not_so_obvious_python_stuff.ipynb +++ b/tutorials/not_so_obvious_python_stuff.ipynb @@ -14,9 +14,7 @@ { "cell_type": "code", "execution_count": 1, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "%load_ext watermark" @@ -25,18 +23,16 @@ { "cell_type": "code", "execution_count": 2, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "Last updated: 16/07/2014 \n", + "last updated: 2018-06-09 \n", "\n", - "CPython 3.4.1\n", - "IPython 2.0.0\n" + "CPython 3.6.4\n", + "IPython 6.2.1\n" ] } ], @@ -57,7 +53,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "
\n", "
" ] }, @@ -186,10 +181,8 @@ }, { "cell_type": "code", - "execution_count": 2, - "metadata": { - "collapsed": false - }, + "execution_count": 3, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -230,10 +223,8 @@ }, { "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, + "execution_count": 4, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -295,25 +286,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Python `list`s are mutable objects as we all know. So, if we are using the `+=` operator on `list`s, we extend the `list` by directly modifying the object directly. \n", + "Python `list`s are mutable objects as we all know. So, if we are using the `+=` operator on `list`s, we extend the `list` by directly modifying the object. \n", "\n", - "However, if we use the assigment via `my_list = my_list + ...`, we create a new list object, which can be demonstrated by the following code:" + "However, if we use the assignment via `my_list = my_list + ...`, we create a new list object, which can be demonstrated by the following code:" ] }, { "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, + "execution_count": 5, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "ID: 4366496544\n", - "ID (+=): 4366496544\n", - "ID (list = list + ...): 4366495472\n" + "ID: 4486856904\n", + "ID (+=): 4486856904\n", + "ID (list = list + ...): 4486959368\n" ] } ], @@ -338,22 +327,20 @@ { "cell_type": "code", "execution_count": 6, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[] \n", - "ID (initial): 140704077653128 \n", + "ID (initial): 4486857224 \n", "\n", "[1] \n", - "ID (append): 140704077653128 \n", + "ID (append): 4486857224 \n", "\n", "[1, 2] \n", - "ID (extend): 140704077653128\n" + "ID (extend): 4486857224\n" ] } ], @@ -390,7 +377,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "\"It often comes as a big surprise for programmers to find (sometimes by way of a hard-to-reproduce bug) that, unlike any other time value, midnight (i.e. `datetime.time(0,0,0)`) is False. A long discussion on the python-ideas mailing list shows that, while surprising, that behavior is desirable—at least in some quarters.\" \n", + "\"It often comes as a big surprise for programmers to find (sometimes by way of a hard-to-reproduce bug) that, unlike any other time value, midnight (i.e. `datetime.time(0,0,0)`) is False. A long discussion on the python-ideas mailing list shows that, while surprising, that behavior is desirable — at least in some quarters.\" \n", "\n", "(Original source: [http://lwn.net/SubscriberLink/590299/bf73fe823974acea/](http://lwn.net/SubscriberLink/590299/bf73fe823974acea/))" ] @@ -404,16 +391,14 @@ }, { "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, + "execution_count": 7, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "\"datetime.time(0,0,0)\" (Midnight) -> False\n", + "\"datetime.time(0,0,0)\" (Midnight) -> True\n", "\"datetime.time(1,0,0)\" (1 am) -> True\n" ] } @@ -460,10 +445,8 @@ }, { "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, + "execution_count": 8, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -489,7 +472,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "(*I received a comment that this is in fact a CPython artefact and **must not necessarily be true** in all implementations of Python!*)\n", + "(*I received a comment that this is in fact a CPython artifact and **must not necessarily be true** in all implementations of Python!*)\n", "\n", "So the take home message is: always use \"==\" for equality, \"is\" for identity!\n", "\n", @@ -505,10 +488,8 @@ }, { "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, + "execution_count": 9, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -537,10 +518,8 @@ }, { "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, + "execution_count": 10, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -567,10 +546,8 @@ }, { "cell_type": "code", - "execution_count": 12, - "metadata": { - "collapsed": false - }, + "execution_count": 11, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -621,23 +598,25 @@ }, { "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, + "execution_count": 12, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "IDs:\n", - "list1: 4346366472\n", - "list2: 4346366472\n", - "list3: 4346366408\n", - "list4: 4346366536\n", + "list1: 4486860424\n", + "list2: 4486860424\n", + "list3: 4486818632\n", + "list4: 4486818568\n", + "\n", + "list1: [3, 2]\n", "\n", "list1: [3, 2]\n", - "list1: [3, 2]\n" + "list2: [3, 2]\n", + "list3: [4, 2]\n", + "list4: [1, 4]\n" ] } ], @@ -655,7 +634,10 @@ "\n", "list3[0] = 4\n", "list4[1] = 4\n", - "print('list1:', list1)" + "print('\\nlist1:', list1)\n", + "print('list2:', list2)\n", + "print('list3:', list3)\n", + "print('list4:', list4)" ] }, { @@ -674,22 +656,23 @@ }, { "cell_type": "code", - "execution_count": 25, - "metadata": { - "collapsed": false - }, + "execution_count": 13, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "IDs:\n", - "list1: 4377956296\n", - "list2: 4377961752\n", - "list3: 4377954928\n", + "list1: 4486818824\n", + "list2: 4486886024\n", + "list3: 4486888200\n", + "\n", + "list1: [[3], [2]]\n", "\n", "list1: [[3], [2]]\n", - "list1: [[3], [2]]\n" + "list2: [[3], [2]]\n", + "list3: [[5], [2]]\n" ] } ], @@ -707,7 +690,9 @@ "print('list1:', list1)\n", "\n", "list3[0][0] = 5\n", - "print('list1:', list1)" + "print('\\nlist1:', list1)\n", + "print('list2:', list2)\n", + "print('list3:', list3)" ] }, { @@ -751,10 +736,8 @@ }, { "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, + "execution_count": 14, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -803,10 +786,8 @@ }, { "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, + "execution_count": 15, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -838,17 +819,15 @@ }, { "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, + "execution_count": 16, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "1397764090.456688\n", - "1397764090.456688\n" + "1528560045.3962939\n", + "1528560045.3962939\n" ] } ], @@ -891,15 +870,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Be aware of what is happening when combining \"`in`\" checks with generators, since they won't evaluate from the beginning once a position is \"consumed\"." + "Be aware of what is happening when combining `in` checks with generators, since they won't evaluate from the beginning once a position is \"consumed\"." ] }, { "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, + "execution_count": 17, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -922,15 +899,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Although this defeats the purpose of an generator (in most cases), we can convert a generator into a list to circumvent the problem. " + "Although this defeats the purpose of a generator (in most cases), we can convert a generator into a list to circumvent the problem. " ] }, { "cell_type": "code", - "execution_count": 27, - "metadata": { - "collapsed": false - }, + "execution_count": 18, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -986,10 +961,8 @@ }, { "cell_type": "code", - "execution_count": 28, - "metadata": { - "collapsed": false - }, + "execution_count": 19, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1036,19 +1009,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Remember the section about the [\"consuming generators\"](consuming_generators)? This example is somewhat related, but the result might still come unexpected. \n", + "Remember the section about the [consuming generators](#consuming_generator)? This example is somewhat related, but the result might still come as unexpected. \n", "\n", "(Original source: [http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html](http://openhome.cc/eGossip/Blog/UnderstandingLambdaClosure3.html))\n", "\n", - "In the first example below, we call a `lambda` function in a list comprehension, and the value `i` will be dereferenced every time we call `lambda` within the scope of the list comprehension. Since the list comprehension has already been constructed and evaluated when we for-loop through the list, the closure-variable will be set to the last value 4." + "In the first example below, we call a `lambda` function in a list comprehension, and the value `i` will be dereferenced every time we call `lambda` within the scope. Since the list comprehension has already been constructed and evaluated when we `for-loop` through the list, the closure-variable will be set to the last value 4." ] }, { "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, + "execution_count": 20, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1077,10 +1048,8 @@ }, { "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, + "execution_count": 21, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1109,10 +1078,8 @@ }, { "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, + "execution_count": 22, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1173,10 +1140,8 @@ }, { "cell_type": "code", - "execution_count": 31, - "metadata": { - "collapsed": false - }, + "execution_count": 23, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1189,10 +1154,13 @@ ], "source": [ "x = 0\n", + "\n", + "\n", "def in_func():\n", " x = 1\n", " print('in_func:', x)\n", - " \n", + "\n", + "\n", "in_func()\n", "print('global:', x)" ] @@ -1206,10 +1174,8 @@ }, { "cell_type": "code", - "execution_count": 34, - "metadata": { - "collapsed": false - }, + "execution_count": 24, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1222,11 +1188,14 @@ ], "source": [ "x = 0\n", + "\n", + "\n", "def in_func():\n", " global x\n", " x = 1\n", " print('in_func:', x)\n", - " \n", + "\n", + "\n", "in_func()\n", "print('global:', x)" ] @@ -1242,10 +1211,8 @@ }, { "cell_type": "code", - "execution_count": 36, - "metadata": { - "collapsed": false - }, + "execution_count": 25, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1259,13 +1226,16 @@ ], "source": [ "def outer():\n", - " x = 1\n", - " print('outer before:', x)\n", - " def inner():\n", - " x = 2\n", - " print(\"inner:\", x)\n", - " inner()\n", - " print(\"outer after:\", x)\n", + " x = 1\n", + " print('outer before:', x)\n", + "\n", + " def inner():\n", + " x = 2\n", + " print(\"inner:\", x)\n", + " inner()\n", + " print(\"outer after:\", x)\n", + "\n", + "\n", "outer()" ] }, @@ -1278,10 +1248,8 @@ }, { "cell_type": "code", - "execution_count": 35, - "metadata": { - "collapsed": false - }, + "execution_count": 26, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1295,14 +1263,17 @@ ], "source": [ "def outer():\n", - " x = 1\n", - " print('outer before:', x)\n", - " def inner():\n", - " nonlocal x\n", - " x = 2\n", - " print(\"inner:\", x)\n", - " inner()\n", - " print(\"outer after:\", x)\n", + " x = 1\n", + " print('outer before:', x)\n", + "\n", + " def inner():\n", + " nonlocal x\n", + " x = 2\n", + " print(\"inner:\", x)\n", + " inner()\n", + " print(\"outer after:\", x)\n", + "\n", + "\n", "outer()" ] }, @@ -1340,18 +1311,17 @@ }, { "cell_type": "code", - "execution_count": 41, - "metadata": { - "collapsed": false - }, + "execution_count": 27, + "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'tuple' object does not support item assignment", "output_type": "error", "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mtup\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mtup\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mtup\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mtup\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } @@ -1365,15 +1335,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### But what if we put a mutable object into the immutable tuple? Well, modification works, but we **also** get a `TypeError` at the same time." + "### But what if we put a mutable object into the immutable tuple? Well, modification works, but we **also** get a `TypeError` at the same time." ] }, { "cell_type": "code", - "execution_count": 42, - "metadata": { - "collapsed": false - }, + "execution_count": 28, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1387,8 +1355,9 @@ "evalue": "'tuple' object does not support item assignment", "output_type": "error", "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mtup\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m[\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[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'tup before: '\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtup\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mtup\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mtup\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m[\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[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'tup before: '\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtup\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mtup\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } @@ -1401,19 +1370,9 @@ }, { "cell_type": "code", - "execution_count": 43, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "tup after: ([1],)\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "print('tup after: ', tup)" ] @@ -1429,10 +1388,8 @@ }, { "cell_type": "code", - "execution_count": 44, - "metadata": { - "collapsed": false - }, + "execution_count": 29, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1452,10 +1409,8 @@ }, { "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, + "execution_count": 30, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1488,15 +1443,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### One more note about the `immutable` status of tuples. Tuples are famous for being immutable. However, how comes that this code works?" + "### One more note about the `immutable` status of tuples. Tuples are famous for being immutable. However, how comes that this code works?" ] }, { "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, + "execution_count": 31, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1517,23 +1470,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "What happens \"behind\" the curtains is that the tuple is not modified, but every time a new object is generated, which will inherit the old \"name tag\":" + "What happens \"behind\" the curtains is that the tuple is not modified, but a new object is generated every time, which will inherit the old \"name tag\":" ] }, { "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, + "execution_count": 32, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "4337381840\n", - "4357415496\n", - "4357289952\n" + "4486707912\n", + "4485211784\n", + "4486955152\n" ] } ], @@ -1580,14 +1531,13 @@ }, { "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, + "execution_count": 33, + "metadata": {}, "outputs": [], "source": [ "import timeit\n", "\n", + "\n", "def plainlist(n=100000):\n", " my_list = []\n", " for i in range(n):\n", @@ -1595,14 +1545,17 @@ " my_list.append(i)\n", " return my_list\n", "\n", + "\n", "def listcompr(n=100000):\n", " my_list = [i for i in range(n) if i % 5 == 0]\n", " return my_list\n", "\n", + "\n", "def generator(n=100000):\n", " my_gen = (i for i in range(n) if i % 5 == 0)\n", " return my_gen\n", "\n", + "\n", "def generator_yield(n=100000):\n", " for i in range(n):\n", " if i % 5 == 0:\n", @@ -1613,27 +1566,25 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### To be fair to the list, let us exhaust the generators:" + "### To be fair to the list, let us exhaust the generators:" ] }, { "cell_type": "code", - "execution_count": 13, - "metadata": { - "collapsed": false - }, + "execution_count": 34, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "plain_list: 10 loops, best of 3: 22.4 ms per loop\n", + "plain_list: 10.8 ms ± 793 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n", "\n", - "listcompr: 10 loops, best of 3: 20.8 ms per loop\n", + "listcompr: 10 ms ± 830 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n", "\n", - "generator: 10 loops, best of 3: 22 ms per loop\n", + "generator: 11.4 ms ± 1 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n", "\n", - "generator_yield: 10 loops, best of 3: 21.9 ms per loop\n" + "generator_yield: 12.3 ms ± 1.82 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" ] } ], @@ -1642,25 +1593,29 @@ " for i in plain_list():\n", " pass\n", "\n", + "\n", "def test_listcompr(listcompr):\n", " for i in listcompr():\n", " pass\n", "\n", + "\n", "def test_generator(generator):\n", " for i in generator():\n", " pass\n", "\n", + "\n", "def test_generator_yield(generator_yield):\n", " for i in generator_yield():\n", " pass\n", "\n", - "print('plain_list: ', end = '')\n", + "\n", + "print('plain_list: ', end='')\n", "%timeit test_plainlist(plainlist)\n", - "print('\\nlistcompr: ', end = '')\n", + "print('\\nlistcompr: ', end='')\n", "%timeit test_listcompr(listcompr)\n", - "print('\\ngenerator: ', end = '')\n", + "print('\\ngenerator: ', end='')\n", "%timeit test_generator(generator)\n", - "print('\\ngenerator_yield: ', end = '')\n", + "print('\\ngenerator_yield: ', end='')\n", "%timeit test_generator_yield(generator_yield)" ] }, @@ -1693,21 +1648,19 @@ "metadata": {}, "source": [ "Who has not stumbled across this quote \"we are all consenting adults here\" in the Python community, yet? Unlike in other languages like C++ (sorry, there are many more, but that's one I am most familiar with), we can't really protect class methods from being used outside the class (i.e., by the API user). \n", - "All we can do is to indicate methods as private to make clear that they are better not used outside the class, but it is really up to the class user, since \"we are all consenting adults here\"! \n", + "All we can do is indicate methods as private to make clear that they are not to be used outside the class, but it really is up to the class user, since \"we are all consenting adults here\"! \n", "So, when we want to mark a class method as private, we can put a single underscore in front of it. \n", "If we additionally want to avoid name clashes with other classes that might use the same method names, we can prefix the name with a double-underscore to invoke the name mangling.\n", "\n", - "This doesn't prevent the class user to access this class member though, but he has to know the trick and also knows that it his own risk...\n", + "This doesn't prevent the class user to access this class member though, but they have to know the trick and also know that it is at their own risk...\n", "\n", "Let the following example illustrate what I mean:" ] }, { "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, + "execution_count": 35, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1723,11 +1676,14 @@ "class my_class():\n", " def public_method(self):\n", " print('Hello public world!')\n", + "\n", " def __private_method(self):\n", " print('Hello private world!')\n", + "\n", " def call_private_method_in_class(self):\n", " self.__private_method()\n", - " \n", + "\n", + "\n", "my_instance = my_class()\n", "\n", "my_instance.public_method()\n", @@ -1768,10 +1724,8 @@ }, { "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, + "execution_count": 36, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1791,10 +1745,8 @@ }, { "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, + "execution_count": 37, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1818,15 +1770,13 @@ "source": [ "
\n", "
\n", - "**The solution** is that we are iterating through the list index by index, and if we remove one of the items in-between, we inevitably mess around with the indexing, look at the following example, and it will become clear:" + "**The solution** is that we are iterating through the list index by index, and if we remove one of the items in-between, we inevitably mess around with the indexing. Look at the following example and it will become clear:" ] }, { "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, + "execution_count": 38, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1880,10 +1830,8 @@ }, { "cell_type": "code", - "execution_count": 14, - "metadata": { - "collapsed": false - }, + "execution_count": 39, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -1939,23 +1887,22 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "As we have all encountered it 1 (x10000) time(s) in our live, the infamous `IndexError`:" + "As we have all encountered it 1 (x10000) time(s) in our lives, the infamous `IndexError`:" ] }, { "cell_type": "code", - "execution_count": 15, - "metadata": { - "collapsed": false - }, + "execution_count": 40, + "metadata": {}, "outputs": [ { "ename": "IndexError", "evalue": "list index out of range", "output_type": "error", "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mmy_list\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m4\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmy_list\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mmy_list\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m4\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmy_list\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mIndexError\u001b[0m: list index out of range" ] } @@ -1969,24 +1916,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "But suprisingly, it is not raised when we are doing list slicing, which can be a really pain for debugging:" + "But suprisingly, it is not raised when we are doing list slicing, which can be a real pain when debugging:" ] }, { "cell_type": "code", - "execution_count": 16, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[]\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "my_list = [1, 2, 3, 4, 5]\n", "print(my_list[5:])" @@ -2025,23 +1962,14 @@ }, { "cell_type": "code", - "execution_count": 37, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "global\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "def my_func():\n", " print(var)\n", "\n", + "\n", "var = 'global'\n", "my_func()" ] @@ -2055,23 +1983,14 @@ }, { "cell_type": "code", - "execution_count": 38, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "global\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "def my_func():\n", " var = 'locally changed'\n", "\n", + "\n", "var = 'global'\n", "my_func()\n", "print(var)" @@ -2086,28 +2005,15 @@ }, { "cell_type": "code", - "execution_count": 40, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "ename": "UnboundLocalError", - "evalue": "local variable 'var' referenced before assignment", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mvar\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'global'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0mmy_func\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\u001b[0m in \u001b[0;36mmy_func\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmy_func\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----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvar\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# want to access global variable\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mvar\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'locally changed'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mvar\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'global'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mUnboundLocalError\u001b[0m: local variable 'var' referenced before assignment" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "def my_func():\n", - " print(var) # want to access global variable\n", - " var = 'locally changed' # but Python thinks we forgot to define the local variable!\n", - " \n", + " print(var) # want to access global variable\n", + " var = 'locally changed' # but Python thinks we forgot to define the local variable!\n", + "\n", + "\n", "var = 'global'\n", "my_func()" ] @@ -2121,25 +2027,15 @@ }, { "cell_type": "code", - "execution_count": 43, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "global\n", - "locally changed\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "def my_func():\n", " global var\n", - " print(var) # want to access global variable\n", - " var = 'locally changed' # changes the gobal variable\n", + " print(var) # want to access global variable\n", + " var = 'locally changed' # changes the gobal variable\n", + "\n", "\n", "var = 'global'\n", "\n", @@ -2175,25 +2071,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Let's assume a scenario where we want to duplicate sub`list`s of values stored in another list. If we want to create independent sub`list` object, using the arithmetic multiplication operator could lead to rather unexpected (or undesired) results:" + "Let's assume a scenario where we want to duplicate sub`list`s of values stored in another list. If we want to create an independent sub`list` object, using the arithmetic multiplication operator could lead to rather unexpected (or undesired) results:" ] }, { "cell_type": "code", - "execution_count": 24, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "initially ---> [[1, 2, 3], [1, 2, 3]]\n", - "after my_list1[1][0] = 'a' ---> [['a', 2, 3], ['a', 2, 3]]\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "my_list1 = [[1, 2, 3]] * 2\n", "\n", @@ -2215,20 +2100,9 @@ }, { "cell_type": "code", - "execution_count": 25, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "initially: ---> [[1, 2, 3], [1, 2, 3]]\n", - "after my_list2[1][0] = 'a': ---> [[1, 2, 3], ['a', 2, 3]]\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "my_list2 = [[1, 2, 3] for i in range(2)]\n", "\n", @@ -2249,22 +2123,11 @@ }, { "cell_type": "code", - "execution_count": 26, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "id my_list1: 4350764680, id my_list2: 4350766472\n", - "id my_list1: 4350764680, id my_list2: 4350766664\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ - "for a,b in zip(my_list1, my_list2):\n", + "for a, b in zip(my_list1, my_list2):\n", " print('id my_list1: {}, id my_list2: {}'.format(id(a), id(b)))" ] }, @@ -2336,11 +2199,7 @@ "- [Handling exceptions](#handling_exceptions)\n", "- [next() function and .next() method](#next_next)\n", "- [Loop variables and leaking into the global scope](#loop_leak)\n", - "- [Comparing unorderable types](#compare_unorder)\n", - "\n", - "
\n", - "
\n", - "\n" + "- [Comparing unorderable types](#compare_unorder)" ] }, { @@ -2371,9 +2230,9 @@ "metadata": {}, "source": [ "\n", - "####- Python 2: \n", + "#### Python 2: \n", "We have ASCII `str()` types, separate `unicode()`, but no `byte` type\n", - "####- Python 3: \n", + "#### Python 3: \n", "Now, we finally have Unicode (utf-8) `str`ings, and 2 byte classes: `byte` and `bytearray`s" ] }, @@ -2381,12 +2240,12 @@ "cell_type": "code", "execution_count": null, "metadata": { - "collapsed": false + "code_folding": [] }, "outputs": [], "source": [ "#############\n", - "# Python 2\n", + "# Python 2 #\n", "#############\n", "\n", ">>> type(unicode('is like a python3 str()'))\n", @@ -2454,9 +2313,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Python 2\n", @@ -2485,9 +2342,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Python 2\n", @@ -2533,9 +2388,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Python 2\n", @@ -2563,16 +2416,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "\n", - "
\n", - "
" + "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "###`xrange()` " + "### `xrange()`" ] }, { @@ -2594,23 +2445,21 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Python 2\n", - "> python -m timeit 'for i in range(1000000):' ' pass'\n", + ">>> python -m timeit 'for i in range(1000000):' ' pass'\n", "10 loops, best of 3: 66 msec per loop\n", "\n", " > python -m timeit 'for i in xrange(1000000):' ' pass'\n", "10 loops, best of 3: 27.8 msec per loop\n", "\n", "# Python 3\n", - "> python3 -m timeit 'for i in range(1000000):' ' pass'\n", + ">>> python3 -m timeit 'for i in range(1000000):' ' pass'\n", "10 loops, best of 3: 51.1 msec per loop\n", "\n", - "> python3 -m timeit 'for i in xrange(1000000):' ' pass'\n", + ">>> python3 -m timeit 'for i in xrange(1000000):' ' pass'\n", "Traceback (most recent call last):\n", " File \"/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/timeit.py\", line 292, in main\n", " x = t.timeit(number)\n", @@ -2656,9 +2505,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Python 2\n", @@ -2719,9 +2566,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Python 2\n", @@ -2742,12 +2587,8 @@ ] }, { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], + "cell_type": "markdown", + "metadata": {}, "source": [ "\n", "
\n", @@ -2774,15 +2615,13 @@ "source": [ "\n", "\n", - "Where you can use both function and method in Python 2.7.5, the `next()` function is all that remain in Python 3!" + "Where you can use both function and method in Python 2.7.5, the `next()` function is all that remains in Python 3!" ] }, { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "# Python 2\n", @@ -2831,26 +2670,14 @@ "source": [ "This goes back to a change that was made in Python 3.x and is described in [What’s New In Python 3.0](https://docs.python.org/3/whatsnew/3.0.html) as follows:\n", "\n", - "\"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.\"" + "*\"List comprehensions no longer support the syntactic form `[... for var in item1, item2, ...]`. Use `[... for var in (item1, item2, ...)]` instead. Also note that list comprehensions have different semantics: they are closer to syntactic sugar for a generator expression inside a `list()` constructor, and in particular the loop control variables are no longer leaked into the surrounding scope.\"*" ] }, { "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "This code cell was executed in Python 3.3.5\n", - "[0, 1, 2, 3, 4]\n", - "1 -> i in global\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "from platform import python_version\n", "print('This code cell was executed in Python', python_version())\n", @@ -2862,21 +2689,9 @@ }, { "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "This code cell was executed in Python 2.7.6\n", - "[0, 1, 2, 3, 4]\n", - "4 -> i in global\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "from platform import python_version\n", "print 'This code cell was executed in Python', python_version()\n", @@ -2899,7 +2714,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### Python 3.x prevents us from comparing unorderable types" + "### Python 3.x prevents us from comparing unorderable types" ] }, { @@ -2911,22 +2726,9 @@ }, { "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "This code cell was executed in Python 2.7.6\n", - "False\n", - "True\n", - "False\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "from platform import python_version\n", "print 'This code cell was executed in Python', python_version()\n", @@ -2938,29 +2740,9 @@ }, { "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "This code cell was executed in Python 3.3.5\n" - ] - }, - { - "ename": "TypeError", - "evalue": "unorderable types: list() > str()", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'This code cell was executed in Python'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpython_version\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[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;34m'foo'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;34m'foo'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;31mTypeError\u001b[0m: unorderable types: list() > str()" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "from platform import python_version\n", "print('This code cell was executed in Python', python_version())\n", @@ -3003,10 +2785,8 @@ }, { "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, + "execution_count": null, + "metadata": {}, "outputs": [], "source": [ "def foo1(x: 'insert x here', y: 'insert x^2 here'):\n", @@ -3023,10 +2803,8 @@ }, { "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, + "execution_count": null, + "metadata": {}, "outputs": [], "source": [ "def foo2(x, y) -> 'Hi!':\n", @@ -3050,38 +2828,18 @@ }, { "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello, World\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "foo1(1,2)" ] }, { "cell_type": "code", - "execution_count": 11, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Hello, World\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "foo2(1,2) " ] @@ -3100,86 +2858,57 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [ "def is_palindrome(a):\n", " \"\"\"\n", " Case-and punctuation insensitive check if a string is a palindrom.\n", - " \n", + "\n", " Keyword arguments:\n", " a (str): The string to be checked if it is a palindrome.\n", - " \n", + "\n", " Returns `True` if input string is a palindrome, else False.\n", - " \n", + "\n", " \"\"\"\n", " stripped_str = [l for l in my_str.lower() if l.isalpha()]\n", - " return stripped_str == stripped_str[::-1]\n", - " " + " return stripped_str == stripped_str[::-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "However, function annotations can be useful to indicate that work is still in progress in some cases. But they are optional and I see them very very rarely.\n", + "However, function annotations can be useful to indicate that work is still in progress in some cases. But they are optional and I see them very, very rarely.\n", "\n", "As it is stated in [PEP3107](http://legacy.python.org/dev/peps/pep-3107/#fundamentals-of-function-annotations):\n", "\n", - "1. Function annotations, both for parameters and return values, are completely optional.\n", + "1. *Function annotations, both for parameters and return values, are completely optional.*\n", "\n", - "2. Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.\n" + "2. *Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.*\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "The nice thing about function annotations is their `__annotations__` attribute, which is dictionary of all the parameters and/or the `return` value you annotated." + "The nice thing about function annotations is their `__annotations__` attribute, which is a dictionary of all the parameters and/or the `return` value you annotated." ] }, { "cell_type": "code", - "execution_count": 17, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "{'y': 'insert x^2 here', 'x': 'insert x here'}" - ] - }, - "execution_count": 17, - "metadata": {}, - "output_type": "execute_result" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "foo1.__annotations__" ] }, { "cell_type": "code", - "execution_count": 18, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "{'return': 'Hi!'}" - ] - }, - "execution_count": 18, - "metadata": {}, - "output_type": "execute_result" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "foo2.__annotations__" ] @@ -3207,7 +2936,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "
\n", "
\n", "" ] @@ -3219,6 +2947,13 @@ "## Abortive statements in `finally` blocks" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[[back to top](#sections)]" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -3228,22 +2963,9 @@ }, { "cell_type": "code", - "execution_count": 24, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "in try:\n", - "do some stuff\n", - "an error occurred\n", - "always execute finally\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "def try_finally1():\n", " try:\n", @@ -3256,7 +2978,8 @@ " print('no error occurred')\n", " finally:\n", " print('always execute finally')\n", - " \n", + "\n", + "\n", "try_finally1()" ] }, @@ -3271,21 +2994,9 @@ }, { "cell_type": "code", - "execution_count": 21, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "do some stuff in try block\n", - "do some stuff in finally block\n", - "always execute finally\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "def try_finally2():\n", " try:\n", @@ -3294,7 +3005,8 @@ " finally:\n", " print(\"do some stuff in finally block\")\n", " return \"always execute finally\"\n", - " \n", + "\n", + "\n", "print(try_finally2())" ] }, @@ -3319,7 +3031,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#Assigning types to variables as values" + "## Assigning types to variables as values" ] }, { @@ -3338,22 +3050,9 @@ }, { "cell_type": "code", - "execution_count": 1, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "data": { - "text/plain": [ - "'123'" - ] - }, - "execution_count": 1, - "metadata": {}, - "output_type": "execute_result" - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "a_var = str\n", "a_var(123)" @@ -3361,23 +3060,9 @@ }, { "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0 \n", - "1 \n", - "2.0 \n", - "3 \n", - "4 \n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "from random import choice\n", "\n", @@ -3400,7 +3085,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Only the first clause of generators is evaluated immediately" + "## Only the first clause of generators is evaluated immediately" ] }, { @@ -3420,22 +3105,9 @@ }, { "cell_type": "code", - "execution_count": 18, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "ename": "ZeroDivisionError", - "evalue": "division by zero", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mgen_fails\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "gen_fails = (i for i in 1/0)" ] @@ -3449,10 +3121,8 @@ }, { "cell_type": "code", - "execution_count": 19, - "metadata": { - "collapsed": false - }, + "execution_count": null, + "metadata": {}, "outputs": [], "source": [ "gen_succeeds = (i for i in range(5) for j in 1/0)" @@ -3460,30 +3130,9 @@ }, { "cell_type": "code", - "execution_count": 20, - "metadata": { - "collapsed": false - }, - "outputs": [ - { - "ename": "ZeroDivisionError", - "evalue": "division by zero", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'But obviously fails when we iterate ...'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mgen_succeeds\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", - "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m(.0)\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mgen_succeeds\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mj\u001b[0m \u001b[0;32min\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" - ] - }, - { - "name": "stdout", - "output_type": "stream", - "text": [ - "But obviously fails when we iterate ...\n" - ] - } - ], + "execution_count": null, + "metadata": {}, + "outputs": [], "source": [ "print('But obviously fails when we iterate ...')\n", "for i in gen_succeeds:\n", @@ -3503,7 +3152,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "##Keyword argument unpacking syntax - `*args` and `**kwargs`" + "## Keyword argument unpacking syntax - `*args` and `**kwargs`" ] }, { @@ -3517,22 +3166,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Python has a very convenient \"keyword argument unpacking syntax\" (often also referred to as \"splat\"-operators). This is particularly useful, if we want to define a function that can take a arbitrary number of input arguments." + "Python has a very convenient \"keyword argument unpacking syntax\" (often referred to as \"splat\"-operators). This is particularly useful, if we want to define a function that can take a arbitrary number of input arguments." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "#### Single-asterisk (*args)" + "### Single-asterisk (*args)" ] }, { "cell_type": "code", - "execution_count": 55, - "metadata": { - "collapsed": false - }, + "execution_count": 41, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3550,6 +3197,7 @@ " print('args contents:', args)\n", " print('1st argument:', args[0])\n", "\n", + "\n", "a_func(0, 1, 'a', 'b', 'c')" ] }, @@ -3557,22 +3205,20 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### Double-asterisk (**kwargs)" + "### Double-asterisk (**kwargs)" ] }, { "cell_type": "code", - "execution_count": 56, - "metadata": { - "collapsed": false - }, + "execution_count": 42, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "type of kwargs: \n", - "kwargs contents: {'d': 4, 'a': 1, 'c': 3, 'b': 2}\n", + "kwargs contents: {'a': 1, 'b': 2, 'c': 3, 'd': 4}\n", "value of argument a: 1\n" ] } @@ -3582,7 +3228,8 @@ " print('type of kwargs:', type(kwargs))\n", " print('kwargs contents: ', kwargs)\n", " print('value of argument a:', kwargs['a'])\n", - " \n", + "\n", + "\n", "b_func(a=1, b=2, c=3, d=4)" ] }, @@ -3590,16 +3237,14 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### (Partially) unpacking of iterables\n", + "### (Partially) unpacking of iterables\n", "Another useful application of the \"unpacking\"-operator is the unpacking of lists and other other iterables." ] }, { "cell_type": "code", - "execution_count": 57, - "metadata": { - "collapsed": false - }, + "execution_count": 43, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3654,10 +3299,8 @@ }, { "cell_type": "code", - "execution_count": 53, - "metadata": { - "collapsed": false - }, + "execution_count": 44, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3673,10 +3316,12 @@ " def __new__(clss, *args, **kwargs):\n", " print('excecuted __new__')\n", " return None\n", + "\n", " def __init__(self, an_arg):\n", " print('excecuted __init__')\n", " self.an_arg = an_arg\n", - " \n", + "\n", + "\n", "a_object = a_class(1)\n", "print('Type of a_object:', type(a_object))" ] @@ -3691,10 +3336,8 @@ }, { "cell_type": "code", - "execution_count": 54, - "metadata": { - "collapsed": false - }, + "execution_count": 45, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3713,10 +3356,12 @@ " print('excecuted __new__')\n", " inst = super(a_class, cls).__new__(cls)\n", " return inst\n", + "\n", " def __init__(self, an_arg):\n", " print('excecuted __init__')\n", " self.an_arg = an_arg\n", - " \n", + "\n", + "\n", "a_object = a_class(1)\n", "print('Type of a_object:', type(a_object))\n", "print('a_object.an_arg: ', a_object.an_arg)" @@ -3724,10 +3369,8 @@ }, { "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, + "execution_count": 46, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3750,10 +3393,8 @@ }, { "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, + "execution_count": 47, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3799,7 +3440,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "I would claim that the conditional \"else\" is every programmer's daily bread and butter. However, there is a second flavor of \"else\"-clauses in Python, which I will call \"completion else\" (for reason that will become clear later). \n", + "I would claim that the conditional `else` is every programmer's daily bread and butter. However, there is a second flavor of `else`-clauses in Python, which I will call \"completion else\" (for reason that will become clear later). \n", "But first, let us take a look at our \"traditional\" conditional else that we all are familiar with. \n" ] }, @@ -3807,15 +3448,13 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "###Conditional else:" + "### Conditional else:" ] }, { "cell_type": "code", - "execution_count": 3, - "metadata": { - "collapsed": false - }, + "execution_count": 48, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3837,10 +3476,8 @@ }, { "cell_type": "code", - "execution_count": 4, - "metadata": { - "collapsed": false - }, + "execution_count": 49, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3866,7 +3503,7 @@ "source": [ "Why am I showing those simple examples? I think they are good to highlight some of the key points: It is **either** the code under the `if` clause that is executed, **or** the code under the `else` block, but not both. \n", "If the condition of the `if` clause evaluates to `True`, the `if`-block is exectured, and if it evaluated to `False`, it is the `else` block. \n", - "\n", + "
\n", "### Completion else\n", "**In contrast** to the **either...or*** situation that we know from the conditional `else`, the completion `else` is executed if a code block finished. \n", "To show you an example, let us use `else` for error-handling:" @@ -3881,10 +3518,8 @@ }, { "cell_type": "code", - "execution_count": 5, - "metadata": { - "collapsed": false - }, + "execution_count": 50, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3906,10 +3541,8 @@ }, { "cell_type": "code", - "execution_count": 6, - "metadata": { - "collapsed": false - }, + "execution_count": 51, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3932,7 +3565,6 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "
\n", "In the code above, we can see that the code under the **`else`-clause is only executed if the `try-block` was executed without encountering an error, i.e., if the `try`-block is \"complete\".** \n", "The same rule applies to the \"completion\" `else` in while- and for-loops, which you can confirm in the following samples below." ] @@ -3946,10 +3578,8 @@ }, { "cell_type": "code", - "execution_count": 7, - "metadata": { - "collapsed": false - }, + "execution_count": 52, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -3972,10 +3602,8 @@ }, { "cell_type": "code", - "execution_count": 8, - "metadata": { - "collapsed": false - }, + "execution_count": 53, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -4004,10 +3632,8 @@ }, { "cell_type": "code", - "execution_count": 9, - "metadata": { - "collapsed": false - }, + "execution_count": 54, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -4028,10 +3654,8 @@ }, { "cell_type": "code", - "execution_count": 10, - "metadata": { - "collapsed": false - }, + "execution_count": 55, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -4090,10 +3714,8 @@ }, { "cell_type": "code", - "execution_count": 34, - "metadata": { - "collapsed": false - }, + "execution_count": 56, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -4125,20 +3747,18 @@ }, { "cell_type": "code", - "execution_count": 38, - "metadata": { - "collapsed": false - }, + "execution_count": 57, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 3 0 LOAD_CONST 1 ('Hello')\n", - " 3 STORE_FAST 0 (s)\n", + " 2 STORE_FAST 0 (s)\n", "\n", - " 4 6 LOAD_FAST 0 (s)\n", - " 9 RETURN_VALUE\n" + " 4 4 LOAD_FAST 0 (s)\n", + " 6 RETURN_VALUE\n" ] } ], @@ -4152,20 +3772,18 @@ }, { "cell_type": "code", - "execution_count": 39, - "metadata": { - "collapsed": false - }, + "execution_count": 58, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 2 0 LOAD_CONST 3 ('Hello')\n", - " 3 STORE_FAST 0 (s)\n", + " 2 STORE_FAST 0 (s)\n", "\n", - " 3 6 LOAD_FAST 0 (s)\n", - " 9 RETURN_VALUE\n" + " 3 4 LOAD_FAST 0 (s)\n", + " 6 RETURN_VALUE\n" ] } ], @@ -4178,25 +3796,23 @@ }, { "cell_type": "code", - "execution_count": 40, - "metadata": { - "collapsed": false - }, + "execution_count": 59, + "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 2 0 LOAD_CONST 1 ('Hell')\n", - " 3 STORE_FAST 0 (s)\n", + " 2 STORE_FAST 0 (s)\n", "\n", - " 3 6 LOAD_FAST 0 (s)\n", - " 9 LOAD_CONST 2 ('o')\n", - " 12 BINARY_ADD\n", - " 13 STORE_FAST 0 (s)\n", + " 3 4 LOAD_FAST 0 (s)\n", + " 6 LOAD_CONST 2 ('o')\n", + " 8 BINARY_ADD\n", + " 10 STORE_FAST 0 (s)\n", "\n", - " 4 16 LOAD_FAST 0 (s)\n", - " 19 RETURN_VALUE\n" + " 4 12 LOAD_FAST 0 (s)\n", + " 14 RETURN_VALUE\n" ] } ], @@ -4215,15 +3831,13 @@ "
\n", "It looks like that `'Hello'` and `'Hell'` + `'o'` are both evaluated and stored as `'Hello'` at compile-time, whereas the third version \n", "`s = 'Hell'` \n", - "`s = s + 'o'` seems to be not interned. Let us quickly confirm the behavior with the following code:" + "`s = s + 'o'` seems to not be interned. Let us quickly confirm the behavior with the following code:" ] }, { "cell_type": "code", - "execution_count": 42, - "metadata": { - "collapsed": false - }, + "execution_count": 60, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -4248,10 +3862,8 @@ }, { "cell_type": "code", - "execution_count": 45, - "metadata": { - "collapsed": false - }, + "execution_count": 61, + "metadata": {}, "outputs": [ { "name": "stdout", @@ -4296,6 +3908,12 @@ "cell_type": "markdown", "metadata": {}, "source": [ + "#### 06/09/2018\n", + "- pep8 spacing\n", + "- fixed minor typos\n", + "- fixed minor markdown formatting\n", + "- fixed broken page jumps\n", + "\n", "#### 07/16/2014\n", "- slight change of wording in the [lambda-closure section](#lambda_closure)\n", "\n", @@ -4322,9 +3940,7 @@ { "cell_type": "code", "execution_count": null, - "metadata": { - "collapsed": false - }, + "metadata": {}, "outputs": [], "source": [] } @@ -4345,9 +3961,40 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.5.0" + "version": "3.6.4" + }, + "latex_envs": { + "LaTeX_envs_menu_present": true, + "autoclose": false, + "autocomplete": true, + "bibliofile": "biblio.bib", + "cite_by": "apalike", + "current_citInitial": 1, + "eqLabelWithNumbers": true, + "eqNumInitial": 1, + "hotkeys": { + "equation": "Ctrl-E", + "itemize": "Ctrl-I" + }, + "labels_anchors": false, + "latex_user_defs": false, + "report_style_numbering": false, + "user_envs_cfg": false + }, + "toc": { + "base_numbering": 1, + "nav_menu": {}, + "number_sections": true, + "sideBar": true, + "skip_h1_title": false, + "title_cell": "Table of Contents", + "title_sidebar": "Contents", + "toc_cell": false, + "toc_position": {}, + "toc_section_display": true, + "toc_window_display": false } }, "nbformat": 4, - "nbformat_minor": 0 + "nbformat_minor": 1 } From 48b25bfd351cdf553a21c74cadebe1695959d50d Mon Sep 17 00:00:00 2001 From: lacanlale Date: Sat, 9 Jun 2018 11:03:08 -0700 Subject: [PATCH 6/8] minor grammar fix and datetime note --- tutorials/not_so_obvious_python_stuff.ipynb | 285 +++++++++++++++----- 1 file changed, 218 insertions(+), 67 deletions(-) diff --git a/tutorials/not_so_obvious_python_stuff.ipynb b/tutorials/not_so_obvious_python_stuff.ipynb index 2e733ed..cf683b0 100644 --- a/tutorials/not_so_obvious_python_stuff.ipynb +++ b/tutorials/not_so_obvious_python_stuff.ipynb @@ -379,6 +379,8 @@ "source": [ "\"It often comes as a big surprise for programmers to find (sometimes by way of a hard-to-reproduce bug) that, unlike any other time value, midnight (i.e. `datetime.time(0,0,0)`) is False. A long discussion on the python-ideas mailing list shows that, while surprising, that behavior is desirable — at least in some quarters.\" \n", "\n", + "Please note that Python version <= 3.4.5 evaluated the first statement `bool(datetime.time(0,0,0))` as `False`, which was regarded counter-intuitive, since \"12am\" refers to \"midnight.\"\n", + "\n", "(Original source: [http://lwn.net/SubscriberLink/590299/bf73fe823974acea/](http://lwn.net/SubscriberLink/590299/bf73fe823974acea/))" ] }, @@ -391,22 +393,25 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ + "Current python version: 3.6.4\n", "\"datetime.time(0,0,0)\" (Midnight) -> True\n", "\"datetime.time(1,0,0)\" (1 am) -> True\n" ] } ], "source": [ + "from platform import python_version\n", "import datetime\n", "\n", - "print('\"datetime.time(0,0,0)\" (Midnight) ->', bool(datetime.time(0,0,0)))\n", + "print(\"Current python version: \", python_version())\n", + "print('\"datetime.time(0,0,0)\" (Midnight) ->', bool(datetime.time(0,0,0))) # Python version <= 3.4.5 evaluates this statement to False\n", "\n", "print('\"datetime.time(1,0,0)\" (1 am) ->', bool(datetime.time(1,0,0)))" ] @@ -1652,7 +1657,7 @@ "So, when we want to mark a class method as private, we can put a single underscore in front of it. \n", "If we additionally want to avoid name clashes with other classes that might use the same method names, we can prefix the name with a double-underscore to invoke the name mangling.\n", "\n", - "This doesn't prevent the class user to access this class member though, but they have to know the trick and also know that it is at their own risk...\n", + "This doesn't prevent the class users to access this class member though, but they have to know the trick and also know that it is at their own risk...\n", "\n", "Let the following example illustrate what I mean:" ] @@ -2679,26 +2684,39 @@ "metadata": {}, "outputs": [], "source": [ - "from platform import python_version\n", - "print('This code cell was executed in Python', python_version())\n", - "\n", - "i = 1\n", - "print([i for i in range(5)])\n", - "print(i, '-> i in global')" + ">>> from platform import python_version\n", + ">>> print 'This code cell was executed in Python', python_version()\n", + "'This code cell was executed in Python 2.7.6'\n", + ">>> i = 1\n", + ">>> print [i for i in range(5)]\n", + "'[0, 1, 2, 3, 4]'\n", + ">>> print i, '-> i in global'\n", + "'4 -> i in global'" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 61, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This code cell was executed in Python 3.6.4\n", + "[0, 1, 2, 3, 4]\n", + "1 -> i in global\n" + ] + } + ], "source": [ + "%%python3\n", "from platform import python_version\n", - "print 'This code cell was executed in Python', python_version()\n", + "print('This code cell was executed in Python', python_version())\n", "\n", "i = 1\n", - "print [i for i in range(5)]\n", - "print i, '-> i in global' " + "print([i for i in range(5)])\n", + "print(i, '-> i in global')" ] }, { @@ -2726,23 +2744,53 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 101, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Couldn't find program: 'python2'\n" + ] + } + ], "source": [ - "from platform import python_version\n", - "print 'This code cell was executed in Python', python_version()\n", - "\n", - "print [1, 2] > 'foo'\n", - "print (1, 2) > 'foo'\n", - "print [1, 2] > (1, 2)" + ">>> from platform import python_version\n", + ">>> print 'This code cell was executed in Python', python_version()\n", + "'This code cell was executed in Python 2.7.6'\n", + ">>> print [1, 2] > 'foo'\n", + "'False'\n", + ">>> print (1, 2) > 'foo'\n", + "'True'\n", + ">>> print [1, 2] > (1, 2)\n", + "'False'" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 67, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This code cell was executed in Python 3.6.4\n" + ] + }, + { + "ename": "TypeError", + "evalue": "'>' not supported between instances of 'list' and 'str'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'This code cell was executed in Python'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mpython_version\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[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;34m'foo'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;34m'foo'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 6\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mTypeError\u001b[0m: '>' not supported between instances of 'list' and 'str'" + ] + } + ], "source": [ "from platform import python_version\n", "print('This code cell was executed in Python', python_version())\n", @@ -2785,7 +2833,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "metadata": {}, "outputs": [], "source": [ @@ -2803,7 +2851,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "metadata": {}, "outputs": [], "source": [ @@ -2828,18 +2876,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 17, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, World\n" + ] + } + ], "source": [ "foo1(1,2)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello, World\n" + ] + } + ], "source": [ "foo2(1,2) " ] @@ -2857,7 +2921,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 18, "metadata": {}, "outputs": [], "source": [ @@ -2897,18 +2961,40 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 19, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "{'x': 'insert x here', 'y': 'insert x^2 here'}" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "foo1.__annotations__" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 20, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "{'return': 'Hi!'}" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "foo2.__annotations__" ] @@ -2994,9 +3080,19 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 21, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "do some stuff in try block\n", + "do some stuff in finally block\n", + "always execute finally\n" + ] + } + ], "source": [ "def try_finally2():\n", " try:\n", @@ -3050,9 +3146,20 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 22, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'123'" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "a_var = str\n", "a_var(123)" @@ -3060,9 +3167,21 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 23, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.0 \n", + "1.0 \n", + "2 \n", + "3.0 \n", + "4.0 \n" + ] + } + ], "source": [ "from random import choice\n", "\n", @@ -3105,9 +3224,21 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 24, "metadata": {}, - "outputs": [], + "outputs": [ + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mgen_fails\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], "source": [ "gen_fails = (i for i in 1/0)" ] @@ -3121,7 +3252,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 25, "metadata": {}, "outputs": [], "source": [ @@ -3130,9 +3261,29 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 26, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "But obviously fails when we iterate ...\n" + ] + }, + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'But obviously fails when we iterate ...'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mgen_succeeds\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m(.0)\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mgen_succeeds\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mi\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mj\u001b[0m \u001b[0;32min\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], "source": [ "print('But obviously fails when we iterate ...')\n", "for i in gen_succeeds:\n", @@ -3178,7 +3329,7 @@ }, { "cell_type": "code", - "execution_count": 41, + "execution_count": 27, "metadata": {}, "outputs": [ { @@ -3210,7 +3361,7 @@ }, { "cell_type": "code", - "execution_count": 42, + "execution_count": 28, "metadata": {}, "outputs": [ { @@ -3243,7 +3394,7 @@ }, { "cell_type": "code", - "execution_count": 43, + "execution_count": 29, "metadata": {}, "outputs": [ { @@ -3299,7 +3450,7 @@ }, { "cell_type": "code", - "execution_count": 44, + "execution_count": 30, "metadata": {}, "outputs": [ { @@ -3336,7 +3487,7 @@ }, { "cell_type": "code", - "execution_count": 45, + "execution_count": 31, "metadata": {}, "outputs": [ { @@ -3369,7 +3520,7 @@ }, { "cell_type": "code", - "execution_count": 46, + "execution_count": 32, "metadata": {}, "outputs": [ { @@ -3393,7 +3544,7 @@ }, { "cell_type": "code", - "execution_count": 47, + "execution_count": 33, "metadata": {}, "outputs": [ { @@ -3453,7 +3604,7 @@ }, { "cell_type": "code", - "execution_count": 48, + "execution_count": 34, "metadata": {}, "outputs": [ { @@ -3476,7 +3627,7 @@ }, { "cell_type": "code", - "execution_count": 49, + "execution_count": 35, "metadata": {}, "outputs": [ { @@ -3518,7 +3669,7 @@ }, { "cell_type": "code", - "execution_count": 50, + "execution_count": 36, "metadata": {}, "outputs": [ { @@ -3541,7 +3692,7 @@ }, { "cell_type": "code", - "execution_count": 51, + "execution_count": 37, "metadata": {}, "outputs": [ { @@ -3578,7 +3729,7 @@ }, { "cell_type": "code", - "execution_count": 52, + "execution_count": 38, "metadata": {}, "outputs": [ { @@ -3602,7 +3753,7 @@ }, { "cell_type": "code", - "execution_count": 53, + "execution_count": 39, "metadata": {}, "outputs": [ { @@ -3632,7 +3783,7 @@ }, { "cell_type": "code", - "execution_count": 54, + "execution_count": 40, "metadata": {}, "outputs": [ { @@ -3654,7 +3805,7 @@ }, { "cell_type": "code", - "execution_count": 55, + "execution_count": 41, "metadata": {}, "outputs": [ { @@ -3714,7 +3865,7 @@ }, { "cell_type": "code", - "execution_count": 56, + "execution_count": 42, "metadata": {}, "outputs": [ { @@ -3747,7 +3898,7 @@ }, { "cell_type": "code", - "execution_count": 57, + "execution_count": 43, "metadata": {}, "outputs": [ { @@ -3772,7 +3923,7 @@ }, { "cell_type": "code", - "execution_count": 58, + "execution_count": 44, "metadata": {}, "outputs": [ { @@ -3796,7 +3947,7 @@ }, { "cell_type": "code", - "execution_count": 59, + "execution_count": 45, "metadata": {}, "outputs": [ { @@ -3836,7 +3987,7 @@ }, { "cell_type": "code", - "execution_count": 60, + "execution_count": 46, "metadata": {}, "outputs": [ { @@ -3862,7 +4013,7 @@ }, { "cell_type": "code", - "execution_count": 61, + "execution_count": 47, "metadata": {}, "outputs": [ { From d6ddacb2d4ed2a8ffe0c6de1a5e2743ab4e54a2e Mon Sep 17 00:00:00 2001 From: Sebastian Raschka Date: Mon, 8 Apr 2019 21:38:51 -0500 Subject: [PATCH 7/8] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c6fbbee..05de8e6 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ *This category has been moved to a separate GitHub repository [rasbt/algorithms_in_ipython_notebooks](https://github.com/rasbt/algorithms_in_ipython_notebooks)* -- Sorting Algorithms [[IPython nb](http://nbviewer.ipython.org/github/rasbt/algorithms_in_ipython_notebooks/blob/master/ipython_nbs/sorting/sorting_algorithms.ipynb?create=1)] +- Sorting Algorithms [[Collection of IPython Notebooks](https://github.com/rasbt/algorithms_in_ipython_notebooks/tree/master/ipython_nbs/sorting) - Linear regression via the least squares fit method [[IPython nb](http://nbviewer.ipython.org/github/rasbt/algorithms_in_ipython_notebooks/blob/master/ipython_nbs/statistics/linregr_least_squares_fit.ipynb?create=1)] From a066dc35fe6b324f39d406b918a9bb8469b8b420 Mon Sep 17 00:00:00 2001 From: Tim Gates Date: Mon, 27 Jun 2022 13:19:05 +1000 Subject: [PATCH 8/8] docs: Fix a few typos There are small typos in: - tutorials/installing_scientific_packages.md - tutorials/sqlite3_howto/README.md - tutorials/sqlite3_howto/code/update_or_insert_records.py - useful_scripts/conc_gzip_files.py Fixes: - Should read `existing` rather than `exisiting`. - Should read `conveniently` rather than `conviniently`. - Should read `calculate` rather than `calulate`. - Should read `accommodate` rather than `accomodate`. --- tutorials/installing_scientific_packages.md | 2 +- tutorials/sqlite3_howto/README.md | 2 +- tutorials/sqlite3_howto/code/update_or_insert_records.py | 2 +- useful_scripts/conc_gzip_files.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tutorials/installing_scientific_packages.md b/tutorials/installing_scientific_packages.md index 0439c71..918d293 100644 --- a/tutorials/installing_scientific_packages.md +++ b/tutorials/installing_scientific_packages.md @@ -278,7 +278,7 @@ print its path: Finally, we can set an `alias` in our `.bash_profile` or `.bash_rc` file to -conviniently run IPython from the console. E.g., +conveniently run IPython from the console. E.g., diff --git a/tutorials/sqlite3_howto/README.md b/tutorials/sqlite3_howto/README.md index ea2a357..c596dfc 100644 --- a/tutorials/sqlite3_howto/README.md +++ b/tutorials/sqlite3_howto/README.md @@ -586,7 +586,7 @@ syntax applies to simple dates or simple times only, too. #### Update Mar 16, 2014: -If'd we are interested to calulate the hours between two `DATETIME()` +If'd we are interested to calculate the hours between two `DATETIME()` timestamps, we can could use the handy `STRFTIME()` function like this diff --git a/tutorials/sqlite3_howto/code/update_or_insert_records.py b/tutorials/sqlite3_howto/code/update_or_insert_records.py index 37292a5..ee461ec 100644 --- a/tutorials/sqlite3_howto/code/update_or_insert_records.py +++ b/tutorials/sqlite3_howto/code/update_or_insert_records.py @@ -1,6 +1,6 @@ # Sebastian Raschka, 2014 # Update records or insert them if they don't exist. -# Note that this is a workaround to accomodate for missing +# Note that this is a workaround to accommodate for missing # SQL features in SQLite. import sqlite3 diff --git a/useful_scripts/conc_gzip_files.py b/useful_scripts/conc_gzip_files.py index da849c9..b8d9b33 100644 --- a/useful_scripts/conc_gzip_files.py +++ b/useful_scripts/conc_gzip_files.py @@ -13,7 +13,7 @@ def conc_gzip_files(in_dir, out_file, append=False, print_progress=True): Keyword arguments: in_dir (str): Path of the directory with the gzip-files out_file (str): Path to the resulting file - append (bool): If true, it appends contents to an exisiting file, + append (bool): If true, it appends contents to an existing file, else creates a new output file. print_progress (bool): prints progress bar if true.