{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Chapter 5: 'Structure and Control'\n", "\n", "Loops are often used to iterate through a sequeunce, list, dictionary, tuple, or an array. Conditional statements, often using booleans, can be employed to determine when a specific code block should be executed (or skipped).\n", "- `For` and `while` loops are used to iterate over an *indented* block of code \n", "- Conditional statements, or `if` statements are often used to determine whether a block of code should be executed or not\n", "- There are also additional use commands in Python that allows the programmer to control a loop or conditional statement\n", "\n", "**Before starting:** Make sure that you open up a Jupyter notebook session using OnDemand so you can interactively follow along today! Also, be sure you have copied this script into your atmos_5340/module_3 subdirectory!\n", "\n", "

" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# 5.1 Interactive input from terminal\n", "# try this" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "Enter a floating point number: 2\n" ] }, { "data": { "text/plain": [ "'2'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "first = input('Enter a floating point number: ')\n", "first" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#what type is first?\n", "type(first)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.0" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# if you want it to be a float then\n", "first_float = float(first)\n", "first_float" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Conditional statements\n", "\n", "Conditional statements are used to execute a specific block of code, if specific conditions are met. Conditional statements almost always start with an *if construct*.\n", "\n", " if condition is met:\n", " execute the following lines of code\n", " \n", " #end of if statement block\n", "\n", "Generally conditional statements are checked using mathematical logical conditions.\n", "\n", "Recall: \n", "\n", ">- Equals: a == b\n", ">- Not Equals: a != b\n", ">- Less than: a < b\n", ">- Less than or equal to: a <= b\n", ">- Greater than: a > b\n", ">- Greater than or equal to: a >= b\n", "\n", "If statements can also be embedded with Python loops, which we will go over later in this lecture...\n", "\n", "For cases where there are multiple conditions, an *if else* `elif` syntax can be added to the first condition:\n", "\n", "if condition is met:\n", "\n", " execute the following lines of code\n", "\n", "if else do we meet this condition?:\n", "\n", " execute this block\n", "\n", "if else do we meet this condition?:\n", "\n", "execute this block\n", " \n", "#end of if statement block\n", "\n", "
\n", "\n", "**Note** There are no limits to how many elif statements can be used!\n", "\n", "Finally, an `else` construct can be used at the end of if conditional statement to execute lines of code for cases where none of the prior conditions are met. For example\n", "\n", " if condition is met:\n", " execute the following lines of code\n", " else:\n", " execute this line of code instead\n", " \n", " #end of if statement block\n", "\n", "\n", "
\n", "\n", "Lets look at some lines of *actual* python code that utilizes conditional statements like the ones we went over above! \n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The temperature is at or below freezing\n" ] } ], "source": [ "temp = 30\n", " \n", "if temp <= 32:\n", " print('The temperature is at or below freezing')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What happens here? Next, try-\n", "\n", "
" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "temp = 50\n", " \n", "if temp <= 32:\n", " print('The temperature is at or below freezing')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What happens here?\n", "\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "Since our temperature variable 'temp' does not meet the criteria of our `if` statement, it skips the lines of code within our `if` statement block.\n", "\n", "❗❗❗❗ Do not forget to add a colon `:` after each `if`, `elif`, and `else` construct\n", "\n", "

\n", "\n", "Here is an example of an `if` statement with a else construct:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The temperature is at or below freezing\n" ] } ], "source": [ "temp = 30\n", "\n", "if temp <= 32:\n", " print('The temperature is at or below freezing')\n", "else:\n", " print('The temperature is above freezing!')\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Try changing the values of our temperature variable 'temp' and see what happens**\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "And here is an example of an `if` statement with an if else construct. What do you think will happen here?\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Slight chance of thunderstorms today\n" ] } ], "source": [ "#Thunderstorm probability\n", "tstorm = 30\n", " \n", "if 20 >= tstorm:\n", " print('Little to no chance of thunderstorms today')\n", "elif 20 < tstorm <= 40:\n", " print('Slight chance of thunderstorms today')\n", "elif 40 < tstorm <= 60:\n", " print('Chance of thunderstorms today')\n", "elif 60 < tstorm:\n", " print('Thunderstorms are likely today')\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "**Try changing the values of our thunderstorm probability variable 'tstorm' and see what happens**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "Conditional statements can also be written as a single line. This is only recommended if the code within the if/else statement is particurly short.\n", "\n", " [expression 1] if condition else [expression 2]\n", " \n", "For example:\n", "\n", " \n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "temperature at or below freezing\n" ] } ], "source": [ "temp = 30\n", "print('temperature at or below freezing') if temp <= 32 else print('Temperature above freezing')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "\n", "# Loops\n", "\n", "There are two types of loops used by Python. This includes `for` and `while` loops.\n", "\n", "`for` loops always require an iterable object and has a similar syntax as a conditional statement. \n", "\n", " for var in iterable object:\n", " do stuff in\n", " this line for \n", " each iteration \n", " that we are \n", " looping through\n", " \n", " #end of for loop\n", " \n", "\n", "In this syntax *iterable object* represents an iterable object that is being loop through, while *var* hold the value of the \n", "current value of the iterable object. The python code block within the `for` loop will be performed for each iteration being performed. \n", "The number of iterations will be equal to the number of elements within the iterable object. \n", "\n", "Lets look at an example:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "36\n", "38\n", "40\n", "44\n", "48\n", "53\n", "60\n", "62\n", "64\n", "65\n", "65\n", "63\n", "60\n", "55\n", "50\n" ] } ], "source": [ "temp = [36,38,40,44,48,53,60,62,64,65,65,63,60,55,50] \n", "\n", "for T in temp:\n", " print(T)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we run this block of code, Python iterate through each element within our object 'temp'. In this loop we have told Python to run the print statement for each iterable element (T) in temperature. \n", "\n", "

\n", "You can also can also use a pre-defined range object as a iterable object. \n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Counting.... 0\n", "Counting.... 1\n", "Counting.... 2\n", "Counting.... 3\n", "Counting.... 4\n", "Counting.... 5\n", "Counting.... 6\n", "Counting.... 7\n", "Counting.... 8\n", "Counting.... 9\n" ] } ], "source": [ "for c in range(0,10):\n", " print('Counting.... '+str(c))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "Sometimes, it is useful to keep track of which iteration we are working on when looping through a variable using the `enumerate` command. Personally, I use this in most of my Python code, especially when I am trouble shooting bugs! For example, there may be a specific iteration where my code breaks, so its always useful to know where this happens!" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 36\n", "1 38\n", "2 40\n", "3 44\n", "4 48\n", "5 53\n", "6 60\n", "7 62\n", "8 64\n", "9 65\n", "10 65\n", "11 63\n", "12 60\n", "13 55\n", "14 50\n" ] } ], "source": [ "temperature = [36,38,40,44,48,53,60,62,64,65,65,63,60,55,50] \n", " \n", "for t, temp in enumerate(temperature):\n", " print(t,temp)\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "# Do it yourself #1\n", "\n", "Write a 'for' loop, which goes through the temperature array below, and prints out whether our temperature is above our below freezing. Have this loop print out the temperature, and in the same statement if it is above or below freezing. For example:\n", "\n", "`Temperature = 50, it is above freezing!`\n", "\n", "Use the temperature array provided below, or if you want, make up your own!" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "temperature = [60,61,61,58,55,50,44,37,30,28,26,25,30,36,41,46,48]" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "60\n", "Temperature = 60 it is above freezing\n", "61\n", "Temperature = 61 it is above freezing\n", "61\n", "Temperature = 61 it is above freezing\n", "58\n", "Temperature = 58 it is above freezing\n", "55\n", "Temperature = 55 it is above freezing\n", "50\n", "Temperature = 50 it is above freezing\n", "44\n", "Temperature = 44 it is above freezing\n", "37\n", "Temperature = 37 it is above freezing\n", "30\n", "Temperature = 30 it is below freezing\n", "28\n", "Temperature = 28 it is below freezing\n", "26\n", "Temperature = 26 it is below freezing\n", "25\n", "Temperature = 25 it is below freezing\n", "30\n", "Temperature = 30 it is below freezing\n", "36\n", "Temperature = 36 it is above freezing\n", "41\n", "Temperature = 41 it is above freezing\n", "46\n", "Temperature = 46 it is above freezing\n", "48\n", "Temperature = 48 it is above freezing\n" ] } ], "source": [ "for t in temperature:\n", " print(t)\n", " if t <= 32:\n", " print(\"Temperature = \",t,\"it is below freezing\")\n", " else:\n", " print(\"Temperature = \",t,\"it is above freezing\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "


\n", "\n", "`while` loops are the other looping construct used within Python. This loop runs for as a long as a specific criteria is being met.\n", "\n", " while condition is being met:\n", " execute this code block\n", " \n", " #end while loop\n", " \n", "For example:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-10\n", "-9\n", "-8\n", "-7\n", "-6\n", "-5\n", "-4\n", "-3\n", "-2\n", "-1\n", "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "a = -10\n", "while a < 5:\n", " print(a)\n", " a += 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This block of code will loop through the above code block until the condition a < 5 is met.\n", "\n", "❗❗ Be careful when working with `while` loops as its possible to accidentally create a loop that runs infinitely! I often refer to this as 'hanging' code, which is a common problem, especally with Fortran, which also uses while constructs.\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "a = 3\n", "while a > 5:\n", " print(a)\n", " a = a + 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this `while` loop above set a equal to 6 and switch the less than sign `<` to a greater than sign `>` and then re-run the code.\n", "\n", "**What happens? Why does this loop never stop?** Hit the pause button to stop the loop from running." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "# Other flow control constructs\n", "\n", "Sometimes we may want to control a loop if a specific criteria is met within a loop. This often requires combining conditional and looping constructs.\n", "\n", "For example, we may want to prematurely end an iteration within a loop if a spefific criteria is met:\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 60\n", "1 61\n", "2 61\n", "3 58\n", "4 55\n", "9 28\n", "10 26\n", "11 25\n" ] } ], "source": [ "temperature = [60,61,61,58,55,50,44,37,30,28,26,25]\n", " \n", "for t,temp in enumerate(temperature):\n", " if 50 >= temp >= 30:\n", " continue\n", " print(t,temp)\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, we loop through each element in temperature. For cases where the temperature is less than 50 but greater than 30, the `if` statement condition is triggered. For elements where the `conditional` is met, the `continue` statement within our conditional statement is executed, which tells Python to ignore the lines after the `continue` statement for the iteration we are working on. Think of the use of \"continue\" to be \"go back to the top of the loop\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "The `break` loop control statement can be used to prematurely exit a `for` or `while` loop:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "60\n", "61\n", "61\n", "58\n", "55\n", "50\n", "44\n", "37\n", "Temperature below freezing: 25\n" ] } ], "source": [ "temperature = [60,61,61,58,55,50,44,37,30,28,26,25]\n", " \n", "for T in temperature:\n", " if T < 32:\n", " break\n", " print(T)\n", "\n", "print('Temperature below freezing: '+str(temp))\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", "# Do it yourself #2\n", "\n", "Write a for loop that loops through our temperature array that we listed below. \n", "For each iteration compute the difference between the temperature that you are iterating \n", "through in our list, with the previous temperature that we iterated through. For example,\n", "if we have a list of temperatures [30,50,45], and we are on the second iteration, we \n", "will substract 50 by 30 to get a temperature difference of 20. If the *absolute* temperature \n", "difference equals or exceeds 5 degrees, print out the result to the screen. In addition to\n", "printing our temperature difference values that exceed an absolute temperature difference of 5,\n", "students should also print out the time this occurs at, in the format of *HH:MM*. " ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "24\n" ] } ], "source": [ "temperature = [42,37,35,34,34,35,36,38,41,44,47,52,58,65,66,67,67,64,61,56,52,47,41,39]\n", "hour = len(temperature)\n", "print(hour)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for t,temp in enumerate(temperature):\n", " if abs(temp) > 5:\n", " continue\n", " print({%d \":00\" %d} % (t,temp))\n", " " ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid decimal literal (3049840816.py, line 5)", "output_type": "error", "traceback": [ "\u001b[0;36m Input \u001b[0;32mIn [35]\u001b[0;36m\u001b[0m\n\u001b[0;31m print({%2d, \":00\", %5d, %5d,%5d} % h,a,b,diff)\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid decimal literal\n" ] } ], "source": [ "for h in range(1,24):\n", " a = temperature[h]\n", " b = temperature[h-1]\n", " diff = a-b\n", " diff_abs = abs(diff)\n", " diff_abs_exceed5 = np.where (diff_abs > 5)\n", " print(h,a,b,diff)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# List Comprehension\n", "\n", "List comprehension is shorthand where we iterate over a list and apply a function\n", "or some other operation to the list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "numbers = [ x for x in range(20)]\n", "print(numbers)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#example\n", "number_list = [ x for x in range(20) if x % 3 == 0]\n", "print(number_list)\n", "#obviously there are other ways to do the same thing, but this approach\n", "#can be useful at times" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Error Handling\n", "\n", "For more complicated codes, it becomes important to try togracefully handle errors\n", "rather than simply stopping. The format is:\n", "\n", "try:\n", "\n", " code block\n", "except:\n", "\n", " alternate code block\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#example (kind of lame because numpy version of sqrt will just give a warning)\n", "import math\n", "import numpy as np\n", "a = -5\n", "a2 = np.sqrt(a)\n", "print(a,a2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import math\n", "values = [10,-5, 25]\n", "for i,val in enumerate(values):\n", " print(i,val)\n", " try:\n", " a2 = math.sqrt(val)\n", " print(val, a2)\n", " except:\n", " a2 = math.sqrt(abs(val))\n", " print('trying to take sqrt of negative number',val,a2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

\n", "\n", "# Want more practice!?
\n", "Check out the following webpages:
\n", "https://www.tutorialspoint.com/python3/python_decision_making.htm
\n", "https://www.tutorialspoint.com/python3/python_loops.htm
\n", "https://www.w3schools.com/python/python_for_loops.asp
\n", "https://www.w3schools.com/python/python_conditions.asp
\n", "\n" ] } ], "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.10.5" } }, "nbformat": 4, "nbformat_minor": 4 }