{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Iteration \n", "\n", "Often, we want to compute perform the same operation many times.\n", "This could be for many reasons\n", "1. We may be approximately solving a mathematical or physical\n", " problem with code and we want to keep improving our\n", " solution until it is \"good enough\" or simply stops getting\n", " better\n", "2. We may want to simulate a more complex process by repeating\n", " many simpler steps again and again\n", "3. We may wish to perform the same operation on different\n", " pieces of data.\n", "4. We may wish to compute some value that inherently relies\n", " on many different values.\n", "\n", "All of these tasks share the common concept of wanting to\n", "repeat a task many times, which translates to wanting\n", "to repeat one or more code statements many times. This\n", "is called the concept of **iteration**. While we could do\n", "this by copying and pasting code, as we discussed with functions,\n", "it is a bad idea in general. Furthermore, we want to be able\n", "to easily adjust how many times a process is executed (whereas\n", "with copy-paste we would need to copy and paste or delete\n", "significant statements of code). Instead, we utilize\n", "what are called **loops**. Loops are a way of telling the\n", "computer to run a sequence of code statements many times. In\n", "fact, you've already seen examples of \"loops\" in math with\n", "formulas involving summations, which may tell us to sum over\n", "some set of values or sum for all values such that some\n", "condition is true.\n", "\n", "## `while` loops\n", "We'll first start with the **`while` loop**. A `while` loop\n", "allows us to repeat a sequence of statements until some condition\n", "occurs. When the condition is `True`, the code inside the loop body\n", "executes. Each time after the loop body finishes executing, the\n", "condition is checked again:\n", "* if it is `True`:\n", " * enter loop\n", " * complete statements in loop\n", " * jump back to re-evaluate condition in `while` statement\n", "* if it is `False`:\n", " * do not reenter the loop\n", " * continue at the next statement after the loop\n", " \n", "Graphically, this can be illustrated as \n", "\n", "\"diagram\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that as with the `if`, `elif`, `else` statements, there is a `:` after\n", "the condition and the body of the block is indented to indicate what falls inside\n", "the `while` (the same way we used this to indicate what fell inside an `if`).\n", "\n", "#### Caution: Infinite Loops\n", "\n", "Note that it's important that the \"loop body code\" in the image above contains\n", "some code that will, at some point, cause the loop condition to no longer be\n", "`True`. If not, we have what is called an *infinite loop* because the loop will\n", "quite literally run forever (or at least until the software/computer you are running\n", "on kills it or dies). You will almost assuredly write many infinite loops as you\n", "write python programs, it is a common mistake for experienced and novice computer\n", "scientists alike. You will simply make this mistake less and identify where you\n", "went wrong faster as you practice more.\n", "\n", "#### Examples\n", "\n", "Let's start by looking at a simple example. Let's start by just summing up numbers\n", "starting at one until the sum is greater than 20.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "total = 0\n", "i = 1\n", "while total <= 20:\n", " total += i\n", " print(\"added\", i, \"total =\", total)\n", " i += 1\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The first line in the loop `total += i` was pretty crucial. Consider what would have\n", "happened without that line. Would `total` have ever changed?\n", "\n", "Now let's look at a slighlty more complicated loop. Consider the problem of counting how\n", "many numbers even numbers starting at 2 you must sum in order for the sum to be greater than 100." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "total = 2\n", "count = 1\n", "current = 4\n", "while (total <= 100):\n", " total += current\n", " count += 1\n", " current += 2\n", "\n", "print(\"adding up\", count, \"increasing even numbers gives sum greater than 100\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In these examples, we were going upward towards our while condition,\n", "but we just as easily could have been decreasing some variable until\n", "it dropped below some value. Additionally, the condition in the `while`\n", "statement can be any boolean expression. It could involve involve negation\n", "(aka `not`) and/or could combine multiple boolean expressions with logical\n", "operators such as `and`, `or`. For instance, maybe we want to simulate\n", "a bank account to see how many days we can double the amount of money\n", "we take out until we either have taken out all of our money or are\n", "taking out \\$1000 per day. One approach to this could look like:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "balance = 3000\n", "withdrawl = 1\n", "days = 0\n", "while (not balance <= 0) and withdrawl <= 1000:\n", " balance -= withdrawl\n", " print(\"withdrew\", withdrawl, \"balance = \", balance)\n", " withdrawl *= 2\n", " days += 1\n", "\n", "print(\"days =\", days)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In general, while loops are useful\n", "when you need to repeat some code until some condition\n", "is met. Other times, you know that you want to repeat\n", "the code for a fixed number of times or for a fixed set\n", "of values, in which case a loop that can do that naturally\n", "is a more appropriate choice. This loop is called a **`for` loop**.\n", "\n", "## `for` loops\n", "\n", "Like `while` loops, `for` loops allowed for repeated code.\n", "However, instead of specifying the conditions under which\n", "to keep executing the loop, we instead directly indicate\n", "the values for the loop variable to take on. They have\n", "the general form:\n", "\n", "```\n", "for val in sequence:\n", " # Loop body code\n", "\n", "\n", "# Other code outside the loop\n", "```\n", "\n", "The word sequence doesn't necessarily mean a specific\n", "variable that has to be named sequence, this is just\n", "to refer to anything that behaves like a sequence. In\n", "python these are known more formally as *iterables* - something\n", "that can be iterated over that defines a set of values and\n", "order in which to move through them.\n", "\n", "In the above example, `val` is a variable name that will\n", "take on the specific value from the sequence each iteration (so\n", "the value for `val` will change each iteration to the next value\n", "in the sequence). We could have used any variable name we wanted\n", "here, `val` was just an arbitrary choice. In general, like with\n", "other variable names, you should choose a variable name for your\n", "loop variable that makes sense given your application. \n", "\n", "#### Examples\n", "\n", "Let's start by looking at a common example, simply looping a set\n", "number of times. This is usually accomplished through the use\n", "of the `range()` function which creates an iterable with set values\n", "in a range. The `range` function can be called with varying numbers\n", "of parameters (because some have default values.) The basic form\n", "is `range(start, stop)`, starting at `start` (inclusive) and stopping\n", "at `stop` (exclusive). Note that `start` is actually optional, by\n", "default `range` will start at 0." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(5):\n", " print(\"hello\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above example was pretty simple, just saying \"hello\" 5 times.\n", "This example didn't even need to make use of the variable `i`, it\n", "the loop solely as a way of controlling how many times to run the statement inside the loop. While this sometimes occurs,\n", "it's often more frequent that we actually need to make use of the\n", "loop variable." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tot = 0\n", "for i in range(0,6):\n", " tot += i\n", " print(\"added\", i, \"tot = \", tot)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that `i` took on the values $0, 1, \\ldots, 5$, but not 6 because\n", "`range` is exclusive of the `stop` value. You might think that\n", "`i` was a bad (or lazy) choice of a variable name (and depending\n", "on the use, it may very well be),\n", "but it is very common to see $i$ as a loop variable in almost\n", "all programming languages.\n", "\n", "We can also pass an optional 3rd argument to the `range()` function\n", "allowing us to specify a `step` -- how much we want to increase\n", "our looping value by each time. Let's look at the same code, but\n", "instead using a `step` value of 2." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tot = 0\n", "for i in range(0,6,2):\n", " tot += i\n", " print(\"added\", i, \"tot = \", tot)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that `i` now took on the values $0, 2, 4$, skipping all of the odd\n", "values. We could have gotten just the odd values (not even) by adjusting\n", "our start value to be 1." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tot = 0\n", "for i in range(1,6,2):\n", " tot += i\n", " print(\"added\", i, \"tot = \", tot)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`range()` is one way of obtaining an iterable sequence and is\n", "often most appropriate if we wish to repeat code a set number of\n", "times or for a set of structured values (like even numbers between 0 and 10). Other times, we may have some set data that we wish to \n", "perform the same operation on. This data could be numerical values,\n", "strings, etc. In this case, we will often use a for loop to loop through the values in a **list**. A **list** is a data structure\n", "that is an ordered sequence of items (where the items can have both\n", "different values and even different types). We'll talk more about\n", "lists later, for now we'll just look at how we can loop through the\n", "values in a list. A list is designated by `[]`, with the list values\n", "inside the brackets separated by commas. Like with any other variable, the list is assigned to a variable name.\n", "\n", "Let's look at an example of looping through a list. Suppose we have\n", "a list of temperatures in Fahrenheit that we wish to convert to\n", "Celsius. We first start by creating a function to convert a single temperature, and then we loop through the list and call the function for each value:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def fahrenheit_to_celsius(ftemp):\n", " ctemp = (ftemp - 32)*(5/9)\n", " return ctemp\n", "\n", "\n", "temps = [0, 32, 50, 70, 90] # Define the list\n", "for ftemp in temps:\n", " # For each temp, convert to celsius and print result\n", " ctemp = fahrenheit_to_celsius(ftemp)\n", " print(ctemp)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Other Loop-related Statements\n", "\n", "#### `break` statement\n", "While it's generally best to choose wisely between `for` and `while` loops and structure your loop appropriately to control when the loop execution finishes, occasionally, there is a need to specifically indicate to exit out of the loop (regardless of where in the iterable it is or whether the loop condition is still `True`. The `break` statement accomplishes this task by \"breaking\" out of the innermost enclosing `for` or `while` loop. Often the break statement would be inside a conditional that checks for something special to have occurred.\n", "\n", "#### `continue` statement\n", "Whereas `break` allows you to exit out of a loop prematurely, `continue` allows you to jump to the next iteration of the loop, bypassing the remaining unexecuted portion of the loop body. This\n", "is typically done to avoid unnecessary work by the computer when some value indicates that the statements in the loop shouldn't be executed this time for some reason.\n", "\n", "With both of these statements, it can be easy to demonstrate them,\n", "but hard to see the examples of when they are truly useful until\n", "you actually need them (when they will really be the most fitting)\n", "solution to solving the problem. For now, we'll just look at a couple of examples to demonstrate how they behave" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "balance = 1000\n", "atm_limit = 5\n", "withdrawl_amount = 50\n", "while balance > 0:\n", " if atm_limit == 0:\n", " break\n", " else:\n", " atm_limit -= 1\n", " balance -= withdrawl_amount\n", "print(balance)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(-5,6):\n", " if i==0:\n", " continue\n", " print(1/i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Nested Loops\n", "Recall that each of the concepts we've covered so far can be\n", "viewed as building blocks of our programs. We create powerful\n", "programs by combining all of these building blocks: functions,\n", "conditionals, variables, loops, etc. together in unique ways to\n", "accomplish our specific task. Other than abiding by the \"rules\"\n", "of the language (how we build up these pieces is up to us). We\n", "can create functions that call other functions, or functions\n", "containing loops and conditionals where these functions may be\n", "called by code in another loop elsewhere. One of these combinations\n", "is the idea of nesting one loop inside of another. We can do these\n", "with any combinations of loop types (`while` and `for`), it is\n", "just up to us to choose what makes sense. Suppose we wish to print\n", "a triangle out of the character 'z's (why, who knows!) -- we can\n", "accomplish this with nested for loops. Let's look at an example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for r in range(1,6):\n", " for c in range(0,r):\n", " print(\"z\", end=\" \") # adds a single z to this row\n", " print(\"\\n\") # adds newline after all zs in this row\n" ] } ], "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.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }