{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Variables in Python\n", "--------------------------------------------\n", "\n", "[[back to top](#top)]\n", "\n", " A variable is a name used to reference a value for later use. Think of a variable as a name pointing to some object. Assigning a value to a variables in Python is done with the assignment operator (=). For example, the following line assigns the value 2 to the the variable x." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "x = 2" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "# Comments begin with the pound sign and continue to the end of the line\n", "# The built-in print function will display a value on the screen\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Assigning variables to values is the primary way that data is stored and manipulated in Python code.\n", "\n", " Variable names must start with a letter and can contain letters, numbers, and the underscore character ( \\_ ). The usual convention for variable names is to use lowercase letters with underscores to seperate words (e.g. my\\_favorite\\_number = 2). In addition, there are a number of keywords in Python that are used by the interpreter. So you'll want to avoid using these keywords as variable names. Namely,\n", "\n", " False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield are keywords to avoid. Now that we know variables are names that reference a value, let's look at some of the types of values that we have in Python." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Survey of some built-in types\n", "----------------------------------------------------------------\n", "\n", "[[back to top](#top)]\n", "\n", " Every value in Python has a type associated with it (*NOTE*: If you ever want to know the type of something, you can use the built-in type function)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Different types have different allowed operations and functionality. For example, as we'll discuss later, the addition operator is defined for integer types." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "3\n" ] } ], "source": [ "a = 1\n", "b = 2\n", "print(type(a))\n", "print(type(b))\n", "# Use addition operator between two integers\n", "print(a + b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " and an uppercase method is defined for string types" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "MADISON, WI\n" ] } ], "source": [ "c = 'Madison, WI'\n", "print(type(c))\n", "# Use the string uppercase method to make every character uppercase\n", "print(c.upper())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The most-commonly used built-in types in Python can be grouped into two categories: simple and compound." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simple types\n", "\n", "[[back to top](#top)]\n", "\n", " The \"simple\" types consist of integers (int), floating-point numbers (float), complex numbers (complex), boolean values (bool), and the None type (NoneType)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Integers\n", "\n", "Integers represent whole numbers ( ...,-2, -1, 0, 1, 2,...). Numbers without a decimal point or exponential notation produce integers." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "a = 2\n", "print(type(a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Floating-point numbers\n", "\n", "Floating-point numbers (often called \"floats\") represent real numbers. Number containing a decimal point or exponential notation are used to define floating-point values. " ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "b = 1.5\n", "print(type(b))" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3, 2)" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b.as_integer_ratio()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Exponential notation (e or E) is shorthand for scientific notation. E.g. 7e3 = $7 \\times 10^3$" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7000.0\n", "\n" ] } ], "source": [ "c = 7e3\n", "print(c)\n", "print(type(c))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Complex numbers\n", "\n", "A complex number can be created by including a 'j' or 'J' in a number. The corresponding real and imaginary parts of the complex number can be accessed using real and imag attributes." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "z = 7 + 4.3j\n", "print(type(z))" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7.0" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z.real" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4.3" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z.imag" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Note that the real and imaginary parts for the complex type are floating-point numbers—regardless of whether or not there is a decimal point." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(z.real))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Booleans\n", "\n", "Booleans can take on one of two possible values: True or False. Booleans will be utilized later when we discuss the conditional statements in Python. " ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "n = True\n", "print(type(n))" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "p = False\n", "print(type(p))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Note that bool values *are* case sensitive—the first letter needs to be capitalized." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " #### None type[¶](#None-type)\n", "\n", "The NoneType type represents just a single value: None. None is commonly used to represent un-initialized values. In addition, functions that don't have an explicit return value will implicity return None.\n", "\n", " " ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "z = None\n", "print(type(z))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ### Compound types[¶](#Compound-types)\n", "\n", "[ [back to top](#top) ]\n", "\n", " In addition to int, float, complex, bool, and NoneType, Python also has several built-in data structures that are used as containers for other types. These \"compound\" types consist of lists (list), tuples (tuple), strings (str), sets (set), and dictionaries (dict).\n", "\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " #### Lists[¶](#Lists)\n", "\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " A list is a *ordered*, *mutable* collection of data (data elements are called \"items\"). We'll discuss mutable vs. immutable objects momentarily. Lists are constructed using square brackets with list items seperated by commas.\n", "\n", " " ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "d = [2.3, 5, -43, 74.7, 5]\n", "print(type(d))" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2.3, 5, -43, 74.7, 5]\n" ] } ], "source": [ "print(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Lists have lots of built-in functionality. For example, You can use the built-in len function to get the number of items in a list" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The list append method can be used to add elements to a list" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2.3, 5, -43, 74.7, 5, 3.1415]\n" ] } ], "source": [ "d.append(3.1415)\n", "print(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The list sort method will sort the items in a list into ascending order" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-43, 2.3, 3.1415, 5, 5, 74.7]\n" ] } ], "source": [ "d.sort()\n", "print(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The list reverse method will reserve the order of a list" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[74.7, 5, 5, 3.1415, 2.3, -43]\n" ] } ], "source": [ "d.reverse()\n", "print(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The list count method counts the number of times an item occurs in a list" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Counts how many times the item 5 occurs in the list d\n", "d.count(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Note that a list can contain any type of object. The types of items in a list need not be homogeneous. For example," ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, False, 23.11, [1, 2, 3], None]\n" ] } ], "source": [ "crazy_list = [1, False, 23.11, [1, 2, 3], None]\n", "print(crazy_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The items in a list can be accessed using **list indexing**. Indexing a list consists of adding the item index in square brackets after a list. It's also important to note that in Python *list indices begin with zero*. So the first item in a list has the index 0, the second item has the index 1, and so on. For example" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "d = [2.3, 5, -43, 74.7, 5]" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.3" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[0]" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[1]" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-43" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Python also supports negative indexing. This has the effect of starting from the end of the list. So the last item in a list has an idex of -1, the second to last item has an index of -2, and so on. If you are familiar with R or other languages that use a different convention for negative indices then this is important to note." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[-1]" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "74.7" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[-2]" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-43" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d[-3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " In addition to indexing a list to get back list items, you can using **slicing** to get back a sub-list. The syntax for list slicing is given by\n", "\n", " list\\_object[starting\\_index : stopping\\_index : index\\_step\\_size] As an example we could use 0:3 which would give us all the elements starting with the zero index item and up to but not including the third index item." ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2.3, 5, -43, 74.7, 5]\n", "[2.3, 5, -43]\n" ] } ], "source": [ "print(d)\n", "print(d[0:3]) # This will return the sub-list starting from the index 0 up to, but not including, the index 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " By default, the starting index is 0 (at the beginning of the list), the stopping index corresponds to the last item, and the step size is 1." ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2.3, 5, -43, 74.7, 5]\n", "[2.3, 5, -43, 74.7]\n", "[5, -43, 74.7, 5]\n", "[2.3, -43, 5]\n" ] } ], "source": [ "print(d)\n", "print(d[:4]) \n", "print(d[1:])\n", "print(d[::2])" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2.3]\n" ] } ], "source": [ "print(d[:-4]) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Tuples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Tuples are *ordered*, *immutable* collection of data. Tuples can be construced in a similar way as lists, but with parenthesis instead of square brackets." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "f = (83.2, -4 ,5e7)\n", "print(type(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " One weird quirk is that a tuple with a single item needs to have a trailing comma, e.g." ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(83.2,)\n", "\n" ] } ], "source": [ "f = (83.2,)\n", "print(f)\n", "print(type(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " If this trailing comma is left out, then python will assume you don't actually want a tuple and will assign whatever the single item is in parenthesis to your variable. For example," ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "83.2\n", "\n" ] } ], "source": [ "f = (83.2)\n", "print(f)\n", "print(type(f))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The number of items in a tuple can be found using the built-in len function, and they support indexing and slicing similar to lists." ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 3.2, False, 222, None)\n", "5\n", "(3.2, False, 222)\n" ] } ], "source": [ "g = (1, 3.2, False, 222, None)\n", "print(g)\n", "print(len(g))\n", "print(g[1:4])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Mutable vs. immutable objects\n", "\n", "Up to this point, it may seem like lists and tuples aren't any different. They are both containers that can hold items, you can access the items with an index, etc. How are these things different? One of the main differences between the list type and the tuple type is that **lists are mutable, while tuples are immutable**. Once created, the value of a mutable object can be changed, while immutable objects cannot be changed once created. Let's look at an example." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Let's create a list" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "g = [1, 2, 3, 4]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Now let's modify the list in place. That is, let's try to change the items in the list without creating a whole new list." ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[99, 2, 3, 4]\n" ] } ], "source": [ "g[0] = 99\n", "print(g)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " As you can see, there wasn't a problem here. We assigned to the variable g the list [1, 2, 3, 4], then modified the zeroth item in g to be the number 99. Let's try the same thing with a tuple now." ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2, 3, 4)\n" ] } ], "source": [ "g = (1, 2, 3, 4)\n", "print(g)" ] }, { "cell_type": "code", "execution_count": 42, "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\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mg\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m99\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mg\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: 'tuple' object does not support item assignment" ] } ], "source": [ "g[0] = 99\n", "print(g)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " We got this error because tuples are immutable—they can't be modified once they're created." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Be careful though. Items within the tuple may be references to mutable objects." ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2, ['a', 'b', 'c'], 4)\n", "(1, 2, ['a', 'scary new data', 'c'], 4)\n" ] } ], "source": [ "f = ['a', 'b', 'c']\n", "g = (1, 2, f, 4)\n", "print(g)\n", "f[1] = 'scary new data'\n", "print(g)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Sets\n", "\n", "A set is an unordered collection with no duplicate elements. They are constructed with comma separated items in curly brackets, {}. " ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1, 2, 3, 4}\n" ] } ], "source": [ "s = {1, 2, 3, 4, 2, 2, 3, 1}\n", "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Set objects support mathematical operations like union, intersection, difference, and symmetric difference. Set unions are done with the | operator or using the set union method. For example," ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1, 2, 3, 4, 5, 6}\n", "{1, 2, 3, 4, 5, 6}\n" ] } ], "source": [ "s1 = {1, 2, 3, 4}\n", "s2 = {3, 4, 5, 6}\n", "print(s1 | s2)\n", "print(s1.union(s2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Set intersections are done with the & operator or using the set intersection method. For example," ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{3, 4}\n", "{3, 4}\n" ] } ], "source": [ "print(s1 & s2)\n", "print(s1.intersection(s2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " As always, the number of items in a set can be found using the len function." ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(s1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Strings\n", "\n", "Strings are used to represent a sequence of characters. Strings can be created by enclosing characters in either single or double quotes. " ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g = 'pizza'\n", "type(g)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "h = \"jamesbond007\"\n", "type(h)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Strings can also be index just like lists and tuples." ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'j'" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "h[0]" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'d'" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "h[-4]" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'esb'" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "h[3:6]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " You can also find out how many characters are in a string using the len() function" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(h)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Dictionaries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Dictionaries are unordered containers for key-value pairs. That is, dictionaries store a mapping for each key to an associated value. Dictionaries are created by placing comma-separated key-value pairs inside curly brackets {}. For a key-value pair, the key and corresponding value are seperated by a colon, :.\n", "\n", " An example might help..." ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "k = {'MJ': 23, 'longitude': -53.2, 'city': 'Tokyo'}\n", "print(type(k))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Here, the dictionary keys are 'MJ', 'longitude', and 'Tokyo', with corresponding values of 23, -53.2, and 'Tokyo'. In a similar way to sequences, you can access the values in a dicionary by giving the corresponding key in square brackets.\n", "\n", " " ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "23" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "k['MJ']" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-53.2" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "k['longitude']" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Tokyo'" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "k['city']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The keys in a dictionary can be obtained by using the dictionary keys method" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys(['MJ', 'longitude', 'city'])" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "k.keys()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The values in a dictionary can be obtained by using the dictionary values method" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_values([23, -53.2, 'Tokyo'])" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "k.values()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The size of a dictionary (the number of key-value pairs it contains) can be found with the built-in len() function." ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(k)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " It is important to note that in the previous example all the keys were strings, but this doesn't have to be the case. The only restriction on keys is that they be hashable. This means that keys must be an *immutable type*. For example, the following is also an acceptable dictionary." ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "m = {-23: [1, 2, 3, 4], 'desk': 3.2, 7.12: (-3, 'bird')}" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m[-23]" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.2" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m['desk']" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(-3, 'bird')" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m[7.12]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Let see what happens if I try to contruct a dictionary with a list (a mutable object) as a key " ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unhashable type: 'list'", "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[0;32m----> 1\u001b[0;31m \u001b[0mn\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;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'WOO'\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: unhashable type: 'list'" ] } ], "source": [ "n = {[1, 2, 3]: 'WOO'}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Whoops lists are mutable! So remember to always use immutable objects for dictionary keys!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Other types\n", "\n", "Other useful types can be found in the collections module in the Python standard library.\n", "\n", " * namedtuple\n", " * Counter\n", " * OrderedDict\n", " * defaultdict\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Type casting\n", "------------------------------\n", "\n", "[[back to top](#top)] " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Sometimes it can be useful to change the type of an object. In Python, this so-called \"type-casting\" can be accomplished using several built-in functions:\n", "\n", " * int()—casts to integer\n", " * float()—casts to float\n", " * str()—casts to string\n", " * bool()—casts to boolean\n", " Let's see it in action" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Casting integers to floats is fairly straight-forward" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.0\n", "\n" ] } ], "source": [ "a = float(2)\n", "print(a)\n", "print(type(a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " When casting a float to an integer, Python will round down to the nearest integer" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "78\n", "\n" ] } ], "source": [ "b = int(78.81)\n", "print(b)\n", "print(type(b))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " You can even cast a number to a string! (This effectively just returns the number in quotes)" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-1324.1\n", "\n" ] } ], "source": [ "c = str(-1324.1)\n", "print(c)\n", "print(type(c))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Things get a little less straight-forward when casting to bool. Below are the bool casting rules:\n", "\n", " * Numbers: Zero of any numeric type, for example, 0, 0.0, 0+0j, cast to False. Everything else casts to True.\n", " * Lists: An empty list, [], will cast to False. Non-empty lists casts to True.\n", " * Tuples: An empty tuple, (), will cast to False. Non-empty tuples casts to True.\n", " * Strings: An empty string, '', will cast to False. Non-empty strings casts to True.\n", " * Dictionaries: The empty dictionary, {}, casts to False. Everything else casts to True.\n", " * NoneType: None casts to False.\n", " Here are some examples: " ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(0)" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(-178.3)" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool([])" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool([1, 2, 3, 4, 5])" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool({})" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool({'key': 'value'})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Arithmetic operations\n", "------------------------------------------------\n", "[[back to top](#top)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The following operations are supported for several of the built-in types in Python:\n", "\n", " * Addition: +\n", " * Subtraction: -\n", " * Multiplication: *\n", " * Division: /\n", " * Floored division: //\n", " * Exponentiation: **\n", " Some examples with numerical types..." ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1+1" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10-3" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "15.0" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3*5.0" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.5" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5/2" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5//3" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "81.0" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "9.0**2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " When performing arithmetic operations, the type of numbers *does* matter. According to the [Python Software Foundation](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex):\n", "\n", " \n", "> Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the 'narrower' type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex.\n", "> \n", "> So, when you have a arithmetic operation with mixed numeric types, say adding an int and a float, the result will have the 'widest' type of the two numbers, in this case float. The convention is int is the most narrow type, float is wider than int, and complex is wider than float." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Some of these arithmetic operations are even defined for compound types. For example, list addition" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5, 6]\n" ] } ], "source": [ "list1 = [1, 2, 3, 4]\n", "list2 = [5, 6]\n", "summed_list = list1 + list2\n", "print(summed_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " tuple addition" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2, 3, 4, 5, 6)\n" ] } ], "source": [ "tup1 = (1, 2, 3, 4)\n", "tup2 = (5, 6)\n", "summed_tuple = tup1 + tup2\n", "print(summed_tuple)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " and string addition are all defined " ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'My name is James'" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'My name is ' + 'James'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Comparison operations\n", "------------------------------------------------\n", "\n", "[[back to top](#top)]\n", "\n", " In addition to using arithmetic operations to combine objects, it's also using to compare the value of objects as well. The comparison operators defined in Python are:\n", "\n", " * '==' (equal)\n", " * '!=' (not Equal)\n", " * '<' (less than)\n", " * '>' (greater than)\n", " * '<=' (less than or equal to)\n", " * '>=' (greater than or equal to)\n", " A boolean value of either True or False will be returned appropreiately from a comparison operator. For example," ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 == 2" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 > 0.5" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 < 0.5" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Python also can handle comparing different types to one another. In particular, floats and integers are compared in a natural way" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 == 2.0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Multiple comparison can also be made at once." ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "a = 25\n", "print(15 < a < 30) # Checks whether or not a is greater than 15 and less thatn 30" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Boolean values can also be combined using the and, or, or not keywords." ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a < 30) and (a > 15)" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a < 30) and (a == 25)" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a > 30) or (a == 25)" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a > 30) or (a < 15)" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "not (a == 25)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Control flow\n", "------------------------------\n", "\n", "[[back to top](#top)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Up to this point, we've explored some of the built-in types in Python and how to store values (i.e. variables) for later use. Now we'll look at using these building blocks to make a dynamic program." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conditional statements\n", "\n", "[[back to top](#top)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Conditional statements are used to execute a piece of code based on if some condition is met. Let's look at some examples." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### If statements\n", "\n", "If statements are used to execute a piece of code if a condition is met. The basic structure of an if statement is shown below." ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Condition is True\n" ] } ], "source": [ "condition = True\n", "if condition:\n", " print('Condition is True')" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [], "source": [ "condition = False\n", "if condition:\n", " print('Condition is True')" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Condition is True\n", "10\n" ] } ], "source": [ "a = 10\n", "if a < 20:\n", " print('Condition is True')\n", " b = 10\n", " print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Multiple conditions can be combined into a more complex condition using the and / or keywords.\n", " The and keyword requires that both conditions are True" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Both conditions are True\n" ] } ], "source": [ "b = 5\n", "c = 15\n", "if b < 10 and c < 20:\n", " print('Both conditions are True')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The or keywords requires that at least one of the conditions be True. For example, below the first condition is True, but the second is False.\n", "\n", " " ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "At least one condition is True\n" ] } ], "source": [ "if b < 10 or c < 10:\n", " print('At least one condition is True')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### If-else statements\n", "\n", "Sometimes more complicated situations can arise in which you would like to have, depending on if a condition is met, different pieces of code run. This leads us to the if-else statement. If-else statements consist of an if statement followed by a piece of code that will be executed if the if-statement condition is not met." ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "b is not 5\n" ] } ], "source": [ "b = 4\n", "if b == 5:\n", " print('b is 5')\n", "else:\n", " print('b is not 5')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Elif statements\n", "\n", "Sometimes your might like to have many if statements you would like to check" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Value neither less than or greater than 10\n" ] } ], "source": [ "value = 10\n", "if value < 10:\n", " print('Value was less than 10')\n", "elif value > 10:\n", " print('Value was greater than 10')\n", "else:\n", " print('Value neither less than or greater than 10')" ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.0 is zero\n" ] } ], "source": [ "x = 0.\n", "if x == 0:\n", " print(x, \"is zero\")\n", "elif x > 0:\n", " print(x, \"is positive\")\n", "elif x < 0:\n", " print(x, \"is negative\")\n", "else:\n", " print(x, \"is unlike anything I've ever seen...\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loops\n", "\n", "[[back to top](#top)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Looping in Python is done via for-loops and while-loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### For loops[¶](#For-loops)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The basic syntax of a for loop is shown below.\n", "\n", "We've run into several iterables already: lists, tuples, strings, and dictionaries.\n", "Below we iterate over a list." ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "for item in [0, 1, 2, 3, 4, 5]:\n", " print(item)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Below we iterate over a tuple." ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "3.2\n", "this is a string\n" ] } ], "source": [ "for item in (False, 3.2, 'this is a string'):\n", " print(item)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Below we iterate over a string." ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "P\n", "y\n", "t\n", "h\n", "o\n", "n\n" ] } ], "source": [ "for letter in 'Python':\n", " print(letter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " The built-in range function creates a list of numbers. You specify the first number and the terminating number" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "10\n", "11\n", "12\n", "13\n", "14\n", "15\n", "16\n", "17\n", "18\n", "19\n" ] } ], "source": [ "for item in range(3, 20):\n", " print(item)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The built-in enumerate function returns an iterable that contains tuples. The first element of the tuple is the index of our original iterable and the second element of the tuple is the value at that index." ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 False\n", "1 3.2\n", "2 this is a string\n" ] } ], "source": [ "tup = (False, 3.2, 'this is a string')\n", "for index, value in enumerate(tup):\n", " print(index, value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For dictionaries it is possible to iterate over the keys" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "MJ 23\n", "longitude -53.2\n", "city Tokyo\n" ] } ], "source": [ "k = {'MJ': 23, 'longitude': -53.2, 'city': 'Tokyo'}\n", "for key in k: # for key in k.keys()\n", " print(key, k[key])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to iterate over key-value pairs" ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "MJ 23\n", "longitude -53.2\n", "city Tokyo\n" ] } ], "source": [ "for key, value in k.items():\n", " print(key, value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### While loops\n", "\n", "Loop over code until condition is evaluated to False" ] }, { "cell_type": "code", "execution_count": 108, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "n = 0\n", "while n < 10:\n", " print(n)\n", " n = n + 1 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### List comprehension" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " One way to create a list is to use the append method inside a for loop\n", "\n", " " ] }, { "cell_type": "code", "execution_count": 109, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 4, 9, 16]\n" ] } ], "source": [ "squared_list = []\n", "for i in range(5):\n", " value = i**2\n", " squared_list.append(value)\n", "print(squared_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " While this approach gets the job done, it's a little too verbose. Python has another, less verbose, syntax for creating lists—list comprehensions" ] }, { "cell_type": "code", "execution_count": 110, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 4, 9, 16]\n" ] } ], "source": [ "squared_list = [i**2 for i in range(5)]\n", "print(squared_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Functions\n", "------------------------\n", "\n", "[[back to top](#top)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Functions allow for the consolidation of several pieces of code into a single reusable object. The basic syntax for defining a function is shown below." ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [], "source": [ "def add(value1, value2):\n", " total = value1 + value2\n", " return total" ] }, { "cell_type": "code", "execution_count": 112, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n" ] } ], "source": [ "print(add(4, 5))" ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "800.0\n" ] } ], "source": [ "print(add(1e3, -200))" ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Pythonrules\n" ] } ], "source": [ "print(add('Python', 'rules'))" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [], "source": [ "def change_zeroth_item_to_3(parameter):\n", " parameter[0] = 3\n", " return parameter" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 2, 3, 4, 5]" ] }, "execution_count": 116, "metadata": {}, "output_type": "execute_result" } ], "source": [ "change_zeroth_item_to_3([1, 2, 3, 4, 5])" ] } ], "metadata": { "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.6.7" } }, "nbformat": 4, "nbformat_minor": 1 }