Practice Exams:

Python Institute PCAP – Control Flow Part 2

  1. For Loops

And that’s essentially being able to skip lines. If you don’t want a certain line of code to run based on some logic or some condition being met, then you use the if else statements. If this, then do this, otherwise do that. That’s a way of controlling the flow of the program. Now there’s another way of controlling the flow of the program. And this is very important, just like the lectures before. And this has to do with iteration, meaning doing something over and over again. If I was to Google the word iterate let’s do that because you’ll hear this being used a lot in programming, iterate perform or utter repeatedly. Okay? So basically means running a line of code over and over and over again. Another word for this is looping. If you need to loop through some lines of code, that means you want to run those lines of code over and over and over again.

So if you wanted to iterate through a list, that means you want a block of code being run for each and every single element in that list. We talked about tuples. So you may have a very large tuple with a lot of data with many, many items in it. So if you wanted to iterate over that tuple, that means you want to run a piece of code for each of those elements that are in that, in that tuple. Okay? That’s what the idea behind iteration is. Iterate over a list, iterate over a tuple or any other collection data type. And you can also iterate over strings. So let’s get into this concept.

Talking about this might seem confusing, but as soon as you start typing this code and running it for yourself, it’s going to make a lot of sense. So let’s define a list, and I’m going to say the list is called farm animals. And let’s say that we have various animals in our farm. We’ve got a goat, we’ve got a horse. Let’s say that we have a chicken and cow. And one more animal, let’s say we also have a dog in our farm. Okay? So to iterate over this, we can use something known as a for loop.

So I’m about to introduce to you this new keyword called four. Okay? Notice the syntax highlighting going on here. So there’s a reserved keyword in Python, as well as many other programming languages. So I could say for item in, there’s another keyword that I’m introducing to you for item in a list of things, and that could be this farm animals. So let’s just do that. And then you put the colon. And now you’re in this block of code. You’re in the four loop.

Notice the indentation going on here, okay, so four spaces in and all of the code that you want run over and over again. For each of these items that are in this list, that code is going to reside in this indentation inside of this for loop. Okay? And there could be all sorts of instructions in this list, like you can have comments, you can have other for loops as well as if else statements and so on and running functions and so on. You can do all of that inside of this for loop as long as it’s indented.

So if I wanted to print the item, I could just do this print item. Okay, so this code that I have here, this print function is going to be executed for each of the items in this list. What is the name of the list? Farm animals. So it’s pretty readable the way the code is right now, right? So let’s run this and you’ll see that it runs those instructions for each of those elements. And it’s a simple set of instructions. We’re just saying print and this variable, this item variable, I’m actually defining this variable as part of this for loop. Okay? There’s not a reserved keyword or anything. Notice it’s not doing any kind of syntax highlighting. We can call this variable anything. I can say V for value, for example. And so this V would be each of these items. And so if we want to print each of those items, we of course have to put V down here as well. And so let’s run this. That’s going to work exactly the same. So as far as this code goes, these are not items. These are not Vs. What are they? They’re animals. So we could say for animal in farm animals, we would like to print the animal. Okay? So much more readable and of course it’s going to run exactly the same. All right, I’m moving step by step here so that we don’t miss a beat. Very important for you to understand this intuitively, not only just being able to watch this video and try it on your own. There’s some intuition that I’m sort of downloading into your brain as we speak. So keep up with this and practice along with me. Like I said, the instructions that we have inside of this loop are going to run for each of the items in the list.

And so let’s say that we wanted to have a sentence be part of this. Let’s say I want to print out that each of these animals are safe in our farm, for example. So what I could do is I could define a variable called sentence, and I can assign this sentence the concatenation of animal and a given sentence. All right? I can name the sentence anything, but I’m just going to say is safe in our farm. Okay? So here, this is a line of instruction that’s going to happen for each of the items in this list. And what’s going to happen for the goat? Goat is going to take place of the animal. So it’s going to say Goat is safe in our farm. It’s going to say horse is safe in our farm. Chicken is safe in our farm. Now if I run this, obviously nothing’s going to print because I’m not giving the print instruction here. This is just an assignment going on here, right? Let’s run this. Notice nothing gets printed.

So let’s print the sentence, okay? And so now let’s run this. And there we go. Notice says, go to safe in our farm. Horse, chicken, cow, dog, all of them are safe in our farm and so on. Now for each iteration, this sentence variable is being assigned whatever data this is, okay? And for each of these iterations, of course, the animal variable is going to take the place of each of these animals, goat, horse, chicken, and so on. But if I was to print, for example, the words, let me just write hello, world, or whatever. Notice if I run this, it says hello world five times 12345. Obviously it’s going to run this instruction for each of the elements in the list. And so since we have five elements, it’s going to run this hello, world five times. So this goes to show that we don’t have to, of course, print the animal in every instruction. And you’ll see more examples of this. Let’s say you are performing various tasks. You have a huge series of instructions where you’re downloading data from the internet for each of the blogs on a website or something, right? Well, you don’t want to print that entire blog entry. You might just save those entries in a file and all you would like to print is saying that, hey, download it successfully or something in the log of your program.

So it might just print, download it successfully downloaded successfully, downloaded successfully and so on. And the actual processing of data that’s happening might be saving to a file and that sort of thing. So you don’t have to necessarily print the items that you’re iterating through in a print function. There’s just an example to show that you could print anything you’d like. So let’s get rid of that. And I’m just going to print sentence. Now this is a list. It’s a collection of items so you can iterate through them. You can also iterate through a tuple. We’ve looked at tuples before, right? So that’s also a collection of items. So all you have to do is change this from square brackets to parentheses. And now this is a tuple, okay? And this code will run exactly the same way. Let’s run it. And there we go. Go to safe and our farm horses, safe and so on. So we looked at a list, we looked at a tuple, same idea.

Now I have an assignment for you. I’d like you to try this. I’d like for you to print the number 1234 and so on before the sentence, okay? So it should say one, go to safe in our farm. Two, horse is safe in our farm. Three, chicken is safe in our farm. So why don’t you try that, pause the video, and then you can resume to watch my solution. Okay, welcome back. Hopefully that wasn’t too difficult. And if it was, don’t worry, you’re going to learn as we go along and practice with me. What we could do is define a variable called counter and let’s assign it to value zero. And this variable is going to be a counter, meaning it changes as we proceed through the list.

And 1234, that’s what this variable is going to contain. So what we could do is up here we can say counter is equal to counter plus one. Okay, let this sink in for a little bit. If it’s a little confusing, don’t worry, think about it. Because what’s happening is every iteration this line of code is going to run and it’s going to reassign counter to the next number. So what is first of all, what is counter plus one? In the first iteration for the goat, counter is of course going to be zero because that’s the initial value. And then we add one to it. So now it’s going to be one. So counter is going to be one. And all I have to do is append or concatenate to this sentence the counter variable. So we could do counter plus. Now you’re aware that you cannot concatenate strings with numbers, right? We’ve looked at this before. This is an integer. This is a string. So what we need to do is turn this into a string. So I’m going to use the STR function, which is one of the very early functions that we looked at in this course. So now since we take that number and we convert it to a string, it’s going to say one right before the animal. And just to keep it a little cleaner, what I’m going to do is I’m going to add another space between this so that it doesn’t club the number with the animal. Like we don’t want it to say one and goat as one word. We want to have a one and then space goat, two, space horse, and so on.

And so that’s what this space represents. So again, in the first iteration for goat, it’s going to say zero plus one is one. It’s going to say one goat is safe in our farm. And then for the next iteration, what is counter? When this loop starts again, for the next animal, horse at that time, what is the value of counter? It’s not zero because we’re not outside of this loop yet. We’re still inside of this loop. This code is going to be running over and over and over again right, until we go through all of the items. So for the horse, for the next value, a counter is going to be one. And then we do one plus one is two. So now it’s going to say two horse is safe in our farm. Which should be plural horses. But we don’t need to get into the technical details of plurality here.

And so for the third iteration, for chicken, the value at that point, when this loop continues, at that point it’s going to advance from two to three. So it’s going to be two plus one is equal to three and then three chicken is safe in our form and so on. Hopefully you get the idea. If you don’t think about this code, try to run it multiple times and keep looking at it and trying to study it and eventually you’ll get it. Okay, I’m trying to break it down as easy as possible, but some people still have trouble. So I want to make this course as approachable to everyone. If you understood this, sorry for the repetition, but at this stage we want to make sure everyone is on the same page. So let’s run this. And there we go. Notice it says one goat is safe in our farm, two horses safe in our farm and so on. So if you got that, congratulations. If you didn’t, don’t worry, stick to it and you’re going to get it in no time. And needless to say, it is going to work exactly the same if we have a tuple or if we have a list. So the idea behind iteration is that we can iterate over the items of a collection, multiple things. So in this case, we have a list, believe it or not. We can also iterate through strings.

Remember we talked about string slicing? We can get first character of the string, last character and middle characters of a string. We could break it down like that. So Python also has the functionality to be able to iterate through a string. So let’s say that I have a sentence. I’m just going to create a sentence here and we’ll call it Greeting. And we’ll say hello, my name is MTOs. This is our sentence or our greeting variable. We can iterate through this greeting. So let me use the same syntax here. We can do four character, so I’ll just put CHR in Greeting. We’d like to do the following. So I’m just going to print the car, whatever car it is, and make sure this is formatted correctly. It needs to be inside four spaces in and there we go. Let’s run this and notice it’s going to print each and every single character takes the he ll o space is also a character and so on. So for each of these characters in this string, it’s performing these instructions, whatever the instructions are. In this case, we just have a simple instruction which is to print car. Now, this doesn’t have to be the car variable, we could make it be anything. This is just say gibberish or it doesn’t really matter as long as this variable is the same down here. Because what’s going to happen is this variable is going to take the place of each of the items in a given list, in a given tuple or a given string, each of the characters in a given string. So we want to make sure that whatever we have here is the thing that we’re working with.

All right? This is known as the iteration variable or the. Iterator don’t get bogged down by the jargon just to understand that this variable needs to be consistent throughout the loop. So let’s run this, and it’s going to run exactly the same, all right? And just change it back to what makes sense. Let’s change it back to Car character. Now, you might be wondering, does this loop can we terminate this loop early? Meaning let’s say we want to iterate through a couple of characters only, and then we want it to break out of this loop. Can we do that? Yes, we can. I’ll show you an example. So let’s say that we would like to end this loop once we come across the letter N. The letter N, we’d like to end this loop. How would we do that? Well, it’s actually quite simple. We spoke about the if else statements in the previous lesson. So what we can do is have an if statement and say and give a condition. And the condition could be as simple as if Car is equal to the letter N, then we would like to do something. And what is that command that we need to break out of the loop to end this loop? Well, it’s as simple as the break keyword. All right. Notice it’s highlighted. There’s a new keyword that I’m introducing to you.

 If you want to jump out of this loop and move on to bigger and better things that are outside of here, right, that are outside of this loop, if you want to move on to bigger and better things, you want to break out of this loop early, you use this break keyword. All right? So what’s going to happen is going to go letter by letter, and then as soon as it notices that there’s an N here, it’s going to break. So what is that going to mean? That means that it’s not going to print the letter N, and it’s not going to print any of the other letters either, the remaining letters. So let’s run this. And you’ll see, and boom. There you go. It says, Hello, My. And then there is a space character here. Notice it did get this space after the word My, but then as soon as it noticed that there is an N, it ended the loop. If there were bigger and better things out here, let me just say that loop is terminated by this point. Just to be specific here. Now let’s run this and notice it says loop is terminated by this point.

So it did not go through the rest of the characters. We were able to prematurely interrupt this loop and break out of it. Now, just like Break, where we break out of this entire loop and move on to bigger and better things of other lines of code that are outside of this loop. Just like Break, we have something called Continue, and it kind of does what you might think. It basically Continues, the loop, but what happens is in Continue, it just moves on to the next character. Okay, so instead of break, if I choose Continue, here, what’s going to happen is it’s not going to continue to the next line. No, that’s not what this means. This Continue means we encountered this character N, right? If we Continue, that means, hey, let’s just move on to the next character. That’s all it’s saying. So Continue prevents going through the rest of the lines of code that may be part of this loop, and it just moves on to the next element or next character in the string. So I’ll prove it to you. Let’s run this and notice. Let’s go up and let’s read through this. Hello, My. And then it says aim instead of name, it says aim. My aim is Mtrs. So what did it do? It skipped the letter N. All right. Because what was supposed to happen is we were supposed to print the letter N, but since we have this Continued statement before this print instruction executed, it just moved on to the next character. And that was a and that’s how you can skip over elements. So understand break is to just break out of this loop entirely, and Continue is to not execute the remaining lines in the loop and just move on to the next element.

I’ll make it much more specific because we’re dealing with characters here, and it’s a little tricky to understand with characters. Let me just bring up our previous example with the animals, because I think that’s easier to go through. So I’m just going to remove all of this and paste that. So we have farm animals, and so we’re printing the farm animals. So if I was to have an if statement and say that if animal is equal to goat, let’s use chicken. If animal is equal to chicken, break. What am I saying here with this code, hopefully you can see the result. Think about it in your head and then run this. Let’s run it and notice it says goat. Horse. It printed goat. It printed horse. And then as soon as it encountered chicken, we’re out of the loop.

All right. It didn’t print chicken. It did not print cow or dog. Right. Loop is terminated. If I was to put Continue here, what do you think it will do? It’s going to skip the step for printing chicken. So let’s run this. And there we go. Goat, horse. No, chicken. It did not print chicken, but it printed cow and dog. All right, again, because it encountered Continue when it saw chicken, it just moved on to the next element in the list. Rather than printing or following other commands, there could be all sorts of commands here. There could be if else statements, there could be other loops, loops within side loops. As soon as it sees this continue, it just moves on to the next element without executing the remaining lines that may be part of the script. All right, so I repeated myself multiple times and I moved slowly through this lecture. These two concepts of break and continue and being able to iterate through a collection of things.

  1. Pass Statement in For Loops

Introduced to you a specific keyword known as pass. Now, I spoke about break and continue in the previous lecture. I wanted to COVID pass in a separate video, as well as a couple of other things to tie up some loose ends. So let’s say that we have a loop. Well, first of all, I’m going to define a list. We’ll call it my list, and it could be a list of objects. So we can say that it’s a computer, car, bottle and TV. Okay? These are my objects. So if I wanted to loop through them, I could say item in my list, and then I can do something with this item. Now, let’s say that I don’t want to do anything with this item, and I just sort of want to move on to bigger and better things. And I sort of want to let this just be there as code that I will fill out later when I get back to this. And let’s say I have some other instructions down here, do other stuff, and then I call some kind of function on the struct down here. But I have an incomplete loop here. I don’t have any instruction. If I run this, we’re going to run into an error. It says indentation error, expected and indented block. So what is the error? Well, it’s saying that it expects this to actually be part of the loop, but we’re out of the loop.

We don’t want to leave anything in this loop. So let’s say that okay, you can maybe put a comment here and say comment to coder, work on this next week or in the next release or whatever. All right? If we run this notice, same error. Because the issue is the Python interpreter expects some instruction as part of this loop. You can’t just have an empty for loop statement here. It needs some kind of instruction. And this comment is not really any instruction to the computer. This is an instruction to a fellow programmer that needs to read comments or something and understand what the code is doing. This is not interpretable by the Python interpreter. So we actually need real code. So what I could do is actually use a pass keyword, all right?

And this is exactly why this keyword exists. It actually does nothing except make sure that this compiles correctly. And typically, you’ll see this type of a structure in real world coding all the time. Let’s say it’s a loop that you intend on building, and you’re not sure some of the data that’s going to be coming in this loop. So you just want to leave this to later, but you want the structure to sort of be there so that another programmer could catch up later.

You’ll typically see this pass, and that basically means do nothing. Okay? And so now if I run this notice, there’s no error. It moves on to bigger and better things, and that bigger and better thing was getting the type for the string, which, who cares what that does? But hopefully you get the idea that we have other instructions, other lines of code, bigger and better things to do than to worry about this. But that’s what Pass does. It does absolutely nothing. It’s sort of a placeholder think of this as a placeholder that you’ll get to later.

 So that’s one thing I wanted to COVID Another thing I wanted to talk about is instead of having a variable that contains our list or our tuple or something, we can also have the actual list itself. So let’s just copy this and paste it here. We can also do something like this and print item. Okay, so let’s run this and notice that works exactly the same.

So I don’t need to define a variable per se that is going to contain our list. I could just literally use the list directly. Okay, same thing with strings. I don’t need to have a sentence defined first. I could just have a string that says this is a string or anything. And this will work exactly the same. If I run this, notice it prints each and every single character in the string. So, just wanted to tie up some loose ends from the previous lecture and we’re going to continue on while loops in the next lecture. That’s a different kind of loop, which basically means while something is true, do something over and over.