Python Institute PCAP – Control Flow Part 3
- While Loops
Now we’re going to talk about the while loop, okay? And this is actually very simple. It basically does exactly what it sounds like. While something is true, do something. So the general syntax is While something is true. So you have a condition here. I’m not going to write any Python code just yet. I’m just going to write some pseudo code, really? While some condition is true, and we talked about conditions with AFL statements and so on, then we’re going to do something else. Do something else. Okay? That’s the general structure of a while loop. So let’s actually add a condition here. Let’s say that while let me move this down. While X is less than ten, do something else. Do something else. So we could say print X is not less than ten. All right? So what is X here? We don’t have a variable defined yet for X. So we actually have to define that variable. In the previous lecture, we talked about four loops, right? Where we can define a variable that will be referred to as the iterator to.
Iterate over each of the elements in the list. Well, in this case, this is not iterating over any elements. This is just a condition. It is going to be equal to a true or a false. It’s a boolean condition. So this Boolean expression, of course, needs to compile. And right now the computer is saying, hey, what is X? We don’t know what X is. Unresolved reference X. So let’s define X and we’ll say X is zero. Okay? And so we need to do something here. So let me replace that comment and say we’re going to print X. All right? Now think about this before I run this. Don’t run it yourself. Just think about this and figure out what you think is going to happen. What is this saying? While X is less than ten, print X. Notice that this is going to continue to run forever, or at least until my computer crashes. And the reason is because this condition will always be true. With the current state of this code, we assigned X to be zero. So X will always be at this stage, x will always be zero.
And we’re not making any changes to X. So it’s just going to keep printing zero over and over and over and over again until my computer crashes. So let’s run this. And you’ll see, this is known as an infinite loop. Look at what’s going on here. So if you run into an infinite loop, which beginner programmers often do, you can always shut this program down, just close it. And the way you do that, you can just press the stop button right here and that will end the execution of this program. And notice how many zeros were printed. This would have continued to run for a very long time. So we need to somehow make this condition false eventually, if we would like this loop to end. Okay? And so the way to do that is we can actually say x is equal to x plus one. Notice what I’m doing here. You’ve seen this before. In the first iteration, the very first iteration of this, x is going to be zero. So it’s going to be zero plus one. And now X is going to be one.
So it’s going to print one. Then in the next iteration, x is one plus one, two, it’s going to print two. And then in the next iteration, it’s going to be two plus one, three and so on. Okay? And so this will eventually what’s going to happen is x is eventually going to get to the number ten. And as soon as this condition plugs in the number ten for x, this is going to no longer be true. This is going to be false. And so what’s going to happen, it’s going to jump out here and it’s going to print. X is no longer not less than ten anymore. So let’s run this and notice it prints from zero to nine. And then finally when it attempts to go to the 10th value of x, it checks this condition. Ten is not less than ten, right? Ten is equal to ten. So ten is not less than ten. This is going to evaluate to false. And so it’s going to jump out here and notice that it printed. X is not less than ten.
Another way to do this same thing is instead of doing x plus one is equal to x, we could actually do plus equals. All right, this is a shorthand and this basically means add whatever number is to the right to the item on the left, okay. And assign it back to itself. So in comments, let me leave that for you because in the beginning it might be easier for you to see that this is what’s going on here. So this is the same thing as this, another shorthand. Let me run this so you can see that the same thing happens. Another thing you could do is you can change this to two or three. And as you can imagine, you’re going to get a lot less numbers printed. So it’s going to add three every time, every iteration.
So it’s going to skip through a bunch of numbers, isn’t it? So let’s run this and notice it’s going to 0369. It skipped all the other numbers in between because we are incrementing every iteration, we’re going up by three. And by the way, the same concepts of break continue pass that I spoke about in the previous lecture apply to this, right? Let’s say that we have a condition in here that says if x is equal to six, we want to continue. What does that mean? And again, you don’t need these parentheses for the condition. I just want to show you that you can do that, but you can have a condition like this. And so what is this code going to do? Think about it before you run it. That’s the best way to practice. Think about what this is going to do. Let’s run this. Notice it leaves everything the way it was before. It prints three, six, nine. If you thought that what we did in a couple of lectures ago, using Continue is going to happen again where it skips the number six, you thought wrong. Because the reason is we’re printing right before all of this happens. So the first thing we’re doing here is printing. So if we were to take this and move it down, now what’s going to happen is when it sees that X is equal to six, it’s going to continue, meaning it’s going to go back to the top of this loop. And at that point, what is the value of x? Value of x is still six. It just didn’t do whatever all the bigger and better code down here, continue basically prevented us from moving forward to these lines. So it did not print six. It just restarted the loop again. And at this, . 6 plus three is going to be nine. So now it’s going to skip six. All right, so let’s run this. And boom.
There you go. Notice it says three, nine. And whoa. Notice it says twelve. This is pretty cool, right? So what happened here? Why do you think it printed twelve? Even though we have a condition here, x should not be equal to or greater than ten. It should be less than ten. But here we’ve got a twelve. Where did this come from? Why don’t you try to compile this code in your head? Think about it. Think about why twelve showed up here. Go through it line by line and even on a sheet of paper, try to assign the value of x and go line by line and see what’s going on. And then you can resume this video to hear my explanation. So think of this as an assignment. I want you to analyze what’s going on here and why it’s printing twelve. All right? So hopefully you analyzed it, wrote those things down on a piece of paper, and kept reassigning the value of x in each iteration and seeing what’s going on. So let me break it down for you. When we got to this point where x was finally equal to six, what happened? It said continue. And so what?
That means it continues to the beginning of the loop, basically starting the loop again. So this line gets executed. So now six plus three is equal to nine. So then of course, nine is not equal to x. So it skips this step and it prints nine. But at this point, what happens? The loop starts here. The check happens again. Nine is less than ten, isn’t it? So boom, there you go. Nine plus three is twelve. So it prints twelve and now finally, when you get to here, twelve is not less than ten. And so it breaks out of this loop. And so that’s why it’s too late. Twelve had already been printed. Now, if that’s tricky for you to grasp, don’t worry. I understand this stumbles a lot of people, but it really has to do with the placement of where this print line statement where this printing is happening. If I was to print this to the top right now, you won’t see this bleeding onto the next number, twelve. I’ll prove it to you. Let’s run this. And there we go. Notice it says 0369.
And it of course, is still going to print six because we have the print line statement first. So as soon as X is equal to six, doesn’t matter what this condition says, it says continue. So at this point, X is equal to six. Anyway, it’s going to print that and then X plus three is nine. And then it moves on to the next. And then nine here. Nine is less than ten. It prints nine here, right? Because printing is the first thing that’s happening. And then it adds three to nine. No printing happens after that. That’s why we don’t see twelve. And then it moves to the top and then that check condition happens. Twelve is not less than ten. So this loop is over and we don’t print twelve.
So it really has to do with the placement of where this print statement was either before or after all of this code happens. And that can affect what you intend to do do with your code. All right, this concept of where you want certain actions being done in a loop trick a lot of people. So study this concept, move this print statement around here in this loop and try to figure out why certain things happen the way they do. And with enough practice, this is going to be.
- Looping and Unpacking with Dictionaries and Tuples
The looping is exactly the same between a tuple and a list. And now, again, what is the difference between a list and a tuple? The difference is that a tuple is immutable, meaning you cannot change that tuple. Whereas a list, you can add things to it, you can remove things from it. You can’t do that with a tuple. All right? And another difference is, obviously tuples are using parentheses, whereas lists are using square brackets. It’s just a syntactical difference. So you loop through them the same way. What about dictionaries? How would you loop through a dictionary? Well, let’s go over an example of how we would do that. So what I’m going to do is I’m going to define an employee’s dictionary, and we’re going to store the names of the employees as well as their salaries. So let’s say the first entry here we have Mike, and he makes $27,000. And then the next entry is John. And let’s say that he makes $65,000 a year. We have Rebecca, and she makes $60,000 a year. And then finally we have Tom, okay? And I’m lowercasing these names and not really caring too much about spelling because it’s just an example. We don’t want to get bogged down by the details.
So here’s our employees and their salaries. So if I wanted to, for example, just do a basic loop over this dictionary, let’s see what happens. So we can say for person in this employee’s dictionary, let’s print what person is. All right? So let’s do this. And notice it gives us the names of those employees. So by default, the key is what is being printed. That’s what this person variable represents. Again, this variable could be anything. I could call it v or k for key and print k here, and it will work exactly the same, right? Now, what if I wanted to get the values? Or what if I wanted to get the entire entry, right? This dictionary has 1234 items in it. So what I could do is I could say for item in employees or for let’s call it entry in employees, I want to actually get the entire entry, the employee’s name, as well as their salary. How would I do that? Well, for that, we use a simple method called items. All right? So we do employees items, okay? And so now we can print the entry.
And you’ll see that because we are actually looping through the items, it’s going to give us the entire item or the entire entry. So let’s print this and boom. There you go. Notice it returns mike as well as his salary, John as well as his salary and so on. Now, by default, this returns when you invoke the items method on the employees object. On this dictionary, the entry is actually a tuple, okay? That’s what Items is supposed to return. It returns a bunch of tuples, which contains the key value pair. If I was to do the type function on the entry. You’ll of course see that these are all tuples. Okay? So you saw how we can get just the keys. You saw how we can get the entire entry. What if we wanted to just get the salaries, just the values that are in the dictionary for each of the employees? Well, we use the values method. So instead of dot items, we could dot values.
Okay? And let’s just print well now instead of entry, let’s call this salary. And we can print the salary just so it’s easier for us to read the code. Again, you can name this variable anything. I’m repeating myself multiple times here. So here you go. 27,060, 5000 and so on. And again, notice the order. It’s in the exact order in which we are looping through one at a time. Okay? Now you can imagine there’s a values method. There’s also a keys method like that keys. And this is what is happening by default. If you actually get rid of this method and just do employees, you’ll remember that it gives just the keys. Okay? So just keep that in mind. So let’s change this to a key. And just to show you for the sake of completeness, let’s run this and you’ll see that now we’re getting the keys, the names of the employees. Now what if we wanted to be able to iterate through this dictionary but unpack the data? Is there a way for us to reference the key as well as the value? Well, like I said, you could use items method and then be able to parse using the notations that I talked about with tuples. If you want to get the first value of a tuple, the second value of a tuple, or so on.
But another way of doing it is actually unpacking this. So what you could do is let’s get rid of this keys function or method rather because it’s being invoked on an object and we’ll talk more about the difference between a method and a function later. I have been hinting to you the difference slightly here and there. So we’ve got the key and then we put a comma and value and now all of a sudden magically, we’re able to unpack each of these entries.
Okay, pretty cool. So now what I could do is I can print the key individually and I can print the value individually. Okay? So let’s run this. Now I made this error on purpose because I want you to figure out what’s going on here. Why do you think this did not work? I just went over this. Remember, if you want to get the actual entry, you actually have to dot items, okay? You have to invoke the dot items method on the employees and only then we get access to both the key as well as the value. And so now this should work. Let’s run this and there we go. We get Mike his salary, john his salary, rebecca her salary, and so on. Now, each of the items, like I said before, are being treated like a tuple, okay? So essentially these are when I define these variables, key and value up here, this is essentially a tuple. I can leave this formatting here, and I can say there’s a tuple in each of the items in the employees because that’s just how the data is stored in the dictionary.
And this will work, of course, exactly the same way. Let’s say if I wanted to only print the values, we would do something like that. Now, again, these variables could be anything. We could put k or NV to represent the key value, and we would just have to reference the right variables there. This will work exactly the same. So this idea of being able to extract each of the components within an item in a dictionary is known as unpacking. We are unpacking the structure of this dictionary for each of the items, and this dictionary has four items in it. Now, as you can imagine, it would be the same way for a tuple or a list of tuples, right? So let me actually restructure this and change this employees to actually a list of tuples. So first let’s make it a list. And then what I’m going to do is I’m going to put a comma between each of these entries and turn each of the entries into a tuple. All right, let’s put a tuple here, and then we’ll make Rebecca also a tuple, and tom as well, a tuple.
Now, again, for tuples, it needs to be separated by a comma. So this colon would not work. So let’s change these colons to commas. And now this code will not exactly work the way it was before, okay? Because again, this items method is supposed to be invoked on a dictionary. This is no longer a dictionary. It’s a list of tuples. All right? So let’s get rid of this dot items thing because that won’t work. And so now we have the entire list here, and we are going to unpack each of the items in that list, okay? And so four items are being unpacked into the key and its value each of the tuples. And so now this code will work. Again, we have to remove the dot items because there’s no longer a dictionary. And there we go. We can see the result. You can print the key. You can of course also print the value, both of them together.
There we go. We could change this to name and then salary, and it will work exactly the same way. I’m being redundant here because we want to make sure everyone gets this. Okay? So this is actually what is known as unpacking, or unpacking each of the items in a collection of data by referencing each of the values. Now, if we had a tuple with three items let’s say we have their salary as well as their age. Let’s say Mike is 29, john is 47, rebecca is 62, and Tom is 29. Okay, so now we’ve got these ages as well. If I run this the way it is, notice it’s going to give me an error. It says too many values to unpack what is name and salary. Obviously the computer is not smart enough to know that this is a name and this is a salary. It’s seeing that a tuple has three values here, but I’m trying to unpack two values. So what are we trying to do here? Because it doesn’t know whether this is the salary or this is the salary. It’s not smart enough for that. So we have to actually give the third thing. So we put a comma here, and you can call it anything, really. Instead of age, I can call this gibberish. It doesn’t really matter. As long as I have that third thing that represents the structure of each of the items in this list, it will be working fine. So let’s run this. And now notice we get Mike and its salary, john and his salary and so on. We don’t even have to get the age if we don’t want to.
But the structure here, if we’re unpacking, it’s important that we have the same structure as for each of the items in the list. And if I ever wanted to get access to that, of course I have that. I could print whatever. Let’s change this to an age because that makes more sense. And let’s run this. And there we go. And again, after each of these entries, if I wanted a space, maybe it’ll help to format the output here a little bit. So let’s just print a little space. So now we have Mike and its data, john and his data, rebecca and her data, and so on with a space after the entry.
So practice this concept of unpacking. Create your own tuples, your own dictionaries, your own lists containing various tuples, and play around with this. Now, let’s say for one of the tuples has different data. Let’s say this particular entry just has two values. So this tuple has three values, but then you’ve got a tuple with two values. We’re going to run into an error. Let’s run this. And of course we run into an error. Not enough values to unpack expected three.
Got two. Where is it getting this expectation of three, this expectation of three? It’s getting from this for loop structure here where I’m saying that each of the entries in the employees list is going to look like this. And so it’s fine with the first entry. Notice it did print down here, it did print Mike his salary in his age. But then as soon as it gets to the second entry, this structure no longer complies with the definition that we have down here in the for loop. And so that is why it crashes.