 In this lesson, we'll be learning about a programming technique called a loop to help us implement our Caesar cipher that we've learned about in previous lessons. In Python, there are two types of loops that we'll be learning about, and the idea behind a loop is that it allows you to repeatedly run the same lines of code over and over again, usually into a particular condition as met. The first type of loop we'll talk about is called a while loop, and it gets its name because we kind of think about we'll use it as under the situations of while a condition is true. Run this code underneath. So here's the format for how it's set up. Normally, there's some variable that controls the condition in this case. It's our variable a and we initialize it to some value. So here we're starting at the value of zero. Then we get to the second line of code, which says while. And then after the while, we have this comparison a less than three and then a colon. So what that is telling the computer is that as while that statement a less than three is true, run the two lines of code that are indented underneath it. And what are those two lines of code going to do? They're going to print the current value of a and then increment a by one. You can see it's a is now equal to a plus one. And when we run that code, it'll loop through that several times repeatedly running that indented block print increment print increment until a equals zero is no longer the case. One time through it'll be a equals one. After the second time through it'll be a equals two. After the third time through it'll be a equals three. But once a equals three, that while statement is no longer going to return true. It's going to return false. When a is three, a is not less than three. Therefore, it will no longer run the code and it'll go to the code underneath the while loop. And in this case, there isn't any. So the program is done running. We're going to use a visualizer tool to help us understand how this loop runs. So we're going to jump over to that right now. Here in this tool, we see our same four lines of code on the left. And on the right hand side, it'll show us all of the memory that's being used by the computer. Currently nothing we haven't run anything. So nothing stores a memory yet. And anything that our code would call to be printed to the screen will show out in this box on the right. The red arrows point to the line of code that's right about to be run. And this faint green arrow, which we don't see any yet, will show the line that was just run. So let's step through this code. We can see that this visualizer tells us that there's a total of 11 instructions that'll be executed in order. So let's run the first one. So after the first line of code was run a equals zero, we can now see that the computer knows that a has a value of zero. And we call that in the global scope or the global frame, meaning any part of your code has access to that variable. We'll see that there's other types of variables that are called local, which only certain pieces of your code get access to. But for now, all of our variables that we create will be global. So now the next line of code that's going to be run is our while a less than three line. And we can see that since a is currently zero, that line of code will evaluate to be true. So the block of code underneath will in fact be run. So when we click next, we can see that it will step into our loop. And now the next line of code will print the current value of a, a is currently zero, and there's our printed output in the top right. Now it's going to increment the value of a by one. And we can see that our variable over here on the right hand side has in fact incremented the computer now believes a to be one. And we go back up to the top of our loop and we try it again. We ask the computer essentially asks itself the question again, is a less than three? Well, since a is one, the answer is true. It's going to run the indented block of code again. So we're going to print and we're going to increment and we go back up to the top of the loop, it asks itself is a less than three. This a less than three resolves to be true. So we go into the loop, we print, we increment, we do it one last time. Is a less than three? Nope, currently it is not. So when we click next, that's it. Our program is done running. Let's take a look at another type of loop that can do some of the same things as a while loop. But it's actually going to be more common for us to be using for our tasks. The second type of loop that we'll be using in this course is called a for loop. And it gets this name because the terminology that we kind of think about every time we use it is for each item in a collection, run the indented block of code. And now we use that term collection loosely because a collection could be a lot of things in Python. It could be a string string is just a collection of individual characters. But it could be other data types like lists or dictionaries or arrays, or we'll see a lot of things can be considered a collection. But for now, let's just think about it as for each character in a string, run this code. So we can see we've got these three characters, ABC, as a single string that we're calling letters. And the structure for this type of loop is we start with the word for and then we provide a variable that we get to name. In this case, we're going to choose char first character and we'll say in and then we provide the name of the variable that contains our collection. So in this case, the string letters contains our collection of characters. So let's see what this is going to do is print each of those characters in succession. Let's check out the visualizer to understand how this actually gets done. So once again, we're here in our visualizer. And we've got our three lines of code that we saw from the slide before. We'll enter that our program and run the first line of code. And we can see that the string ABC is stored to the global to the string named letters. And now we're going to get into our for loop. So as we enter the for loop, we'll see it actually creates this very variable that we're going to call char. I named it that myself because I wanted it to be descriptive that it's containing a single character from the string named letters. And now it's going to jump in and it's going to use that version of the variable character to run the indented code. In this case, it's just going to print the character a. We go back up to the loop and this header of the loop will now increment the variable char to the next unit in our collection. So in this case, that means it should take on the value of B. And it does. And now it uses that version of the variable char to run the indented code, which in this case, again, is just very simple printed out. And we'll do that one last time, changing the variable char to the next unit in the collection C, print it out, and our code is now done. The last time it got up to the top of the loop, there were no more units within the collection to increment. So the program ended. We can see this is a nice way to work through a string, which when we're dealing with encrypted messages like text, a lot of our data will be strings. Let's look at a little bit more of the details of these two types of loops and figure out when we might want to use one over the other. Choosing between a for loop and a while loop can often be tricky because they both do similar things. But we'll see that sometimes a while loop is better suited for one task, while a for loop is often better suited for another. While loops are generally good to use if there's an indeterminate number of times that your code will need to run in order to meet that specified criteria in the header of the loop. For example, say we have a string named plain text, which contains the string short. This loop starts out with while, length of the plain text, that l-e-n is a function that we'll talk about in just a moment. That's that computes the length of a string. So it would compute the length of short and get five. And since five is less than eight, the while header returns true, meaning it will run the code that's indented underneath it. So what does it do? It increments our plain text by adding the letter z to the end of it. And then we go back up to the top. So now we have short z. Its length would be six, which is less than eight. So it's going to run that code again and tack on another z to the end and so on until it finally no longer makes that header statement true. And that'll happen when we have short with three z's, because now it has a length of eight. Eight is not less than eight. So we're done and it prints our plain text. So that time it ran three times through the loop to add on those three z's. And as a quick reminder, before we go on and see it with a slightly different plain text, that length function, all it does is will compute the length of an object. So right now, the length of a string, it would tell you how many characters are in it, but we can use this for other things in Python, like lists or dictionaries or other data types as well. Okay, let's look at another example. Say our plain text now contains the string longer. Well, this code underneath is exactly the same, but it's just going to run a little less time because this initial plain text string is a little bit longer. So it will only have to go through twice. So that's what we mean by an indefinite number of times. The same exact loop will run a different number of times, depending on the other criteria in your code. Now, caution, you need to make sure that your condition that is specified in the while statement eventually becomes false. If it never becomes false, this code will run forever and ever. We call that getting stuck in an infinite loop. So if I maybe never appended the Z on to the end of the string and my string just stayed the same length the entire time, well, then I would never get the length of the plain text to be anything bigger than eight and this loop would just run forever. Now, what we'll see is that both of these examples, actually you could determine the number of times that this loop was going to run before you actually entered the loop. While loops are more often used when there's maybe some randomness involved or some statistical analysis that takes place repeatedly until a certain result gets found. And you don't know how often that's going to be because of that randomness. So while in this case, these are more kind of able to be determined how many times a loop be run. There'll be many situations where we won't know that. And that is really where the while loop shines. Now, a few operators that you saw used there in a while loop and this will often get used in while loops are these comparison operators. So they're probably used to these from mathematics class but here's the syntax and how to use them in Python. We've got the equal to, notice that is two equal signs in a row and that is to make sure that it is unique compared to the single equal sign which already has a use in Python. That's our assignment operators what allows us to assign a value to a variable. So if we're comparing if two things are equal, we would use a double equal sign between them. If you want to know if two things are not equal, use the exclamation point and then the equal, the greater than, the greater than or equal to, the less than or less than or equal to are fairly easy to remember. They're very similar to what we already have seen in math class. So let's talk about four loops. So I mentioned earlier, four loops are the best type of loop to use if you want your code to run once for each item in a larger collection. So the code on the screen, our string plain text is the larger collection and the individual units in a string are a character which is why we've named our iterating variable char the way that we did char short for character and it seems to be a nice descriptive way to describe what each unit that it's going to take represents but you can name it whatever you want to just remember it's good practice for your variables to be descriptive. Let's take a look at a second example on the right. Here we're going to add a new function from Python to our dictionary here or mental dictionary of available functions to use and this is the range function. The range function creates a quick collection of numbers between zero and the integer that you specify. So if we were to specify six, we'd have the numbers zero through five including all of those in between. So if we look at our code example here we start with the string which contains the word short will compute its length which is five and then we'll iterate over that collection of numbers from zero to four, zero, one, two, three, four. That's the collection that range will create. So we'll say for I in that range print I and we can see that that's exactly what it does. It prints the first number in the range zero and then the next number in the range one and so on until it gets to the very last number in the range four. One other note about the range function is that you can kind of supercharge it or customize it if you really want to. This is a lot like the slicing syntax that we saw from strings earlier. Say you wanted to start your range at three and end at nine and count by two. You could do range parenthesis three colon nine comma two and it will start at three, go to nine counting by two or we call that our step value. So a lot of flexibility there but for the most part we're gonna use it the way we see on the screen. Range of the length of our text. We'll see that these two loop structures that are on the screen right now are the ones that we use almost most often in this course when we're working with text. The one on the left will loop over the string and directly store each character to our iterating variable char. The one on the right instead of giving us the character it gives us the indices or the index numbers for all of the characters that are in the string index zero, index one, index two. Most of the time we're gonna wanna use the loop on the left because we're interested in knowing what is the, is the letter that is stored there so you can convert that to its number and so on but there are some ciphers where we actually care more about the position in the string as opposed to the letter that we find there. So let's start to piece this together a little bit and actually build some code that will allow us to do our Caesar cipher. In order to do that, we're gonna have to be able to transition back and forth between the characters in our messages and their numerical representations. In fact, we've seen this already in a previous lesson but let's just hit this again. We're gonna be making good use of this string that we're gonna call all capital letters that contain all of the letters between A and Z in order because as a reminder, it lets us quickly specify which character to pull out using the numerical representation which is the exact same thing as the index where we'll find that character in the letter string. So when I do letters and I put the number seven in the brackets, I'm gonna go to index seven where I find character H which is the exact same character that we specify should be represented by the number seven, it's perfect. What we haven't talked about yet is how do we go the other way? What Python commands could we use where I could specify a letter and it will give me the numerical representation? Well, it turns out we can utilize this relationship between the index number and the numerical representation yet one more time, we just need another command and to do it in the reverse way. And that's where this dot find command will come in handy. Here you can see that we have our letters string and I can call dot find onto the end and this is really the first time where we're gonna use a dot find but we've seen this kind of syntax before where we have a string and then we use the dot and then we can run a command on that string but here it's the first time we can specify some argument or input to that function that we're running on the string. In this case, we're providing the single character capital C and it will go find which index in the big string letters we find the substring character C and we'll see that the code, the Python code, we'll find that character C at index two so it'll return two. If it doesn't find that string, find is gonna give back the value negative one so you're gonna have to be mindful of that. Sometimes you'll write some code, you won't get an error message but maybe it won't find it in that long letters. Now, why might it not find it in there? The number one mistake I see when I teach this course is has to do with capitalization. Remember capital C and lowercase C are two different letters to the computer so if you're trying to find a lowercase C in this letters string, it's not gonna find it so you've got to make sure that your cases always match up but now we've got a way to switch between numbers and letters and vice versa. We should have everything we need to do the Caesar cipher to encrypt a message. Let's check that out on the next slide. All right, here's our setup. We're gonna go through this a little bit by a little bit and then watch the whole thing run in the visualizer. So this is a common setup to a block of code that we're gonna be using for encryption. We'll include our letters or the alphabet that we expect to use for the message. So in this case, just A through Z. We'll give our plain text message all in lowercase and it's just gonna be hello. I've created an empty string which will ultimately, when this code is done, contain the cipher text message but for now it's just empty and we'll see why we create that at the beginning in just a few moments and then I'm gonna specify the key used for my Caesar encryption. So for Caesar, our key is just an integer and I've chosen seven but you can choose any valid key that you like. Next, we're gonna write our loop and if you think about, well, what do I want to iterate over? Meaning what do I want to do to create my cipher text message is I want to take each letter in the plain text and convert it to a cipher text letter. So for each character in the plain text do something to get a cipher text letter and I've already given it away in the language I've used we're gonna use a for loop to do this and here's what we've got. I've got four char in the plain text and notice I'm using dot upper because we know our cipher text should be upper case when we're done but also we're about to utilize this dot find command we just learned about and I know that those characters if I'm actually going to find them in that long letter string they need to be the upper case version of those letters otherwise they won't be found. So let's look at what I'm gonna do for each letter in the upper case version of our plain text string what am I gonna do? Well I'm gonna find the current character in the letter string so we know that means I'm gonna get the numerical representation of the current letter and I save that to the variable named plain text underscore num so I chose that because it's the numerical version of the plain text and now what do I do on the next line? Well I add the key to it and then I mod by essentially 26 I was a little fancy here I use the length function on the string letters that's because maybe someday we use a different alphabet maybe for a different language maybe I extend this out so it's got uppercase and lowercase I don't have to come back and change my code everywhere there was a 26 and change it to like 29 or 52 or something this way it's pretty flexible. What's interesting to point out here is this is the only line of code in this entire block so far that is actually about this user cipher specifically this is where we're doing that P plus K mod 26 in order to get C or our cipher text number and then on this last line of code here inside the for loop I'm using a plus equals that's something new we haven't seen before this is essentially the same thing as just appending this current letter to the end of the cipher text string so it could have been the same thing as cipher text equals cipher text plus letters of cipher text num when the loop is done running we print it out and we see we get O L S S V now it's kind of hard to look at code and imagine it running so let's hop over to the visualizer and see it in action. All right here we are in our visualizer with the same set of code let's go ahead and run the first four lines of code to kind of store everything we need into memory so now we can see the computer knows these three strings and one integer we get to our first part of our for loop and we'll see it stores the first character of our plain text string to the variable char and now it will run these three lines of codes with H stored to the variable char so what does it do? The first thing it does is it finds char in the letter string and it finds that at index seven now we're gonna add the key to that and mod by the length of the letters so mod by 26 let's run that and we see that's what produces our cipher text of 14 so numerical value for the plain text of seven add the key of seven it's already 14 but we always are gonna mod by 26 just in case that key caused it to go above 25 like we saw earlier. Next we do this plus equals on the letters of cipher text number so that's gonna go to index 14 in our letters string and that's gonna pull out the character O which gets appended to our cipher text string which is already created stored in memory ready to go and now we go on and we do this again the for loop changes what value is stored the char now it's character E because it's the next letter in our plain text and it just does it again finds E, updates the plain text num recomputes the cipher text num by adding the key and modding by 26 and then converts that to a character and appends it to our cipher text string and we'll do that just a few more times to complete building up the cipher text string until it finishes it with the last unit or the last character in our plain text string it goes back at the check one last time and says, yep, I'm done skips past the block of for loop gets to the last line of code down here which says print the cipher text and there it is. Let's just hit a real quick recap here of all the Python that we covered in this lesson because it was quite a bit we learned how to construct while loops for loops, use comparison operators compute the length of strings using the LEN or LEN function find the location or index of a substring within a larger string and how to use the range function to quickly compute a collection of numbers based off of the integer input it's quite a bit so make sure that you play around with these functions understand how they're used and particularly go back and check out that visualization of our Caesar cipher to see them all used together so you can get a feel for how we're gonna start to compare how to combine these different functions to create really interesting computer code. We'll continue to use this loop structure on our next cipher the multiplicative and affine ciphers and we'll continue to see this overall structure throughout the rest of the course so make sure that you really understand the topics that were covered in this lesson.