In many of the algorithms we saw earlier in the course, we needed to perform some actions repeatedly. In the previous part of the course, we saw that the computer can execute an instruction that will cause it to jump back to a previous one. Recently, we saw conditional execution in Python using if-then statements. But when we want to execute code repeatedly, we do so using a loop. The first type of loop we'll see is known as a for-loop, where the conditionally executed code is run for each element in a list. Let's start with this example in which we want to print the square of each number in a list. As you can see in the flowchart, we're going to repeat this functionality for each number. As long as there are more elements to process, we'll continue. But when we finished with all the elements, then we're done. So, in the code on the left, we first define our list code numbers and initialize it with these four values. Now we have our for-loop. It starts with the keyword for and then the variable name that will give to each individual element of our collection, which we'll call number. This is followed by the keyword in and then the name of the list. Inside the body of the for-loop, we print number raised to the power of two using the double asterisks. When we finished with all the elements, then we're done. Note that as we saw before with if statements, we need to indent the body of the for-loop so that Python knows that this is the code to run for each element of the list. This print statement is executed four times, once for each element in the list. First, the variable number is assigns the value 7.3. The body of the for-loop print 7.3 squared, which is 53.29. When we're done with that, we loop back and see whether there are any more elements in the list. There are, so now number refers to the second element of the list, which is 6.4. So, the body of the for-loop, print number squared which is 6.4 squared, which is 40.96. Then we loop back and see if there are still more elements. There are more elements. So, now number holds the value 13.1. We go back into the body of the loop. We print number squared which is 13.1 squared, which is 171.61. There's one more element, which is 2.0. So, we set number to hold that value, and we print its square which is 4. 0. Although we're at the last element, the program doesn't know that yet. So, it loops back and sees if there are any more elements. There aren't anymore. So, we're done, and then we come down to this print statement. We certainly could have printed out the square of these four values one at a time without a for-loop, but in that case, we'd have four lines of code, one for each value, instead of just the three that we see here. If our list had 100 values, we'd have 100 lines of code if we printed them one at a time. But again, if we have this loop, it's still just three lines. You might ask, can we have if statements within four loops? Sure, why not? The body of the for-loop is just regular Python code like everything else we've seen so far. So, this code may look familiar. It's the same code that we used in the last part of the course when we introduce the idea of labels and variables. Sue showed it at the end of the first lesson in this part of the course when she introduced you to Python programming. So, here we have another list called numbers, and we want to know how many of the values are even. So, we first declare the list and then define a variable called count, which we'll use to count the number of even values. We'll initialize it to zero, meaning there are no even numbers yet. As we saw on the previous example, we have a for-loop which will iterate over each element in numbers, and we'll call each one number. Because there are eight elements in numbers, we'll execute this code eight times, but the variable number referring to a different element each time. To determine whether a number is even, we can use the modulus operator with the operand two. If you have an even number and divide it by two, the remainder will be zero. So, that is how we can check if it's even. If it's even, the we'll increment our counter. A few things to note here. First, as the comment mentions, count plus equals one is just shorthand for count equals count plus one. We're just incrementing that value by adding one to it. Also, note that count plus equals one is doubly indented. We need to indent the body of the for-loop, but then we also need to further indent the body of the if statement. At the end, count will hold the number of even values in the list, and we can print it out here. We can also have a loop within a loop, which we refer to as nested for-loops. In this case, I have two lists of names, and I want to find the distinct names that they have in common, or what we'd call the intersection. So, I defined my two lists as names one and names two. Then I have an empty list called common names. So, now here are the nested for-loops. In the outer for-loop, I'm iterating over all the elements names one and referring to each element as name one. So, the first time through this outer loop, name one is "Lydia". Then I have the inner for-loop where I'm iterating over all the elements in names two and referring to each element as name two. So, the first time, name two is "Yichen". For each of those elements, I compared name one to name two to see if they're equal using the double equals sign, and I also want to see if name one is not already in common names. Previously, we saw this notation to see if an element is in a list. This is just a variation to see if it is not in the list. If name one and name two are equal, and name one is not already in the list of common names, then we'll append it to that list and insert it at the end. So, in this case, because name one is "Lydia" and name two is "Yichen", they're not equal. So, this is false, and we continue looping. So, which names do we compare next? Well, we're still iterating in the inner loop or the elements of names two. So, now name two is "Laura", but name one is still "Lydia" because we haven't finished running all the code inside the outer for-loop yet. So, we compare "Lydia" to "Laura", then "Lisa", then "Veronika", then "Karin". Finally, the inner for-loop has completed. So, we move on to the next element of the outer for-loop. So, now name one is "Claire", and we go into the body of the outer for-loop. So, what do we do here? Well, now we're going to iterate over all the elements of the list called names two. So, we start over. So, now named two is "Yichen", then "Laura", then "Lisa", "Veronika", "Karin", et cetera. In the end, common names only holds one name, which is Lisa, because it's the only one that appears in both lists, and it's only in there once because we don't add it to the list if it's already there, as we see here. Here's a visualization of the flow chart for that code. You can see that we have the nested for-loops or the loop within a loop. When we continue in the outer loop, we go into another loop which is going to compare the values. When that inner loop is done, we go back to the start of the outer loop and continue again into the inner loop if there are more names in names one. If you're having trouble following that code, don't worry. It can be very complicated at first. Even though I've been programming for a fairly long time, I'm still a big fan of well-placed print statements in order to figure out what a piece of code is doing. Here I've added print statements and highlighted them in red to show what names are being compared and which names are being added to the list. If you're writing code and struggling to understand its behavior, you might want to try this approach, though there are of course tools out there that will help automate this a bit too. Anyway, for-loops are very useful when we want to iterate over the elements of a list. But sometimes, we want to access elements by their indices while in the loop, and we need some counter index that increments on each iteration. In this example, we want to determine whether a list is sorted in increasing order. There are a few ways to do this, but in this case, we'll look at each element of the list and compare it to the one that comes before it. For instance, we can compare the value at index one to the value at index zero, and so on. When the value at one index is greater than the one that comes before it, we know we're okay. But if an element is less than or equal to the one that comes before it, then we know it's not sorted in increasing order. So, here's a list called "ages". We have this Boolean variable is sorted to indicate whether or not the list is sorted. We'll initialize it to true because we assume that the list is sorted until we determine otherwise. Because we're going to use the list indices to compare elements at adjacent positions, we need to know the number of elements in the list which we can get using the LEN function that we saw last time. So, now here's our for-loop. Although we're going to iterate over every element of the list, the for-loops we've seen previously just give us a single name to use for each element. However, in this case, we want to look at two elements: an element, and the one that goes before it. So, what we want is not named elements, but indices that go 1, 2, 3, and so on. We can get this collection of indices using the range function. The range function returns a list containing numbers that start with this first value which is one, and end with this last value, but not including the last one. So, in this case, since length is four, then we only want a list that contains 1, 2, and 3. You might wonder why don't we just start with zero since the indices start with zero. We'll see that in just a second. So, what we're doing now is iterating over this list of numbers 1, 2, 3, and then using those as indices for our ages list. I'll use the variable i to store each value. This name is used by convention to refer to a list index. So, now here's the body of the loop. I'll compare ages of i to ages of i minus one, that is a compare an element to the one that came before it. This line here shows why we didn't start our range at zero because in that case, we'd be comparing elements zero to element negative one which is not what we want. If the element is less than or equal to the one that came before it, that means it's not greater than the one that came before it. That would mean that the list is not sorted in increasing order. In that case, we'd go into the body of the if statement where we set "is sorted" to false indicating that the list is not sorted. At this point, we know we don't need to look at any more elements, so we can stop looping. We do so using the keyword "break" which breaks us out of the loop. So, when we run this loop, we first compare ages of one to ages of zero. Ages of one, which is 45, is greater than ages of zero which is 23, so we're okay. Then we compare ages of two to ages of one. Sixty two is greater than 45, so we're still okay. But in the last comparison, we compare ages of three to ages of two, and because ages of three is less than or equal to ages of two, we set "is sorted" to false. Note that, if the list was sorted in increasing order, then we would never run this line, so we would never set "is sorted" to false, "is sorted" would still be true. So, when we get down here, we can use the value of "is sorted" to determine which of these two things we should print out. For-loops are good for when we know in advance how many times we want to run the loop. But we can also write a loop that keeps iterating as long as some condition is true, this is known as a while loop. In this case, we're going to ask the user of our program to enter a positive number and continuously repeat that until they actually do so. The input function shows the user a message and waits for them to input something which we'll call "value". Unfortunately, we can't use this function in our Coursera code blocks, but you could use it on your computer if you were to install Python. Python treats that input as a string of characters and not a number that you can do math with. So, we'll use this int function to convert it to a whole number or an integer. This will give us a value error if the value is non-numeric, but we won't worry about that for now. Now, we have a while statement. A while statement is structured just like an if statement. If this condition is true, then we'll enter the block of code. We want to do this if the value that the user entered is not positive. That is, if it's less than or equal to zero. In that case, we would ask the user to enter the input again. The difference between a while loop and an if statement, aside from the word while here, is that after we go to the last line, we go back and check the condition again, and keep doing this while this condition is true. So, we keep looping until this condition is false. That is, until the number is greater than zero, which means it's positive. If it's false, we don't enter the block, we know that the number is positive and we can continue. Earlier in the course, we looked at algorithms that use lists or collections to do things like find the maximum value, and see if it contains a target value. You may wonder why didn't we look at that code in Python in this lesson? That's because these algorithms are so common that Python already provides this functionality for you. So, you don't have to write it yourself. Here, we have a list called scores. The max function returns the largest element in the list, and as you can guess, the min function returns the smallest element. As we saw last time, the in keyword determines whether the target element is in the list. You shouldn't write your own iteration code in these cases, but rather should always use the functionality that Python provides. We're moving pretty quickly through Python, but now you're at a point where you can start implementing complex algorithms using just the features you've seen so far. Last time, we saw lists which are ways of gathering elements together into a single entity. Now, we've seen ways of iterating or looping over these lists using for-loops and while loops. Next time, we'll talk a little bit more about organizing our code and see how we can make it easier to understand.