{ "cells": [ { "cell_type": "markdown", "id": "8f45eca1-6539-4539-83f3-c55a7bc65ae2", "metadata": {}, "source": [ "# Geo-Python review\n", "\n", "It has been requested that we review a few topics covered in the Geo-Python part of this course. This notebook presents the main topics and notes/examples generated during our discussion in class." ] }, { "cell_type": "markdown", "id": "ab9f5b49-295c-4216-898a-e3e1bf9d7a3e", "metadata": {}, "source": [ "## `for` loops\n", "\n", "`for` loops are used to iterate over a collection of items and perform calculations using that collection. The collection could be something like a Python list, a NumPy array, or some other structure.\n", "\n", "The structure of the loop is:\n", "\n", "```python\n", "for variable in collection:\n", " code\n", " to\n", " execute\n", "```\n", "\n", "where `variable` is a normal Python variable that will be assigned a value from `collection` sequentially as the loop is executed. All of the lines indented beneath the `for` statement contain code that will be run each time a new value from `collection` is assigned to `variable`." ] }, { "cell_type": "markdown", "id": "9040577f-3a31-475d-a6dc-0bda5006c8a1", "metadata": {}, "source": [ "### Direct iteration\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "31355af8-283d-4660-be31-fea9932989e5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Today the weather is Cloudy.\n", "Today the weather is Snowing.\n", "Today the weather is Rainy.\n", "Today the weather is Windy.\n" ] } ], "source": [ "weather_conditions = [\"Cloudy\", \"Snowing\", \"Rainy\", \"Windy\"]\n", "\n", "for weather in weather_conditions:\n", " print(f\"Today the weather is {weather}.\")" ] }, { "cell_type": "markdown", "id": "112cc4b0-2ac2-4dda-92ba-2b01c0155718", "metadata": {}, "source": [ "### Iteration using the `range()` function\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "8a208f7d-8853-44d0-ae45-5de5473e60c8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Today the weather is Cold.\n", "Today the weather is Unpleasant.\n", "Today the weather is Blustery.\n", "Today the weather is Cool.\n" ] } ], "source": [ "# Example using index values\n", "temperatures = [\"Cold\", \"Unpleasant\", \"Blustery\", \"Cool\"]\n", "\n", "for i in range(len(temperatures)):\n", " print(f\"Today the weather is {temperatures[i]}.\")" ] }, { "cell_type": "code", "execution_count": 3, "id": "7a0b1bf5-9a47-4055-ac10-465145b9b1bc", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Today the weather is Cold and Cloudy.\n", "Today the weather is Unpleasant and Snowing.\n", "Today the weather is Blustery and Rainy.\n", "Today the weather is Cool and Windy.\n" ] } ], "source": [ "# Using index values to access items from 2 lists\n", "for i in range(len(temperatures)):\n", " print(f\"Today the weather is {temperatures[i]} and {weather_conditions[i]}.\")" ] }, { "cell_type": "markdown", "id": "d5199328-97ef-4662-ba14-bba76cb52f25", "metadata": {}, "source": [ "### Nested loops\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "9b621c9e-8220-4c05-a8a5-2a9b15a5b0d8", "metadata": {}, "outputs": [], "source": [ "# Not covered in today's lesson" ] }, { "cell_type": "markdown", "id": "402e0287-3a36-43b3-8651-f82c43426894", "metadata": {}, "source": [ "### Other loop notes" ] }, { "cell_type": "code", "execution_count": 5, "id": "30e2f8e6-7d3e-4140-9a73-d1ea84c047d1", "metadata": {}, "outputs": [], "source": [ "# None" ] }, { "cell_type": "markdown", "id": "e72c0598-69ea-4aeb-a15b-1b828fd50bab", "metadata": {}, "source": [ "## Functions\n", "\n", "Functions are designed to be used to perform calculations that are frequently used in a program. One of the key ideas of a function is to avoid having to repeat code within a program, as it is possible that repeating code may introduct typographic errors and it can be cumbersome to update the code if the same thing occurs in multiple places in a program.\n", "\n", "The syntax of a function in Python is below:\n", "\n", "```python\n", "def function_name(parameter1, parameter2=0.0, ...):\n", " code\n", " to\n", " execute\n", " return return_value\n", "```\n", "\n", "where `function_name` is the name of the function, and `parameter1` and `parameter2` are parameters (or the names of variables used within the function), `default2` is a default value assigned to a function parameter, the indented code is that executed within the function, and the `return` statement lists the value(s) that will be returned when the function is used. Note that parameters with default values do not need to be listed when calling the function, and when defining the function the parameters without a default value must be listed first in the parameter list.\n", "\n", "### Function examples" ] }, { "cell_type": "code", "execution_count": 6, "id": "ec46f71b-60ab-40f4-bcfe-532e0d4bc9e6", "metadata": {}, "outputs": [], "source": [ "def family_name_printer(first_name, last_name=\"Whipp\"):\n", " print(f\"Hello {first_name} {last_name}!\")\n", " \n", " return 0" ] }, { "cell_type": "code", "execution_count": 7, "id": "8226eefb-f2f9-456b-b3b8-1e3c98842c98", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Dave Whipp!\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# This is OK\n", "# Note: the function prints something and then the return value is displayed\n", "family_name_printer(\"Dave\")" ] }, { "cell_type": "code", "execution_count": 8, "id": "df16b06e-e383-4ee3-bcb5-b89bd13200af", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Dave Whipp!\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# This is also OK\n", "family_name_printer(first_name=\"Dave\")" ] }, { "cell_type": "code", "execution_count": 9, "id": "ac7672c4-beb0-4c24-90cc-eeed065069c1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Dave Smith!\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# This too is OK\n", "family_name_printer(first_name=\"Dave\", last_name=\"Smith\")" ] }, { "cell_type": "code", "execution_count": 10, "id": "e993749f-7f01-4a00-a4e8-2b82a7fe3674", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Dave Smith!\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# So is this\n", "family_name_printer(\"Dave\", last_name=\"Smith\")" ] }, { "cell_type": "code", "execution_count": 11, "id": "172cbc1e-856d-4923-8bda-079f2ad874ad", "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "positional argument follows keyword argument (2272524676.py, line 4)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"/var/folders/lp/cjwc88bd3w10sg327y_4ghg0fsk7jj/T/ipykernel_64613/2272524676.py\"\u001b[0;36m, line \u001b[0;32m4\u001b[0m\n\u001b[0;31m family_name_printer(last_name=\"Smith\", \"Dave\")\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m positional argument follows keyword argument\n" ] } ], "source": [ "# This is not OK because \"Dave\" is ambiguous\n", "# Is that value meant to be the second parameter or assigned to first_name?\n", "# Python cannot tell, so you need to include the parameter name\n", "family_name_printer(last_name=\"Smith\", \"Dave\")" ] }, { "cell_type": "code", "execution_count": 12, "id": "53a6fa30-d443-4ce2-84b8-1834e72ff87d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Dave Smith!\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Like this, all is OK\n", "family_name_printer(last_name=\"Smith\", first_name=\"Dave\")" ] }, { "cell_type": "code", "execution_count": 13, "id": "13511bbe-150b-4a6c-a629-d873e8961cb6", "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'first_name' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/lp/cjwc88bd3w10sg327y_4ghg0fsk7jj/T/ipykernel_64613/501617233.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfirst_name\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'first_name' is not defined" ] } ], "source": [ "# Note that first_name is not a variable available outside of the function\n", "print(first_name)" ] }, { "cell_type": "code", "execution_count": 18, "id": "9ecaaa97-c088-4370-817d-27b23cddda33", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "John\n" ] } ], "source": [ "# Unless we define it first\n", "first_name = \"John\"\n", "print(first_name)" ] }, { "cell_type": "code", "execution_count": 16, "id": "a814e832-4b11-4cf6-89c0-c55817468cd2", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Fred Smith!\n" ] }, { "data": { "text/plain": [ "0" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Note that this does not affect the function use if first_name is assigned in the call\n", "family_name_printer(first_name=\"Fred\", last_name=\"Smith\")" ] }, { "cell_type": "code", "execution_count": 17, "id": "de247181-02a5-4294-b630-d058bef47d20", "metadata": {}, "outputs": [], "source": [ "# Let's define a middle_name variable\n", "middle_name = \"Michael\"" ] }, { "cell_type": "code", "execution_count": 20, "id": "8eb14ec9-0052-48cd-a64d-f18f17e70d0a", "metadata": {}, "outputs": [], "source": [ "# And we can modify our function to return middle_name\n", "# NOTE: We do not pass in middle_name or define it in our function\n", "def family_name_printer(first_name, last_name=\"Whipp\"):\n", " print(f\"Hello {first_name} {last_name}!\")\n", " \n", " return middle_name" ] }, { "cell_type": "code", "execution_count": 21, "id": "5442649c-f659-473b-a045-981ced79fc7d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Fred Smith!\n" ] }, { "data": { "text/plain": [ "'Michael'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Now look what is returned when the function is used\n", "# Be careful!\n", "family_name_printer(first_name=\"Fred\", last_name=\"Smith\")" ] }, { "cell_type": "code", "execution_count": 22, "id": "bd1069ec-cd21-4b2d-8d51-ade8650da425", "metadata": {}, "outputs": [], "source": [ "# Let's make a modified function where the string is returned rather than printed\n", "def family_name_printer2(first_name, last_name=\"Whipp\"):\n", "\n", " return f\"Hello {first_name} {last_name}!\"" ] }, { "cell_type": "code", "execution_count": 26, "id": "4e9b2362-13e8-4e66-be92-64fdc15dfd29", "metadata": {}, "outputs": [], "source": [ "# Let's assign the returned value to a variable\n", "name_output = family_name_printer2(\"Dave\")" ] }, { "cell_type": "code", "execution_count": 27, "id": "2fa55fe5-0ad9-4cfb-8a99-b5fc80de46c0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Dave Whipp!\n" ] } ], "source": [ "# And print...nice!\n", "print(name_output)" ] }, { "cell_type": "code", "execution_count": 28, "id": "18c42601-5eab-478b-8e8d-2f25633c25db", "metadata": {}, "outputs": [], "source": [ "# New function to add two to a number\n", "def add_two(number):\n", " \"\"\"Adds two to a number (duh)\"\"\"\n", " return number + 2" ] }, { "cell_type": "code", "execution_count": 31, "id": "c2a97a2b-761d-4806-9702-ed3251bc4077", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n" ] } ], "source": [ "# It works!\n", "new_number = add_two(4)\n", "print(new_number)" ] }, { "cell_type": "code", "execution_count": 30, "id": "28315bc5-de11-4193-b45b-24783b66c2d8", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can only concatenate str (not \"int\") to str", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/lp/cjwc88bd3w10sg327y_4ghg0fsk7jj/T/ipykernel_64613/1478562146.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnew_number\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0madd_two\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Dave\"\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/var/folders/lp/cjwc88bd3w10sg327y_4ghg0fsk7jj/T/ipykernel_64613/2112875414.py\u001b[0m in \u001b[0;36madd_two\u001b[0;34m(number)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0madd_two\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnumber\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[0;34m\"\"\"Adds two to a number (duh)\"\"\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mreturn\u001b[0m \u001b[0mnumber\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[0m", "\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" ] } ], "source": [ "# But we can break it\n", "# Note: This is a good example of a Pythonic way to have your code fail\n", "# We let Python identify the problem, rather than checking that a number was passed\n", "# into the function\n", "new_number = add_two(\"Dave\")" ] }, { "cell_type": "code", "execution_count": 32, "id": "29414813-68f3-4019-b4e8-02f26cb9a32a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "***------------------------------------------------------------------------***\n" ] } ], "source": [ "# Having fun with formatting output :D\n", "print(3 * '*' + 72 * '-' + 3 * '*')" ] }, { "cell_type": "markdown", "id": "c0f0f75e-6a52-4a02-a958-d335236ec792", "metadata": {}, "source": [ "### Namespaces and functions" ] }, { "cell_type": "code", "execution_count": null, "id": "2093461a-bc46-4a3f-90ae-966bb20976dc", "metadata": {}, "outputs": [], "source": [ "# Covered above" ] }, { "cell_type": "markdown", "id": "e345ea37-b414-443b-bcbb-9ec23c643d47", "metadata": {}, "source": [ "### Other function notes" ] }, { "cell_type": "code", "execution_count": null, "id": "85c63e29-3d69-4d4e-8528-9211232500b7", "metadata": {}, "outputs": [], "source": [ "# None" ] }, { "cell_type": "markdown", "id": "c9e7861f-c917-41c3-82aa-45955c990d70", "metadata": {}, "source": [ "## When to use which brackets\n", "\n", "A common point of confusion in Python relates to when to use which kinds of brackets. There are three different types of brackets that are commonly used, and each are used for different purposes. Below you can find examples of each.\n", "\n", "### Parentheses - `(` and `)`\n", "\n", "#### Mathematical order of operations\n", "\n", "Of course, the most natural example familiar to you would be to use parentheses in a mathematical equation to determine the order in which calculations should be done. Let's consider an example." ] }, { "cell_type": "code", "execution_count": 33, "id": "4bb8f200-f8fb-479d-af0d-4e42f49e6e80", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.5" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Parentheses matter\n", "# Add 3 and 2, then divide by 2\n", "(3 + 2) / 2" ] }, { "cell_type": "code", "execution_count": 34, "id": "c3182167-6e1c-44a1-8136-17a90de3d333", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4.0" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Not equal to above!\n", "# Divide 2 by 2, add 3 to result\n", "3 + 2 / 2" ] }, { "cell_type": "markdown", "id": "608dcc9d-6afe-47b1-9994-d68d5a0cf627", "metadata": {}, "source": [ "Here, the parentheses determine the order in which the math operations occur and will have important implications for the resulting calculated value.\n", "\n", "#### Defining and calling functions\n", "\n", "When functions are defined and called, you also use parentheses to give the list of parameters." ] }, { "cell_type": "code", "execution_count": 35, "id": "0ce457a0-0ff2-44ea-ba11-67b0956be465", "metadata": {}, "outputs": [], "source": [ "# Functions use parentheses too\n", "def add_divide(number1, number2, number3):\n", " return (number1 + number2) / number3" ] }, { "cell_type": "code", "execution_count": 36, "id": "afdb5e88-b356-4441-af62-ac4f5ac2ef41", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.5" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Same as the example above\n", "add_divide(3, 2, 2)" ] }, { "cell_type": "markdown", "id": "e6f886bf-9205-4dfd-8bff-7d43ca58d3ce", "metadata": {}, "source": [ "#### Tuples\n", "\n", "We have not dealt much with tuples so far, but they are similar to Python lists with one important difference: Tuples are immutable, meaning they cannot be changed after they are defined. Let's see an example." ] }, { "cell_type": "code", "execution_count": 37, "id": "46352d0a-04ab-42f7-acae-ce471e56a267", "metadata": {}, "outputs": [], "source": [ "# Make an example tuple\n", "my_tuple = (3.0, \"Dave\", True, 1)" ] }, { "cell_type": "code", "execution_count": 38, "id": "fefc8d39-9269-4df3-9fc5-644fac13af2e", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check the data type\n", "type(my_tuple)" ] }, { "cell_type": "code", "execution_count": 39, "id": "137db47a-4167-4a89-b054-db898e50e42b", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'tuple' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/lp/cjwc88bd3w10sg327y_4ghg0fsk7jj/T/ipykernel_64613/1030788979.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Tuples cannot be modified, this will fail!\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[0mmy_tuple\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\"John\"\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" ] } ], "source": [ "# Tuples cannot be modified, this will fail!\n", "my_tuple[1] = \"John\"" ] }, { "cell_type": "code", "execution_count": 40, "id": "0aa601fb-3b38-449e-a57f-94c95b7be498", "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'tuple' object has no attribute 'append'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/lp/cjwc88bd3w10sg327y_4ghg0fsk7jj/T/ipykernel_64613/2694787715.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Cannot append (modify) a tuple!\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[0mmy_tuple\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Whipp'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'append'" ] } ], "source": [ "# Cannot append (modify) a tuple!\n", "my_tuple.append('Whipp')" ] }, { "cell_type": "markdown", "id": "b15094c2-3854-45ca-bf51-72981f0f7cf0", "metadata": {}, "source": [ "### Square brackets - `[` and `]`\n", "\n", "#### Python lists\n", "\n", "As you have seen, the square brackets are used to create Python lists." ] }, { "cell_type": "code", "execution_count": 41, "id": "15a32892-bd5c-4b2b-b67b-6d3eff574b4c", "metadata": {}, "outputs": [], "source": [ "# Make a list\n", "my_list = [3.0, \"Dave\", True, 1]" ] }, { "cell_type": "code", "execution_count": 42, "id": "831fe15a-c557-47c3-945c-2a9f571ffdb0", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check the data type\n", "type(my_list)" ] }, { "cell_type": "code", "execution_count": 43, "id": "04f7a5b8-7375-4f92-ab34-b9d0544ba594", "metadata": {}, "outputs": [], "source": [ "# Lists CAN be modified\n", "my_list[1] = \"John\"" ] }, { "cell_type": "code", "execution_count": 44, "id": "b89d3e9f-8491-4fbf-95cd-5bab8a9f9b8c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3.0, 'John', True, 1]\n" ] } ], "source": [ "# Confirm list has changed\n", "print(my_list)" ] }, { "cell_type": "markdown", "id": "d4565c16-9e16-466c-9289-b5b8fb327b2e", "metadata": {}, "source": [ "#### Accessing values using index values\n", "\n", "Another common use of the square brackets in Python is to access values from Python lists, tuples, or other collections using an index value." ] }, { "cell_type": "code", "execution_count": 48, "id": "26a2950c-ea79-4b43-af8d-4578586da7f4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'John'" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check a value in our list\n", "my_list[1]" ] }, { "cell_type": "code", "execution_count": 46, "id": "3854e5af-2346-4c3c-ba20-55467eb5d3b4", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check that values in the list and tuple are the same at the same position...yes!\n", "my_list[3] == my_tuple[3]" ] }, { "cell_type": "code", "execution_count": 47, "id": "752b472b-419a-423f-81df-ddba8ab48366", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check that values in the list and tuple are the same at the same position...no!\n", "# Names were changed\n", "my_list[1] == my_tuple[1]" ] }, { "cell_type": "markdown", "id": "e0e8d2e1-a510-41d6-8a1f-d05e11ac6276", "metadata": { "tags": [] }, "source": [ "### Curly braces - `{` and `}`\n", "\n", "#### Dictionaries\n", "\n", "We have only dealt with dictionaries to a limited extent so far, but they can be used to relate a \"key\" in the dictionary to a \"value\", as shown below.\n", "\n", "```python\n", "dictionary_name = {key1: value1, key2: value2, ...}\n", "```\n", "\n", "where `dictionary_name` is the name of the dictionary, and the keys (`key1`, `key2`) are listed and followed by a `:` character that is followed by a corresponding value (`value1`, `value2`). This allows you to find a value using its associated key. This may be easiest to understand through an example." ] }, { "cell_type": "code", "execution_count": 49, "id": "ac78a4f9-fe04-4cb3-b403-ef9b75fa31e9", "metadata": {}, "outputs": [], "source": [ "# Create a dictionary\n", "my_dict = {\"Helsinki\": \"Cloudy\", \"Hyvinkää\": \"Snowy\"}" ] }, { "cell_type": "code", "execution_count": 50, "id": "cfb5bebe-fdcc-4380-bd82-84a5067ca77d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check the data type\n", "type(my_dict)" ] }, { "cell_type": "code", "execution_count": 51, "id": "2b8a0b22-64b4-4773-8dc0-88ce8f33b165", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Snowy'" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use a key to access a value\n", "my_dict[\"Hyvinkää\"]" ] }, { "cell_type": "markdown", "id": "1640eb5e-0b2d-4819-bc72-56ffe49020c2", "metadata": {}, "source": [ "#### Sets\n", "\n", "Sets are yet another type of collection in Python, however they are slightly different from lists and tuples. In a Python set you can create a collection, but one that is not indexed and cannot contain duplicate values. Let's look at an example again." ] }, { "cell_type": "code", "execution_count": 54, "id": "91daae08-a2a4-4f80-ab22-f9648609ed79", "metadata": {}, "outputs": [], "source": [ "# Create a set\n", "my_set = {3.0, \"Dave\", 1, 2}" ] }, { "cell_type": "code", "execution_count": 55, "id": "1a27627e-7850-4767-b780-dcc375a27220", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "set" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Check the data type\n", "type(my_set)" ] }, { "cell_type": "code", "execution_count": 56, "id": "7cf298c5-6c6a-4e87-9596-de43ace9f708", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'set' object is not subscriptable", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m/var/folders/lp/cjwc88bd3w10sg327y_4ghg0fsk7jj/T/ipykernel_64613/3507569771.py\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# Sets are unindexed. Cannot use indices to get values!\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[0mmy_set\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[0m", "\u001b[0;31mTypeError\u001b[0m: 'set' object is not subscriptable" ] } ], "source": [ "# Sets are unindexed. Cannot use indices to get values!\n", "my_set[1]" ] }, { "cell_type": "code", "execution_count": 57, "id": "4ccf71c8-ad98-47b6-b83c-3795040dfef8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{2, 1, 'Dave', 3.0}\n" ] } ], "source": [ "# Check set contents\n", "print(my_set)" ] }, { "cell_type": "code", "execution_count": 60, "id": "aeb8b847-fc9a-4fb8-bd87-10c802fdf534", "metadata": {}, "outputs": [], "source": [ "# Create another set\n", "my_set = {3.0, \"Dave\", 1, True, \"Dave\"}" ] }, { "cell_type": "code", "execution_count": 62, "id": "3020daff-d622-4e78-8977-772831b71040", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1, 'Dave', 3.0}\n" ] } ], "source": [ "# Check set contents. What???\n", "# Sets do not allow duplicate values, so the name \"Dave\" can only occur once\n", "# We have also guessed that True is converted to 1 and thus does not appear separately!\n", "# Often 0 = False and 1 = True in programming languages\n", "print(my_set)" ] }, { "cell_type": "markdown", "id": "ae61ab00-0fae-4e4b-9021-8e87420b95b8", "metadata": {}, "source": [ "#### F-strings" ] }, { "cell_type": "code", "execution_count": 64, "id": "44b05a94-6838-47b2-a19c-a9416017b1ff", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My name is John.\n" ] } ], "source": [ "# F-strings also use curly braces to enclose variables\n", "print(f\"My name is {first_name}.\")" ] }, { "cell_type": "markdown", "id": "b80fbd36-53c3-4707-8b34-bcb84731f7da", "metadata": {}, "source": [ "## Other notes\n", "\n", "### Looping over dictionary keys and values\n", "\n", "Dictionaries are quite handy data structures in Python, and often there is a need to use loops to find the values for each key in the dictionary. Below is a silly example." ] }, { "cell_type": "code", "execution_count": 65, "id": "94c7cb05-2deb-4c93-b2f6-df74c259a3f1", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The dog goes woof.\n", "The cat goes meow.\n", "The bird goes chirp.\n" ] } ], "source": [ "animal_sound = {\"dog\": \"woof\", \"cat\": \"meow\", \"bird\": \"chirp\"}\n", "\n", "for key, value in animal_sound.items():\n", " print(f\"The {key} goes {value}.\")" ] }, { "cell_type": "markdown", "id": "a47c6b11-3997-4853-855a-a37b65b43260", "metadata": {}, "source": [ "### Checking variables defined in memory\n", "\n", "You can check to see what is defined in the notebook by running `%whos`." ] }, { "cell_type": "code", "execution_count": 66, "id": "730b6ca8-b5a3-4bda-831f-b89fddfa0ef3", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Variable Type Data/Info\n", "--------------------------------------------\n", "add_divide function \n", "add_two function \n", "animal_sound dict n=3\n", "family_name_printer function \n", "family_name_printer2 function \n", "first_name str John\n", "i int 3\n", "key str bird\n", "middle_name str Michael\n", "my_dict dict n=2\n", "my_list list n=4\n", "my_set set {1, 'Dave', 3.0}\n", "my_tuple tuple n=4\n", "name_output str Hello Dave Whipp!\n", "new_number int 6\n", "temperatures list n=4\n", "value str chirp\n", "weather str Windy\n", "weather_conditions list n=4\n" ] } ], "source": [ "%whos" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.8.10" } }, "nbformat": 4, "nbformat_minor": 5 }