{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Recap 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Second Checkpoint\n", "\n", "Since the first recap, you've learned about lists, dictionaries and loops. Let's revise those concepts and how to use them in this notebook before continuing on to some new material. Answer the questions as best you can, working through any error messages you receive and remembering to refer back to previous notebooks. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists\n", "First, here's a reminder of some useful methods (_i.e._ functions) that apply to lists:\n", "\n", "| Method | Action |\n", "|------------------------|------------------------------------------------------------------|\n", "| list.count(`x`) | Return the number of times x appears in the list |\n", "| list.insert(`i`, `x`) | Insert value `x` at a given position `i` |\n", "| list.pop([`i`]) | Remove and return the value at position `i` (`i` is optional) |\n", "| list.remove(`x`) | Remove the first element from the list whose value is `x` |\n", "| list.reverse() | Reverse the elements of the list in place |\n", "| list.sort() | Sort the items of the list in place |\n", "| list.index(`x`) | Find the first occurence of `x` in the list |\n", "| list[x:y] | Subset the list from index `x` to `y-1` |\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interacting with Lists\n", "\n", "Replace `???` in the following code blocks to make the code work as instructed in the comments. All of the methods that you need are listed above, so this is about testing yourself on your understanding *both* of how to read the help *and* how to index elements in a list." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**a)** The next line creates a list of city names (each element is a string) - run the code and check you understand what it is doing. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cities = [\"Bristol\", \"London\", \"Manchester\", \"Edinburgh\", \"Belfast\", \"York\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**b)** Replace the `???` so that it prints the position of Manchester in the list" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print(\"The position of Manchester in the list is: \" + str(cities.???('Manchester')))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print(\"The position of Manchester in the list is: \" + str(cities.index('Manchester')))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**c)** Replace the `???` so that it prints Belfast" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print(cities[2 + ???])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print(cities[2 + 2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**d)** Use a **negative** index to print *Belfast*" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print(cities[???])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print(cities[-2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**e)** Force Python to generate a `list index out of range` error. NB: This error happens you provide an index for which a list element does not exist" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print(cities[???])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print(cities[6]) #anything above five would do it" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**f)** Think about what the next line creates, then run the code. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "temperatures = [15.6, 16.5, 13.4, 14.0, 15.2, 14.8]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**g)** What would you change `???` to, to return `[16.5, 13.4, 14.0]`?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print(temperatures[???])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print(temperatures[1:4])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**h)** What are two different ways of getting `[15.2, 14.8]` from the `temperatures` list?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print(temperatures[???])\n", "print(temperatures[???])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print(temperatures[4:6])\n", "print(temperatures[-3:-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**i)** Notice that the list of `temperatures` is the same length as the list of `cities`, that's because these are (roughly) average temperatures for each city! Given this, how do you print: \"The average temperature in Manchester is 13.4 degrees.\" _without_ doing any of the following:\n", "1. Using a list index directly (*i.e.* `cities[2]` and `temperatures[2]`) or \n", "2. Hard-coding the name of the city? \n", "\n", "**To put it another way, neither of these solutions is the answer**:\n", "```python\n", "print(\"The average temperature in Manchester is \" + str(temperatures[2]) + \" degrees.\")\n", "```\n", "or \n", "```python\n", "city=2\n", "print(\"The average temperature in \" + cities[city] + \" is \" + str(temperatures[city]) + \" degrees.\")\n", "```\n", "\n", "_Hint:_ you need to combine some of the ideas we've used above!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "city=\"Manchester\" # Use this to start the solution...\n", "#your code here" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "city=\"Manchester\" # Use this to get the solution...\n", "index = cities.index(city)\n", "print(\"The average temperature in \" + cities[index] + \" is \" + str(temperatures[index]) + \" degrees.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now copy+paste your code and change only **one** thing in order to print out: \"The average temperature in Belfast is 15.2 degrees\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "???" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "city=\"Belfast\"\n", "index = cities.index(city)\n", "print(\"The average temperature in \" + cities[index] + \" is \" + str(temperatures[index]) + \" degrees.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.2 Manipulating Multiple Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We'll create two lists for the next set of questions" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list1 = [1, 2, 3]\n", "list2 = [4, 5, 6]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**j)** How do you get Python to print: `[1, 2, 3, 4, 5, 6]`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print( ??? )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print ( list1 + list2 )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**k)** How to you get Python to print: `[1, 2, 3, [4, 5, 6]]`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print( ??? )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print( list1+[list2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's re-set the lists (run the next code block)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list1 = [1, 2, 3]\n", "list2 = [4, 5, 6]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**l)** How would you print out: `[6, 5, 4, 3, 2, 1]` ?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "list3 = ???\n", "list3.???\n", "print(list3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "list3 = list1+list2\n", "list3.reverse()\n", "print(list3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**m)** How would you print out: `[3, 2, 1, 6, 5, 4]` ?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "list1.???\n", "list2.???\n", "print( list1+list2 )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "list1.reverse()\n", "list2.reverse()\n", "print( list1+list2 )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**n)** How would you print out `[3, 2, 6, 5]` with a permanent change to the list (not slicing)? NB: this follows on from the previous question, so note that the order is still 'reversed'." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "list1.???\n", "list2.???\n", "print( list1+list2 )" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "list1.remove(1)\n", "list2.remove(4)\n", "print( list1+list2 )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries\n", "\n", "Remember that dictionaries (a.k.a. dicts) are like lists in that they are [data structures](https://docs.python.org/2/tutorial/datastructures.html) containing multiple elements. A key difference between [dictionaries](https://docs.python.org/2/tutorial/datastructures.html#dictionaries) and [lists](https://docs.python.org/2/tutorial/introduction.html#lists) is that while elements in lists are ordered, dicts are unordered. This means that whereas for lists we use integers as indexes to access elements, in dictonaries we use 'keys' (which can multiple different types; strings, integers, etc.). Consequently, an important concept for dicts is that of key-value pairs. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating an Atlas\n", "\n", "Replace `???` in the following code block to make the code work as instructed in the comments. If you need some hints and reminders, revisit [Code Camp Lesson 7](https://kingsgeocomputation.org/teaching/code-camp/code-camp-python/lessons/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Run the code and check you understand what the data structure that is being created (the data for each city are latitude, longitude and airport code)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "cities = {\n", " 'San Francisco': [37.77, -122.43, 'SFO'],\n", " 'London': [51.51, -0.08, 'LDN'],\n", " 'Paris': [48.86,2.29, 'PAR'],\n", " 'Beijing': [39.92,116.40 ,'BEI'],\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**a)** Add a record to the dictionary for Chennai ([data here](https://en.wikipedia.org/wiki/Chennai))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "cities = ???" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "cities = {\n", " 'San Francisco': [37.77, -122.43, 'SFO'],\n", " 'London': [51.51, -0.08, 'LDN'],\n", " 'Paris': [48.86,2.29, 'PAR'],\n", " 'Beijing': [39.92,116.40 ,'BEI'],\n", " 'Chennai': [13.08, 80.27,'MAA']\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**b)** In *one* line of code, print out the airport code for Chennai" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print(???)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print(\"The airport code for Chennai is \" + cities[\"Chennai\"][2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**c)** Check you understand the difference between the following two blocks of code by running them, checking the output and editing them (e.g. try the code again, but replacing *Berlin* with *London*)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "print(cities['Berlin'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "print(cities.get('Berlin'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "#Berlin is not in the dict. \n", "#The first code block above returns an error because Berlin is missing\n", "#The second does not because it uses the .get method which handles the error for us (returning a None value)\n", "#This second method is 'safer' because of how it handles this error\n", "\n", "#compare to use using the two different methods for London\n", "print(cities['London'])\n", "print(cities.get('London'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "print(cities.get('London'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**d)** Adapting the code below, print out the city name and airport code for every city in our Atlas." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "for k, v in cities.items():\n", " print(k)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "for k, v in cities.items():\n", " print(\"The city of \" + str(k) + \" has an airport code of \" + str(v[2]) )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loops\n", "\n", "Recall from the previous notebook that loops are a way to *iterate* (or repeat) chunks of code. The two most common ways to iterate a set of commands are the `while` loop and the `for` loop. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Working with Loops\n", "The questions below use `for` loops. Replace `???` in the following code block to make the code work as instructed in the comments. If you need some hints and reminders, revisit the previous notebook." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**a)** Print out the name and latitude of every city in the cities dictionary using a for loop" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "for ??? in cities.???:\n", " print(??? + \" is at latitude \" + str(???))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "for city, latitude in cities.items():\n", " print(city + \" is at latitude \" + str(latitude[0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**b)** Print out every city on a separate line using a for loop:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "for c in ???:\n", " print(???)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "for c in cities.items():\n", " print(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**c)** Now print using a loop this new data structure:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden", "solution2_first": true }, "outputs": [], "source": [ "citiesB = [\n", " {'name': 'San Francisco',\n", " 'position': [37.77, -122.43],\n", " 'airport': 'SFO'},\n", " {'name': 'London',\n", " 'position': [51.51, -0.08],\n", " 'airport': 'LDN'},\n", " {'name': 'Paris',\n", " 'position': [48.86, 2.29],\n", " 'airport': 'PAR'},\n", " {'name': 'Beijing',\n", " 'position': [39.92, 116.40],\n", " 'airport': 'BEI'}\n", "]\n", "\n", "for ??? in citiesB.???:\n", " print(??? + \" is at latitude \" + str(???))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "solution2": "hidden" }, "outputs": [], "source": [ "citiesB = [\n", " {'name': 'San Francisco',\n", " 'position': [37.77, -122.43],\n", " 'airport': 'SFO'},\n", " {'name': 'London',\n", " 'position': [51.51, -0.08],\n", " 'airport': 'LDN'},\n", " {'name': 'Paris',\n", " 'position': [48.86, 2.29],\n", " 'airport': 'PAR'},\n", " {'name': 'Beijing',\n", " 'position': [39.92, 116.40],\n", " 'airport': 'BEI'}\n", "]\n", "\n", "for city in citiesB:\n", " print(city['name'] + \" is at latitude \" + str(city['position'][0]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Nice work. Hopefully these questions have helped you compound your understanding. Onwards!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Credits!\n", "\n", "#### Contributors:\n", "The following individuals have contributed to these teaching materials: \n", "- [James Millington](https://github.com/jamesdamillington)\n", "- [Jon Reades](https://github.com/jreades)\n", "- [Michele Ferretti](https://github.com/miccferr)\n", "- [Zahratu Shabrina](https://github.com/zarashabrina)\n", "\n", "#### License\n", "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).\n", "\n", "#### Acknowledgements:\n", "Supported by the [Royal Geographical Society](https://www.rgs.org/HomePage.htm) (with the Institute of British Geographers) with a Ray Y Gildea Jr Award.\n", "\n", "#### Potential Dependencies:\n", "This notebook may depend on the following libraries: None" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 4 }