Flow Control in Python

Developed with
QA

Contents

keyboard_tab

The course is part of this learning path

Practical Data Science with Python
course-steps 3 certification 4 lab-steps 3
play-arrow
Start course
Overview
DifficultyAdvanced
Duration49m
Students16

Description

Continuing on from Practical Data Science with Python, this course explores a variety of Python features in a practical, hands-on way. It starts by looking at Python functions and you are given a guided walkthrough of a range of functions relating to data science. It then moves on to dictionaries in Python and how to create them. After that, you'll be guided through flow control in Python, loops, and finally, you'll be shown a technical demonstration in Python looking at classes, variables, and stringification.

Learning Objectives

The main objective of this course is to enhance your knowledge of Python, and learn about Python functions, loops, dictionaries, and flow control.

Intended Audience

This course is intended for IT professionals who already have a good knowledge of Python and who want to enhance that knowledge from a data science perspective.

 

Transcript

Hello and welcome back. We're going to look at flow control now. What do I mean by flow control? So if we look at the flow of everything that we've written so far, it's just been sequential. It's been do this, do this, do that, do that, etc. We can implement structures that will branch off and carry out certain actions if certain things happen to be true or false. And that's using if and else statements.

So what do we want? We want new statements. Age, I'm going to set it to 18. So can we put in, if age is greater than 65, print, see retirement plans. If age is greater than, let's say, 30, I'm going to print, see career plans. And then if age is greater than 16, we'll print, see education plans, and else we'll print, see your mother. Great, okay.

So how is this working? What's going on here? I've got retirement in there, career planning, education plans. So what we have is an if else branching with our statement where certain lines of code are only going to evaluate if something's approved. If a condition is met, then it will do something. So if one of these conditions is met, a line of code will evaluate. It's always going to do with true or false Boolean statements. You can only ask if to something Boolean. So we have if and then we have some Boolean expression, elif and then some other Boolean expression, and then we have a final else here.

So if is the first question that we ask, everything after that, if we want it to be part of the same block, is going to be an elif, that's how we can say we want to ask more questions, elif this, elif that, etc. And then finally, if none of the above statements evaluates as true, we have an else statement at the end.

So as I change this value, I should be getting different things printing out. That's what we should expect. If I have a nine-year-old child, then it should show see your mom, okay. So this is where we can control the flow of our program. Each of these blocks carries out certain actions depending on whether the Boolean evaluates to true or false.

Structurally, it's quite similar to a function statement in that we have a keyword. Here we have a Boolean statement, whereas in a function, we would have the function definition, but then it's finished by a colon, and after the colon we indent to associate this bit of code with the above statement. So this is our if else statement.

What other methods of control do we have? What do we have available to us if we want to perform an action multiple times? We have for loops and we have while loops. And while loops impact for loops. Those are the two main kinds of loops. We'll have a look at while loops first, because while loops are quite literally just Boolean expressions that evaluate continuously. 

So I've got a list of happiness scores here. If I wanted to, I could add an action individually to each of these and then remove them from the list whenever it's actually carried out its action. I can use my while the length of happiness is greater than zero, and I can run print happiness.pop. So dot pop removes the last element. It removes the last element from the list and returns it.

So what are we asking here? So while the length of the list is greater than zero, greater than having nothing in it, we want to print happiness.pop. And then the dot pop is what makes this stop because eventually the list will be empty. That's when we go and do something else. I'm going to redefine happiness to be this collection of scores just here, because otherwise I have to go and find this definition somewhere else.

So we can see that from the end, we're printing out iteratively each of the elifs, again, somewhat similar to function statements in that you have keyword, expression and then what you want to do after you've evaluated that. Now we can actually define as well, because this is just an if statement that continually evaluates again, and again, and again, we can actually define an else to be carried out when we actually finish looping through. I can print out, I'm all done.

So when we actually finish this loop, we print out that we finished our loop. And we can do that using an else statement. So that's the while loop. So with while loops, we tend to use a little less frequently than we do for loops. We'll have a look at a for loop here. We can use happiness again. So if we just use happiness, if I want to carry out an action for each element in happiness, for each element in happiness, and I wanted to say print out the element and actually update the underlying structure. And I could run it like this.

So what this is going to do is this is going to iteratively move through my collection, pulling out element by element and kind of sorting it in a local variable called element, each time I pull it out, then I can do whatever I want with element. I could do elements to the power of 100 every single time. But then if I have a look at my final list, we will see that I've not actually changed the underlying structure. This is a local copy.

If I wanted to change the underlying structure, I would have to specifically say I wanted to change the underlying structure. So I can do that using things like enumerate, or defining an iterator. They're somewhat syntactically the same. So this is just performing an action on a local copy.

If I did want to update the underlying element in the happiness list, I could do something like enumerate. And what this does is this adds an index to my iteration. So if I just print out, i and element first, comment out this, we should see that I've got the first thing that's getting printed out is the index location of the element. The second thing is the element itself. Then if I wanted to update the element in list, I can have happiness if i. Well, in my case, I can do star star equals two, or I could do star star equals 100 if I want to, if I want to do every element to the power of 100. I have some very low numbers in my list. So it enumerates the sort of thing that you will see pop up quite frequently when you want to update the values in the list.

There is something called the dict, which we can have a look at a bit later in the course.

Now, I would like to have a look at one final thing. This is a comprehension. So comprehensions are a special kind of for loop. They carry out the loop, and will then put the result of the loop into a container. So be it a list, a dictionary, a set, or a tuple, or whatever you like. So they're designed to build up data structures.

So we'll have a look at a nice sample one to start with. We have things like i times 10, or i in range five, I'll go range 10. So we've already seen the range function, range function, by default, will give you a range of numbers between zero and the upper limit that you put into the brackets. So we're getting numbers between zero and nine in here. What this comprehension is doing is it's taking each element out of this and it's multiplying it by 10. And then we set square brackets around it, it's putting these in our list.

So this would be entirely equivalent to me defining a list at the start, writing for element in range 10, ls.append element times 10. This is entirely equivalent. It's just much easier to do it for our comprehension. The way to read comprehensions is to start with the for bit. I always recommend starting with the for. So you're saying for i or for elements in range 10, take the elements and multiply it by 10.

In this case here, we can say for elements in range 10, we're going to do ls.append element times 10. These are really quite specific to Python. You'll see these popping up all the time.

Now what is making this a list is the fact that we simply have square brackets around it. I could define, for example, a dictionary comprehension by changing the brackets and simply specifying that I want two values to come out of this. I want element giving me the original element, and then as my feed, and then for my value, I want element times 10.

So then what I'm getting is a dictionary of the value, and then the value after I perform whatever transformation I wanted to perform, that turns this into a dictionary comprehension. We can do this for sets, we would just have to specify a single value for a set. For dictionary, we have to make sure that we specify these things.

We can chain together more complicated commands as well. So we can include if statements and things like that within a list. We could ask if for elements in range 10, element times 10. If element is divisible by two, then I'll only get even numbers out, percentage two double equals zero. And you can see we have an error message, so I'll change this to four element times 10. If that, else zero, something like that.

Okay, so this is now a set comprehension. I want to have a list comprehension here. So I can combine together sort of a more complicated versions of these where I'm putting the element times 10 if it's divisible by two, otherwise I'm putting in a zero. So now I've only got the even numbers coming out of this here.

About the Author

Delivering training and developing courseware for multiple aspects across Data Science curriculum, constantly updating and adapting to new trends and methods.

Covered Topics