{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Introduction to programming for Geoscientists through Python\n", "### [Gerard Gorman](http://www.imperial.ac.uk/people/g.gorman), [Nicolas Barral](http://www.imperial.ac.uk/people/n.barral)\n", "\n", "# Lecture 2: Conditional expressions, loops and lists" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Learning objectives:\n", "\n", "* Know how to form a *condition* using a *boolean expression*.\n", "* Be able to use a conditional expression in combination with a *while-loop* to perform repetitive tasks.\n", "* Be able to store data elements within a Python *list*.\n", "* Be able to use a *for-loop* to iterate, and perform some task, over a *list* of elements." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Boolean expressions\n", "An expression with value *true* or *false* is called a boolean expression. Example expressions for what you would write mathematically as\n", "$C=40$, $C\\ne40$, $C\\ge40$, $C\\gt40$ and $C\\lt40$ are:\n", "\n", "```python\n", "C == 40 # Note: the double == checks for equality!\n", "C != 40 # This could also be written as 'not C == 4'\n", "C >= 40\n", "C > 40\n", "C < 40\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "We can test boolean expressions in a Python shell:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C != 40: True\n", "C < 40: False\n", "C == 41: True\n" ] } ], "source": [ "C = 41\n", "print(\"C != 40: \", C != 40)\n", "print(\"C < 40: \", C < 40)\n", "print(\"C == 41: \", C == 41)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Several conditions can be combined with the special 'and' and 'or' keywords into a single boolean expression:\n", "\n", "* Rule 1: (**C1** *and* **C2**) is *True* only if both **C1** and **C2** are *True*\n", "* Rule 2: (**C1** *or* **C2**) is *True* if either **C1** or **C2** are *True*\n", "\n", "Examples:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "x=0; y=1.2\n", "print (x >= 0 and y < 1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Exercise 2.1: Values of boolean expressions\n", "Add a comment to the code below to explain the outcome of each of the boolean expressions:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Case 1: False\n", "Case 2: False\n", "Case 3: True\n", "Case 4: True\n", "Case 5: False\n", "Case 6: True\n", "Case 7: True\n", "Case 8: False\n", "Case 9: True\n", "Case 10: False\n", "Case 11: False\n", "Case 12: True\n", "Case 13: False\n", "Case 14: True\n" ] } ], "source": [ "C = 41\n", "\n", "print(\"Case 1: \", C == 40)\n", "print(\"Case 2: \", C != 40 and C < 41)\n", "print(\"Case 3: \", C != 40 or C < 41)\n", "print(\"Case 4: \", not C == 40)\n", "print(\"Case 5: \", not C > 40)\n", "print(\"Case 6: \", C <= 41)\n", "print(\"Case 7: \", not False)\n", "print(\"Case 8: \", True and False)\n", "print(\"Case 9: \", False or True)\n", "print(\"Case 10: \", False or False or False)\n", "print(\"Case 11: \", True and True and False)\n", "print(\"Case 12: \", False == 0)\n", "print(\"Case 13: \", True == 0)\n", "print(\"Case 14: \", True == 1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Loops\n", "Suppose we want to make a table of Celsius and Fahrenheit degrees:\n", "```\n", " -20 -4.0\n", " -15 5.0\n", " -10 14.0\n", " -5 23.0\n", " 0 32.0\n", " 5 41.0\n", " 10 50.0\n", " 15 59.0\n", " 20 68.0\n", " 25 77.0\n", " 30 86.0\n", " 35 95.0\n", " 40 104.0\n", " ```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "How do we write a program that prints out such a table?\n", "\n", "We know from the last lecture how to make one line in this table:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-20 -4.0\n" ] } ], "source": [ "C = -20\n", "F = 9.0/5*C + 32\n", "print(C, F)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "We can just repeat these statements:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-20 -4.0\n", "-15 5.0\n", "-10 14.0\n", "-5 23.0\n", "0 32.0\n", "5 41.0\n", "10 50.0\n", "15 59.0\n", "20 68.0\n", "25 77.0\n", "30 86.0\n", "35 95.0\n", "40 104.0\n" ] } ], "source": [ "C=-20; F=9.0/5*C+32; print(C,F)\n", "C=-15; F=9.0/5*C+32; print(C,F)\n", "C=-10; F=9.0/5*C+32; print(C,F)\n", "C=-5; F=9.0/5*C+32; print(C,F)\n", "C=0; F=9.0/5*C+32; print(C,F)\n", "C=5; F=9.0/5*C+32; print(C,F)\n", "C=10; F=9.0/5*C+32; print(C,F)\n", "C=15; F=9.0/5*C+32; print(C,F)\n", "C=20; F=9.0/5*C+32; print(C,F)\n", "C=25; F=9.0/5*C+32; print(C,F)\n", "C=30; F=9.0/5*C+32; print(C,F)\n", "C=35; F=9.0/5*C+32; print(C,F)\n", "C=40; F=9.0/5*C+32; print(C,F)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "So we can see that works but its **very boring** to write and very easy to introduce a misprint.\n", "\n", "**You really should not be doing boring repetitive tasks like this.** Spend one time instead looking for a smarter solution. When programming becomes boring, there is usually a construct that automates the writing. Computers are very good at performing repetitive tasks. For this purpose we use **loops**." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## The while loop (and the significance of indentation)\n", "A while loop executes repeatedly a set of statements as long as a **boolean** (i.e. *True* / *False*) condition is *True*\n", "\n", "```\n", "while condition:\n", " \n", " \n", " ...\n", "\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Note that all statements to be executed within the loop must be indented by the same amount! The loop ends when an unindented statement is encountered.\n", "\n", "At this point it is worth noticing that **blank spaces may or may not be important** in Python programs. These statements are equivalent (blanks do not matter):" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v0=3\n", "v0 = 3\n", "v0= 3\n", "# The computer does not care but this formatting style is\n", "# considered clearest for the human reader.\n", "v0 = 3" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Here is a while loop example where blank spaces really do matter:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n" ] } ], "source": [ "counter = 0\n", "while counter <= 10:\n", " counter = counter + 1\n", "print(counter)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Let's take a look at what happens when we forget to indent correctly:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "IndentationError", "evalue": "expected an indented block (, line 3)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m counter = counter + 1\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n" ] } ], "source": [ "counter = 0\n", "while counter <= 10:\n", "counter = counter + 1\n", "print(counter)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Let's use the while loop to create the table above:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-20 -4.0\n", "-15 5.0\n", "-10 14.0\n", "-5 23.0\n", "0 32.0\n", "5 41.0\n", "10 50.0\n", "15 59.0\n", "20 68.0\n", "25 77.0\n", "30 86.0\n", "35 95.0\n", "40 104.0\n" ] } ], "source": [ "C = -20 # Initialise C\n", "dC = 5 # Increment for C within the loop\n", "while C <= 40: # Loop heading with condition\n", " F = (9.0/5)*C + 32 # 1st statement inside loop\n", " print(C, F) # 2nd statement inside loop\n", " C = C + dC # Increment C for the next iteration of the loop." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Exercise 2.2: Make a Fahrenheit-Celsius conversion table\n", "Write a program that prints out a table with Fahrenheit degrees 0, 10, 20, ..., 100 in the first column and the corresponding Celsius degrees in the second column.\n", "\n", "Hint: $C = \\frac{5}{9}(F-32)$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Exercise 2.3: Write an approximate Fahrenheit-Celsius conversion table\n", "Many people use an approximate formula for quickly converting Fahrenheit ($F$) to Celsius ($C$) degrees:

\n", "$C \\approx \\hat{C} = \\frac{F − 30}{2}$

\n", "Modify the program from the previous exercise so that it prints three columns: $F$, $C$, and the approximate value $\\hat{C}$." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Lists\n", "So far, one variable has referred to one number (or string). Sometimes however we naturally have a collection of numbers, say\n", "degrees −20, −15, −10, −5, 0, ..., 40. One way to store these values in a computer program would be to have one variable per value, i.e." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "C1 = -20\n", "C2 = -15\n", "C3 = -10\n", "# ...\n", "C13 = 40" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "This is clearly a terrible solution, particularly if we have lots of values. A better way of doing this is to collect values together in a list:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "C = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Now there is just one variable, **C**, holding all the values. Elements in a list are accessed via an index. List indices are always numbered as 0, 1, 2, and so forth up to the number of elements minus one:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "6\n", "-3.5\n", "3\n" ] } ], "source": [ "mylist = [4, 6, -3.5]\n", "print(mylist[0])\n", "print(mylist[1])\n", "print(mylist[2])\n", "print(len(mylist)) # length of list" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Here are a few example of operations that you can perform on lists:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-10, -5, 0, 5, 10, 15, 20, 25, 30, 35]\n" ] } ], "source": [ "C = [-10, -5, 0, 5, 10, 15, 20, 25, 30]\n", "C.append(35) # add new element 35 at the end\n", "print(C)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]\n" ] } ], "source": [ "C=C+[40,45] # And another list to the end of C\n", "print(C)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]\n" ] } ], "source": [ "C.insert(0, -15) # Insert -15 as index 0\n", "print(C)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-15, -10, 0, 5, 10, 15, 20, 25, 30, 35, 40, 45]\n" ] } ], "source": [ "del C[2] # delete 3rd element\n", "print(C)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-15, -10, 5, 10, 15, 20, 25, 30, 35, 40, 45]\n" ] } ], "source": [ "del C[2] # delete what is now 3rd element\n", "print(C)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n" ] } ], "source": [ "print(len(C)) # length of list" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "print(C.index(10)) # Find the index of the list with the value 10" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "print(10 in C) # True only if the value 10 is stored in the list" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "45\n" ] } ], "source": [ "print(C[-1]) # The last value in the list." ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "40\n" ] } ], "source": [ "print(C[-2]) # The second last value in the list." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "You can also extract sublists using \":\"" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[20, 25, 30, 35, 40, 45]\n" ] } ], "source": [ "print(C[5:]) # From index 5 to the end of the list." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[20, 25]\n" ] } ], "source": [ "print(C[5:7]) # From index 5 up to, but not including index 7." ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[30, 35, 40]\n" ] } ], "source": [ "print(C[7:-1]) # From index 7 up to the second last element." ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-15, -10, 5, 10, 15, 20, 25, 30, 35, 40, 45]\n" ] } ], "source": [ "print(C[:]) # [:] specifies the whole list." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "You can also unpack the elements of a list into seperate variables:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Moe Larry Curly\n" ] } ], "source": [ "somelist = ['Curly', 'Larry', 'Moe']\n", "stooge1, stooge2, stooge3 = somelist\n", "print(stooge3, stooge2, stooge1)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Exercise 2.4: Store odd numbers in a list\n", "\n", "Step 1: Write a program that generates all odd numbers from 1 to *n*. Set *n* in the beginning of the program and use a while loop to compute the numbers. (Make sure that if *n* is an even number, the largest generated odd number is *n*-1.).\n", "\n", "Step 2: Store the generated odd numbers in a list. Start with an empty list and use the same while loop where you generate each odd number, to append the new number to the list.\n", "\n", "Finally, print the list elements to the screen." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## For loops\n", "We can visit each element in a list and process the element with some statements using a *for* loop, for example:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "list element: 0\n", "list element: 10\n", "list element: 20\n", "list element: 40\n", "list element: 100\n", "The degrees list has 5 elements\n" ] } ], "source": [ "degrees = [0, 10, 20, 40, 100]\n", "for C in degrees:\n", " print('list element:', C)\n", "print('The degrees list has', len(degrees), 'elements')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Notice again how the statements to be executed within the loop must be indented! Let's now revisit the conversion table example using the *for* loop:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-20 -4.0\n", "-15 5.0\n", "-10 14.0\n", "-5 23.0\n", "0 32.0\n", "5 41.0\n", "10 50.0\n", "15 59.0\n", "20 68.0\n", "25 77.0\n", "30 86.0\n", "35 95.0\n", "40 104.0\n" ] } ], "source": [ "Cdegrees = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]\n", "for C in Cdegrees:\n", " F = (9.0/5)*C + 32\n", " print(C, F)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "We can easily beautify the table using the printf syntax that we encountered in the last lecture:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " -20 -4.0\n", " -15 5.0\n", " -10 14.0\n", " -5 23.0\n", " 0 32.0\n", " 5 41.0\n", " 10 50.0\n", " 15 59.0\n", " 20 68.0\n", " 25 77.0\n", " 30 86.0\n", " 35 95.0\n", " 40 104.0\n" ] } ], "source": [ "for C in Cdegrees:\n", " F = (9.0/5)*C + 32 \n", " print('%5d %5.1f' % (C, F))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "It is also possible to rewrite the *for* loop as a *while* loop, i.e.,\n", "\n", "```\n", "for element in somelist:\n", " # process element\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "can always be transformed to a *while* loop\n", "```\n", "index = 0\n", "while index < len(somelist):\n", " element = somelist[index]\n", " # process element\n", " index += 1\n", " ```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Taking the previous table example:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " -20 -4.0\n", " -15 5.0\n", " -10 14.0\n", " -5 23.0\n", " 0 32.0\n", " 5 41.0\n", " 10 50.0\n", " 15 59.0\n", " 20 68.0\n", " 25 77.0\n", " 30 86.0\n", " 35 95.0\n", " 40 104.0\n" ] } ], "source": [ "Cdegrees = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]\n", "index = 0\n", "while index < len(Cdegrees):\n", " C = Cdegrees[index]\n", " F = (9.0/5)*C + 32\n", " print('%5d %5.1f' % (C, F))\n", " index += 1" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Rather than just printing out the Fahrenheit values, let's also store these computed values in a list of their own:" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-4.0, 5.0, 14.0, 23.0, 32.0, 41.0, 50.0, 59.0, 68.0, 77.0, 86.0, 95.0, 104.0]\n" ] } ], "source": [ "Cdegrees = [-20, -15, -10, -5, 0, 5, 10, 15, 20, 25, 30, 35, 40]\n", "Fdegrees = [] # start with empty list\n", "for C in Cdegrees:\n", " F = (9.0/5)*C + 32\n", " Fdegrees.append(F) # add new element to Fdegrees\n", "print(Fdegrees)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "In Python *for* loops usually loop over list values (elements), i.e.,\n", "\n", "```\n", "for element in somelist:\n", " ...process variable element\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "However, we can also loop over list indices:\n", "\n", "```\n", "for i in range(0, len(somelist), 1):\n", " element = somelist[i]\n", " ... process element or somelist[i] directly\n", " ``` " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The statement *range(start, stop, inc)* generates a list of integers *start*, *start+inc*, *start+2\\*inc*, and so on up to, but not including, *stop*. We can also write *range(stop)* as an abbreviation for *range(0, stop, 1)*:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "range(0, 3)\n" ] } ], "source": [ "print(range(3)) # same as range(0, 3, 1)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "range(2, 8, 3)\n" ] } ], "source": [ "print(range(2, 8, 3))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## List comprehensions\n", "Consider this example where we compute two lists in a *for* loop:" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Cdegrees = [-5.0, -4.5, -4.0, -3.5, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5]\n", "Fdegrees = [23.0, 23.9, 24.8, 25.7, 26.6, 27.5, 28.4, 29.3, 30.2, 31.1, 32.0, 32.9, 33.8, 34.7, 35.6, 36.5]\n" ] } ], "source": [ "n = 16\n", "Cdegrees = []; Fdegrees = [] # empty lists\n", "for i in range(n):\n", " Cdegrees.append(-5 + i*0.5)\n", " Fdegrees.append((9.0/5)*Cdegrees[i] + 32)\n", "print(\"Cdegrees = \", Cdegrees)\n", "print(\"Fdegrees = \", Fdegrees)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "As constructing lists is a very common requirement, the above way of doing it can become very tedious to both write and read. Therefore, Python has a compact construct, called list comprehension for generating lists from a *for* loop:" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Cdegrees = [-5.0, -4.5, -4.0, -3.5, -3.0, -2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0, 2.5]\n", "Fdegrees = [23.0, 23.9, 24.8, 25.7, 26.6, 27.5, 28.4, 29.3, 30.2, 31.1, 32.0, 32.9, 33.8, 34.7, 35.6, 36.5]\n" ] } ], "source": [ "n = 16\n", "Cdegrees = [-5 + i*0.5 for i in range(n)]\n", "Fdegrees = [(9.0/5)*C + 32 for C in Cdegrees]\n", "print(\"Cdegrees = \", Cdegrees)\n", "print(\"Fdegrees = \", Fdegrees)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "The general form of a list comprehension is:\n", "```\n", "somelist = [expression for element in somelist]\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Exercise 2.5: Repeat the previous exercise using: a for loop, list comprehension and the range function" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# Using for loop" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# Using list comprehension" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# Using the function range" ] } ], "metadata": { "celltoolbar": "Slideshow", "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.2" } }, "nbformat": 4, "nbformat_minor": 1 }