fixed for-loop example

This commit is contained in:
Sebastian Raschka 2014-04-29 21:25:40 -04:00
parent 2587ebf9db
commit c3fc8395e2

View File

@ -947,7 +947,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"As it was briefly mentioned in the introduction, `for-loops` will create their own namespaces, which will be deleted after the for-loop has completed. Consider the following example (exectuted in Python 3.4):\n"
"In contrast to some other programming languages, `for-loops` will use the scope they exist in and leave their defined loop-variable behind.\n"
]
},
{
@ -971,32 +971,13 @@
]
}
],
"prompt_number": 15
"prompt_number": 5
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can roughly sketch the situation as follows \n",
"\n",
"*before the for-loop*: \n",
"`- global_namespace = {'a_name':object1, ...}`\n",
"\n",
"*during the for-loop*: \n",
"`- global_namespace = {'a_name':object1, ...}` \n",
"`- for-loop_namespace = {'a':object201, ...}`\n",
"\n",
"*after the for-loop*: \n",
"`- global_namespace = {'a_name':object1, ...}`\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**However, this does not apply if we defined the `for-loop` variable in the global namespace before!**"
"**This also applies if we explicitely defined the `for-loop` variable in the global namespace before!** In this case it will rebind the existing variable:"
]
},
{
@ -1021,13 +1002,13 @@
]
}
],
"prompt_number": 7
"prompt_number": 9
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In **Python 3.4**, we can use closures to prevent the for-loop variable to cut into the global namespace. Here is an example (exectuted in Python 3.4):"
"However, in **Python 3.x**, we can use closures to prevent the for-loop variable to cut into the global namespace. Here is an example (exectuted in Python 3.4):"
]
},
{
@ -1056,12 +1037,20 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"Why did I mention \"Python 3.4\"? Well, as it happens, the same code executed in Python 2.x would print:\n",
"Why did I mention \"Python 3.x\"? Well, as it happens, the same code executed in Python 2.x would print:\n",
"\n",
"<pre>\n",
"print(4, '-> i in global')\n",
"<pre>"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [],
"language": "python",
"metadata": {},
"outputs": []
}
],
"metadata": {}