diff --git a/notebook-01.ipynb b/notebook-01.ipynb index 7619f9b..7404bf2 100644 --- a/notebook-01.ipynb +++ b/notebook-01.ipynb @@ -629,7 +629,9 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "(2+2+1250)/3" + ] }, { "cell_type": "markdown", @@ -1143,9 +1145,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.5" + "version": "3.7.3" } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/notebook-04.ipynb b/notebook-04.ipynb index f97e306..87f1d9c 100644 --- a/notebook-04.ipynb +++ b/notebook-04.ipynb @@ -483,9 +483,7 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "*The content and structure of this teaching project itself is licensed under the [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license](https://creativecommons.org/licenses/by-nc-sa/4.0/) , and the contributing source code is licensed under [The MIT License](https://opensource.org/licenses/mit-license.php). *" ] @@ -508,9 +506,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.5" + "version": "3.7.3" } }, "nbformat": 4, - "nbformat_minor": 1 + "nbformat_minor": 4 } diff --git a/notebook-05.ipynb b/notebook-05.ipynb index a11de1f..95cbaef 100644 --- a/notebook-05.ipynb +++ b/notebook-05.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Notebook-5 Truth & Conditions" + "# Notebook-5: Truth & Conditions" ] }, { @@ -835,9 +835,7 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [] }, { @@ -865,9 +863,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.5" + "version": "3.7.3" } }, "nbformat": 4, - "nbformat_minor": 1 + "nbformat_minor": 4 } diff --git a/notebook-07.ipynb b/notebook-07.ipynb index 4b0343d..f4ec79b 100644 --- a/notebook-07.ipynb +++ b/notebook-07.ipynb @@ -129,7 +129,7 @@ "metadata": {}, "outputs": [], "source": [ - "print(myDict[???])" + "print(myDict[\"key2\"])" ] }, { @@ -184,7 +184,8 @@ "outputs": [], "source": [ "eNumbers = {\n", - " ???\n", + " \"IS\": '112', # It's not very important here whether we use single- or double-quotes\n", + " \"US\": '911'\n", "}\n", "print(\"The Icelandic emergency number is \" + eNumbers['IS'])\n", "print(\"The American emergency number is \" + eNumbers['US']) " @@ -220,7 +221,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "Or maybe you just need to access all of the values without trouble to ask for each key:" + "Or maybe you just need to access all of the values without troubling to ask for each key:" ] }, { @@ -355,7 +356,11 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "print(cityData[1][1])\n", + "print(cityData[4][3])\n", + "print(cityData[2][0])" + ] }, { "cell_type": "markdown", @@ -380,8 +385,13 @@ "eNumbers = {\n", " 'IS': ['Icelandic',112],\n", " 'US': ['American',911],\n", + " 'FR': ['French',112],\n", + " 'RU': ['Russion',102],\n", + " 'UK': ['British',999]\n", "}\n", - "print(\"The \" + eNumbers['IS'][0] + \" emergency number is \" + str(eNumbers['IS'][1]))" + "print(\"The \" + eNumbers['IS'][0] + \" emergency number is \" + str(eNumbers['IS'][1]))\n", + "print(\"The \" + eNumbers['RU'][0] + \" emergency number is \" + str(eNumbers['RU'][1]))\n", + "print(\"The \" + eNumbers['UK'][0] + \" emergency number is \" + str(eNumbers['UK'][1]))" ] }, { @@ -447,7 +457,26 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "# Note that we can tweak the formatting a bit: Python is smart \n", + "# enough to understand that if you have a '+' on the end of a\n", + "# string and there next line is also a string then it'll \n", + "# continue to concatenate the string...\n", + "print(\"The population of \" + 'London' + \", the capital of \" + \n", + " cityData2['London']['country']['Full'] + \" (\" + cityData2['London']['country']['ISO2'] + \"), is \" + \n", + " str(cityData2['London']['population']) + \". It has a density of \" + \n", + " str(cityData2['London']['population']/cityData2['London']['area']) + \" persons per square km\")\n", + "\n", + "# But a _better_ way to do this might be one in which we don't\n", + "# hard-code 'London' into the output -- by changing the variable\n", + "# 'c' to Paris we can change the output completely...\n", + "c = 'Paris'\n", + "cd = cityData2[c]\n", + "print(\"The population of \" + c + \", the capital of \" + \n", + " cd['country']['Full'] + \" (\" + cd['country']['ISO2'] + \"), is \" + \n", + " str(cd['population']) + \". It has a density of \" + \n", + " \"{0:8.1f}\".format(cd['population']/cd['area']) + \" persons per square km\")" + ] }, { "cell_type": "markdown", @@ -517,13 +546,13 @@ "latitude = '51.51130657591914'\n", "\n", "# Set this up as a coordinate pair \n", - "KCLCoords = [??? , latitude ]\n", + "KCLCoords = [longitude, latitude ]\n", "\n", "# How can you assign KCLCoords to \n", "# the key KCLGeometry[\"coordinates\"]?\n", "KCLGeometry = {\n", " \"type\": \"Point\",\n", - " \"coordinates\": ???\n", + " \"coordinates\": KCLCoords\n", " }\n", "\n", "KCL_position = {\n", @@ -552,7 +581,12 @@ "# You should see it if you click on the 'Home' tab in your open\n", "# browser window (it's the one where you started this notebook)\n", "with open('my-first-marker.geojson', 'w') as outfile:\n", - " json.dump(json.dumps(KCL_position, indent=4), outfile)" + " json.dump(json.dumps(KCL_position, indent=4), outfile)\n", + " \n", + "# And we can also show this in Jupyter directly (it won't show\n", + "# up in the PDF version though)\n", + "from IPython.display import GeoJSON\n", + "GeoJSON(json.dumps(KCL_position, indent=4))" ] }, { @@ -564,9 +598,7 @@ }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "**Congratulations on finishing your seventh notebook!**" ] @@ -614,9 +646,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.5" + "version": "3.7.3" } }, "nbformat": 4, - "nbformat_minor": 1 + "nbformat_minor": 4 } diff --git a/notebook-08.ipynb b/notebook-08.ipynb index 39a9c2f..6e28d26 100644 --- a/notebook-08.ipynb +++ b/notebook-08.ipynb @@ -42,6 +42,7 @@ "\n", "[![Demonstration of While and For Loops](http://img.youtube.com/vi/9AJ0uoxtdCQ/0.jpg)](https://www.youtube.com/watch?v=9AJ0uoxtdCQ)\n", "\n", + "\n", "The 'right' approach you use usually depends on [what sort of data structure you are iterating over](http://stackoverflow.com/questions/920645/when-to-use-while-or-the-for-in-python) and [whether we know before we start how many times we want to repeat the commands](https://www.reddit.com/r/learnprogramming/comments/3bqzpf/python_for_loops_vs_while_loops/). That might sound a little vague at this point, but come back and have a think about it once you have a better understanding of how loops work.\n", "\n", "So let's first see how while loops work, then we'll look at actual loops in Python." @@ -128,9 +129,9 @@ "source": [ "otherCounter = 1\n", "\n", - "while ??? <= 10:\n", + "while otherCounter <= 10:\n", " print(\"This is an odd number: \" + str(otherCounter))\n", - " ??? += 2" + " otherCounter += 2" ] }, { @@ -283,7 +284,7 @@ " if i % 7 == 0:\n", " print(\"WOOT!\")\n", " \n", - " if i == 21:\n", + " if i == 25:\n", " break\n", " \n", "print(\"Done!\")" @@ -307,8 +308,38 @@ "17\n", "19\n", "WOOT!\n", - "`\n", + "`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "i = 0\n", "\n", + "while True:\n", + " \n", + " i += 1\n", + " \n", + " if i % 2 != 0:\n", + " if i % 7 == 0:\n", + " print(\"WOOT!\")\n", + " else:\n", + " print(i)\n", + " \n", + " if i == 25:\n", + " break\n", + " \n", + "print(\"Done!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "### A challenge for you!\n", "\n", "Now, replace the `???` in the code below and use it to print only even numbers less than 22." @@ -325,9 +356,9 @@ " i += 1\n", " \n", " if i % 2 != 0:\n", - " ???\n", + " continue\n", " if i == 22:\n", - " ???\n", + " break\n", " print(i)\n", "\n", "print(\"Done!\")" @@ -393,6 +424,19 @@ "*Hint*: check (using `print`) the values of `counter` and `britishCompList`. What is the condition we are asking Python to use?" ] }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "counter = 0\n", + "while counter < len(britishCompList):\n", + " print(britishCompList[counter] + \" was a british computer scientist\")\n", + " # don't forget to increment the counter!!!\n", + " counter += 1" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -401,7 +445,7 @@ "\n", "If you think that being skipped over in the loop above was tough for old Babbage, then perhaps you might be interested to hear about the history of the [NASA 'computers' who helped put a man on the moon](https://www.washingtonpost.com/lifestyle/style/the-nearly-forgotten-story-of-the-black-women-who-helped-land-a-man-on-the-moon/2016/09/12/95f2d356-7504-11e6-8149-b8d05321db62_story.html) and are only getting a film made about them in 2016.\n", "\n", - "[![The hidden history of NASA's computers](http://img.youtube.com/vi/RK8xHq6dfAo/0.jpg)](http://www.youtube.com/watch?v=RK8xHq6dfAo)" + "[![The hidden history of NASA's computers](http://img.youtube.com/vi/RK8xHq6dfAo/0.jpg)](http://www.youtube.com/watch?v=RK8xHq6dfAo)\n" ] }, { @@ -419,7 +463,7 @@ "metadata": {}, "outputs": [], "source": [ - "counter = ???\n", + "counter = 0\n", "nonBritishProgrammers = [\"Torvald\", \"Knuth\", \"Swartz\"]\n", "stoppingCondition = len(nonBritishProgrammers)\n", "\n", @@ -556,9 +600,9 @@ "outputs": [], "source": [ "numbers = [1,2,3,4,5,6,7,8,9,10]\n", - "for ??? in numbers:\n", - " if (??? % 2 != 0):\n", - " print(???)" + "for n in numbers:\n", + " if (n % 2 != 0):\n", + " print(n)" ] }, { @@ -574,7 +618,7 @@ "metadata": {}, "outputs": [], "source": [ - "??? i ??? ???(10):\n", + "for i in range(10):\n", " if (i % 2 != 0):\n", " print(i)" ] @@ -653,8 +697,8 @@ " ]\n", " }\n", " }\n", - "for k,v in KCL_marker[\"???\"].???():\n", - " print(\"KCL_marker has a property: \" + v + \" for the key: \" + k)\n" + "for k,v in KCL_marker[\"properties\"].items():\n", + " print(\"KCL_marker has a property: '\" + v + \"' for the key: \" + k)\n" ] }, { @@ -675,17 +719,17 @@ "source": [ "# Code (Applied Geo-example)\n", "\n", - "The geo-excercise I'll give you this time is a real-world problem that you might face one day in your career as geospatial professionals. Depending on how well you understood the material above (and from previous notebvooks) you may or may not be able to work this one out. If not, don't worry, just try to understand the concepts above and hopefully in future you'll be able to come back and work it out. \n", + "The geo-excercise I'll give you this time is a real-world problem that you might face one day in your career as geospatial professionals. In _principle_ it is possible to work out everything below based on what we've done up to this point; however, this exercise is also _hard_ since it is a big jump conceptually that mixes up the ideas in a new way. So if you can't quite make out the answer don't worry, just try to understand the concepts above and see if you can solve _parts_ of the problem. \n", "\n", "Let's say a colleague of yours used a GPS to survey at regular intervals the dispersion of pollutants in a patch of terrain. Unfortunately, after a good start they forgot to record all the remaining points! \n", "\n", - "But that's not a terrible problem, as the transect has a perfect West-East orientation and direction, and all the points are spaced by a the same value dX of 0.03 degrees longitude, i.e.:\n", + "But that's not a terrible problem, as the transect has a perfect West-East orientation and direction, and all the points are spaced by a the same value dX (short for 'delta-X', the change in X between each point) of 0.03 degrees longitude, i.e.:\n", "\n", "(0.0102, 51.592)-----(X+dX,Y)-----(X+2dX,Y)-----(X+3dX,Y)--->\n", " \n", "Using what we've seen so far, try to create a `GeoJSON featureCollection` of points. To give you a head start, I've provided some *scaffolding*.\n", "\n", - "HINT: Being the skilled geographer that you are, you immediately realise that actually you've got all the coordinates that you need, even for the missing points (i.e. the latitude values will remain constant..)" + "HINT: Being the skilled geographer that you are, you immediately realise that actually you've got all the coordinates that you need, even for the missing points (i.e. the latitude values will remain constant...)" ] }, { @@ -694,10 +738,16 @@ "metadata": {}, "outputs": [], "source": [ - "# define a new featureCollection\n", - "# it's simply a dictionary\n", - "# we are going to add new point features (dictionaries as well)\n", - "# in its features property (which is a list, so we'll have to append them )\n", + "# define a new featureCollection: it is basically a very fancy dictionary\n", + "# to which we are going to add new 'features' (which are points on a map\n", + "# but represented as *data* by a dictionary). We need to add one feature\n", + "# at a time when building our transect...\n", + "# initial coordinate list\n", + "init_coords = [-0.0200, 51.592]\n", + "# dX delta \n", + "dx = 0.03\n", + "gap = 0\n", + "\n", "transect = {\n", " \"type\": \"FeatureCollection\",\n", " \"features\": [\n", @@ -706,27 +756,20 @@ " \"properties\": {},\n", " \"geometry\": {\n", " \"type\": \"Point\",\n", - " \"coordinates\": [\n", - " 0.0100,\n", - " 51.592\n", - " ]\n", + " \"coordinates\": init_coords\n", " }\n", " }\n", "# -------------------------------------------------------------\n", - "# here is where the remaining three points have to go\n", + "# here is where the remaining three points have to be\n", + "# added using *code* and not manually\n", "# -------------------------------------------------------------\n", " ]\n", "}\n", "\n", - "# initial coordinate list\n", - "initial_coordinates = [0.0100, 51.592]\n", - "# dX delta \n", - "gap = 0.03\n", "# new empty list where I'm going to put all the new dictionaries \n", "# a.k.a. all the new points\n", "three_new_points = []\n", "\n", - "\n", "for i in range(3):\n", "# define a new point \n", " new_point = {\n", @@ -738,24 +781,57 @@ "\n", " }\n", " }\n", - "# create a new list with the updated coordinates\n", - " new_coordinates = [???[0] + gap, initial_coordinates[1]]\n", - "# assign the new coordinates to the coordinates key\n", - "# in the new point dictionary\n", + " \n", + " # increment the longitude\n", + " gap += dx\n", + " \n", + " # create a new list with the updated coordinates\n", + " new_coordinates = [init_coords[0] + gap, init_coords[1]]\n", + "\n", + " # assign the new coordinates to the coordinates key\n", + " # in the new point dictionary\n", " new_point[\"geometry\"][\"coordinates\"] = new_coordinates\n", - "# append the new point dictionary to the list of new points\n", - " three_new_points.append(???)\n", - "# increment the longitude\n", - " gap += 0.03\n", + " new_point[\"properties\"][\"name\"] = \"Point \" + str(i+1)\n", + "\n", + " # append the new point dictionary to the list of new points\n", + " three_new_points.append(new_point)\n", "\n", "\n", - "# out of the For Loop\n", - "# append the list with all the three new points\n", - "# to the features list within the transect dictionary\n", - "transect[\"features\"].append(???)\n", + "# append to the feature list the three new points\n", + "# that we created\n", + "transect[\"features\"].extend(three_new_points)\n", "print(transect)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This output on its own makes _very_ little sense, but it's actually a real world data structure called JSON. Below we use a handy library (that you might not yet have installed on your computer) to turn that JSON into something easier to read, and _then_ we'll see how you can use it!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import json \n", + "parsed = json.loads(str(transect).replace(\"\\'\", \"\\\"\"))\n", + "print(json.dumps(parsed, indent=4))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# And show the points on an interactive map!\n", + "from IPython.display import GeoJSON\n", + "GeoJSON(parsed)" + ] + }, { "cell_type": "markdown", "metadata": {}, @@ -806,9 +882,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.5" + "version": "3.7.3" } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 } diff --git a/notebook-09.ipynb b/notebook-09.ipynb index 308065c..e435974 100644 --- a/notebook-09.ipynb +++ b/notebook-09.ipynb @@ -136,9 +136,9 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "#### A challenge for you!\n", + "Notice that the sequence of function **definiton** (`def`) *and then* function **call** (`function_name()`) is important! Think about it: how would Python know what we are referring to (i.e. what is the `myFirstFunc` it has to call?), if we haven't yet specified it?\n", "\n", - "Now define and call a new function called \"sunnyDay\" that prints the string \"What a lovely day!\" And then define and call one named \"gloomyDay\" that prints \"I hate rainy days!\"" + "It's the same as with variables: try to `print` one before you've defined it and Python will complain!" ] }, { @@ -147,18 +147,15 @@ "metadata": {}, "outputs": [], "source": [ - "def ??? :\n", - " print(???)" + "print(myVariable)\n", + "myVariable = \"Hallo Hallo!\"" ] }, { - "cell_type": "code", - "execution_count": null, + "cell_type": "markdown", "metadata": {}, - "outputs": [], "source": [ - "??? gloomyDay??\n", - "???print \"I hate rainy days!\"" + "Reading (out loud!) the error message hopefully makes the error obvious... Quite explicit, isn't it? :)" ] }, { @@ -167,16 +164,17 @@ "metadata": {}, "outputs": [], "source": [ - "gloomyDay??" + "myVariable = \"Hallo Hallo!\"\n", + "print(myVariable)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "Notice that the sequence function definiton *and then* function call is important! Think about it: how would Python know what we are referring to (i.e. what is the `myFirstFunction` it has to call?), if we haven't yet specified it?\n", + "#### A challenge for you!\n", "\n", - "It's the same as with variables: try to `print` one before you've defined it and Python will complain!" + "Now define and call a new function called \"sunnyDay\" that prints the string \"What a lovely day!\" And then define and call one named \"gloomyDay\" that prints \"I hate rainy days!\" Call both of them in whatever order you like." ] }, { @@ -185,17 +183,28 @@ "metadata": {}, "outputs": [], "source": [ - "print(myVariable)\n", - "myVariable = \"Hallo Hallo!\"" + "def sunnyDay():\n", + " print(\"What a lovely day!\")" ] }, { - "cell_type": "markdown", + "cell_type": "code", + "execution_count": null, "metadata": {}, + "outputs": [], "source": [ - "#### A challenge for you!\n", - "\n", - "Once again, read (out loud!) the error message. What is it saying to you? Quite explicit, isn't it? :)" + "def gloomyDay():\n", + " print(\"I hate rainy days!\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "gloomyDay()\n", + "sunnyDay()" ] }, { @@ -240,16 +249,31 @@ "metadata": {}, "outputs": [], "source": [ - "printMyName(???)" + "printMyName(\"Jon Reades\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "A *little* more useful, right? If we had to print out name badges for a big conference, rather than typing \"Hi! My name is ...\" hundreds of times, if we had a list of people's names, we could just use a `for` loop to print out each one in turn using this function. The function adds the part that *is the same* for every name badge and all we need to do is pass it the input parameters.\n", - "\n", - "In the function `printMyName` we used just one parameter as input, but we are not constrained to that. We can in fact input multiple *comma-separated* parameters; let's _redefine_ the `printMyName` function:" + "A *little* more useful, right? If we had to print out name badges for a big conference, rather than typing \"Hi! My name is ...\" hundreds of times, if we had a list of people's names, we could just use a `for` loop to print out each one in turn using this function. The function adds the part that *is the same* for every name badge and all we need to do is pass it the input parameters. In fact, why don't we try that now?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for name in [\"Jon Reades\", \"James Millington\", \"Chen Zhong\", \"Naru Shiode\"]:\n", + " printMyName(name)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the function `printMyName` we used just one parameter as an input, but we are not constrained to just one. We can input many parameters *separated by commas*; let's _redefine_ the `printMyName` function:" ] }, { @@ -310,7 +334,31 @@ "execution_count": null, "metadata": {}, "outputs": [], - "source": [] + "source": [ + "def printMyAge(name, age):\n", + " print(name + \" is \" + str(age) + \" years old.\")\n", + " \n", + "printMyAge('Jon',25)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There's actually a new way to do this in Python 3.7 that is quite helpful because it's easier to read:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def printMyAge(name, age):\n", + " print(f\"{name} is {age} years old.\") # This is called a 'f-string' and we use {...} to add variables\n", + " \n", + "printMyAge('Jon',25)" + ] }, { "cell_type": "markdown", @@ -329,10 +377,14 @@ "metadata": {}, "outputs": [], "source": [ - "def whoAmI(name, surname):\n", - " print(\"Hi! My name is \"+ name + \" \" + surname + \"!\")\n", + "def whoAmI(myname, mysurname):\n", + " if not myname:\n", + " myname = 'Charles'\n", + " if not mysurname:\n", + " mysurname = 'Babbage'\n", + " print(\"Hi! My name is \"+ myname + \" \" + mysurname + \"!\")\n", "\n", - "print(name)" + "print(myname) # myname _only_ exists 'inside' the function definition" ] }, { @@ -341,8 +393,22 @@ "source": [ "Notice how the ErrorMessage is the same as before when we tried to `print` a variable that wasn't defined yet? It's the same concept: the variables defined as parameters exist only in the indented code block of the function (the [function *scope*](http://python-textbok.readthedocs.io/en/latest/Variables_and_Scope.html) ).\n", "\n", - "But notice too that if you replace `print name` with `whoAmI(\"Ada\", \"Lovelace\")` then the error disappears and you will see the output: \"Hi! My name is Ada Lovelace.\" So to reiterate: parameters to a function exist as variables **only within the function scope**.\n", - "\n", + "But notice too that if you replace `print name` with `whoAmI(\"Ada\", \"Lovelace\")` then the error disappears and you will see the output: \"Hi! My name is Ada Lovelace.\" So to reiterate: parameters to a function exist as variables **only within the function scope**." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "whoAmI('Ada','Lovelace')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ "## Default Parameters\n", "\n", "Let's say that your namebade printing function is a worldwide hit, and while most conferences take place in English, in some cases they might need to say 'Hello' in a different languages. In this case, we might like to have a parameter with a _default_ value (\"Hi\") but allow the programmer to override that with a _different_ value (e.g. \"Bonjour\").\n", @@ -411,7 +477,7 @@ "returnedValue = sumOf(4, 3)\n", "\n", "# Notice the casting from int to str!\n", - "print(\"This is the returned value: \"+ str(returnedValue))" + "print(f\"This is the returned value: {returnedValue}\")" ] }, { @@ -563,10 +629,8 @@ " for i in range(inputRange):\n", " if i%2 != 0:\n", " print(i)\n", - "# ---------------------\n", - "# you code here \n", - "# ---------------------\n", - "# HINT : remember the IF ELSE statment?\n", + " else:\n", + " print(\"Yuck, an even number!\")\n", "\n", "oddNumbers(8)" ] @@ -589,15 +653,18 @@ "def addTwo(param1):\n", " return param1 + 2\n", "\n", - "def multiplyByThree(param1):\n", - " print param1 * 3\n", + "def multiplyByThree(param1): # Note: this is a *separate* variable from the param1 in addTwo() because of scoping!\n", + " return param1 * 3\n", "\n", "# you can use multiplyByThree\n", "# with a regular argument as input \n", - "multiplyByThree(4)\n", + "print(multiplyByThree(2))\n", "\n", "# but also with a function as input\n", - "multiplyByThree(addTwo(2))" + "print(multiplyByThree(addTwo(2)))\n", + "\n", + "# And then\n", + "print(addTwo(multiplyByThree(2)))" ] }, { @@ -665,17 +732,19 @@ "\n", "# Calculate the proportion of the population\n", "# that lives in a borough given the total population. \n", - "def calcProportion(???,???):\n", + "def calcProportion(boro,city_pop=7375000):\n", " # do your magic here\n", " # then return the proportion!\n", " # Note that one of them can probably\n", " # default to a particular value...\n", + " return boro['population']/city_pop\n", "\n", - "def getLocation(borough):\n", + "def getLocation(boro):\n", " # do your magic here assuming\n", " # that you've been asked to find\n", " # a borough name in the keys of \n", " # the london_boroughs DoD above.\n", + " return boro['coordinates']\n", " \n", "# ---------------------------\n", "# Let's go!\n", @@ -683,20 +752,36 @@ "\n", "# Print the proportion of the population that\n", "# lives in the City of London\n", - "\n", - "# Do the same for Hackney\n", + "print(calcProportion(london_boroughs['City of London']))\n", + "print(\"\")\n", + "\n", + "# Print all of the population proportions\n", + "# You'll need to think about why this works!\n", + "# Don't get too hung up on the '%3.2f' stuff, \n", + "# we'll look at that in a later class but I just\n", + "# want to show you how it works here.\n", + "for boro, data in london_boroughs.items():\n", + " prop = calcProportion(data)\n", + " \n", + " print(\"Proportion is {0:3.3f}%\".format(prop*100))\n", + "print(\"\")\n", "\n", "# What is the longitude of Lambeth?\n", "# You should be able to do this in one line, \n", "# but don't stress it if you can't figure out \n", - "# how... " + "# how... \n", + "print(getLocation(london_boroughs['Lambeth'])[0])\n", + "print(\"\")\n", + "\n", + "# Here's a more user-friendly way:\n", + "coord = getLocation(london_boroughs['Lambeth'])\n", + "long = coord[0]\n", + "print(long)" ] }, { "cell_type": "markdown", - "metadata": { - "collapsed": true - }, + "metadata": {}, "source": [ "**Congratulations on finishing your ninth notebook!**" ] @@ -744,9 +829,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.5" + "version": "3.7.3" } }, "nbformat": 4, - "nbformat_minor": 1 + "nbformat_minor": 4 } diff --git a/notebook-10.ipynb b/notebook-10.ipynb index a987ea9..185794f 100644 --- a/notebook-10.ipynb +++ b/notebook-10.ipynb @@ -4,7 +4,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "# Notebook-10: Wrapping Up (Paths, Terminals & Style)" + "# Notebook-10: Wrapping Up (A Matter of Style)" ] }, { @@ -136,9 +136,9 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.6.5" + "version": "3.7.3" } }, "nbformat": 4, - "nbformat_minor": 2 + "nbformat_minor": 4 }