Controlling the Flow of Your Program
00:00 Now you’re getting onto some really exciting stuff. You’re going to be able to control the flow of your program. Based on certain conditions, you’re going to let your program flow one way or another way.
00:12 A good way to think about this is about creating branches. A program can consist of many, many branches, although generally, when you’re working on programs yourself, you want to try and keep the branches to a minimum just because whenever you come back to your code after a while, if you have to work out what’s going on in this very complex and highly branched conditional structure, that can be quite hard to take on.
In this lesson, you’ll be learning about the
if keyword, the
else keyword, the
elif keyword—which in other languages is called the
else if keyword, but here at Python, it’s abbreviated—and you’re going to learn about the
else block, how these keywords chain together to allow you to form branches.
In this indented block, you can put anything you like. You can put another
if statement, and that’s where this idea of branching comes in. So you can put another
if statement and then another
if statement and then branch off into infinity.
But you can put in anything that you like within this indented block. The key is that anything in this indented block will only run if the condition is true. Anything that’s not indented, like the
print("done"), is outside the
if construct and so will always run no matter what the condition is.
Both of these are completely separate from each other. However, the second one has
if False: so the indented block within here, the
print("Hello"), will never print because
False can never be
True, and the
if statement will only execute the indented block corresponding to it if the condition evaluates to
03:04 To drive all of this home, it’s best to look at examples. And one of the canonical examples for looking at if statements is a school grading example. You have a bunch of values, and you need to determine whether the grade is a passing grade or a failing grade.
To get started with your grading program, you’re going to need some kind of input. For this example, you’re just going to define a variable with the name
grade and a numerical value of numbers between
100. Now to get started with your branching program, you are going to start with an
if block. Now that starts with the
if keyword. Then on the right of the
if keyword you need an expression that will evaluate to
So if it’s greater than or equal to
50, you want
True. If it’s less than
50, you want
False. You can take the
grade and use the
>= operator with
50. So that will take grade
60 and evalute to
True, which is the behavior we want right now.
And that’s it. Maybe you also want another message to be printed at the end just to indicate that the program is done. So you could have another
print() function call here that says
"Grading done." So now if you save this and then run it, F5, you can see that you have an output that says,
You passed! Grading done. To walk through this step by step, you’ve got the variable at the top,
grade = 60.
Then you have an
if block. It starts off with the
if keyword, and then it has a conditional expression, which evaluates to
False. This takes
grade, which is
60, and asks if
60 is greater than or equal to
50, which evaluates to
Now, if you put the
grade as equal to
50, what do you think will be the result? So let’s save and run, and it says
You passed! because if the grade is greater than or equal to
50, then it will print
"You passed!" Let’s go back to a lower grade, say
30. Now, if you save and run this, you’ll see that it says
Grading done. but it doesn’t give you any messages. So say you wanted to add something that will give you a message with a lower grade, and it says something like,
"You failed." So you can do this with another
if block. You’ll get to better ways of doing this later in this lesson, but for now you can say
grade < 50:
if blocks are totally separate from each other. They’ll always evalute each time, and you’ve just created two with conditions that will cover the whole range of possible numbers. So,
>= 50 or
So now any number that you pass in there will end up printing one of these two messages:
"You passed!" or
"You failed :(" But you could mess with this and say,
if this was
< 60, you say
"You failed :(" and if you had a grade of say,
55, what do you think will happen here?
So if you save this and run it, you’ll see that you get both messages now, because if a grade
if grade >= 50, which
55 is, it’ll print
"You passed!" But then it does another test because there’s another
if block that says if it’s
< 60, say
"You failed :(" So since
55 is less than
60, it will print
"You failed :(" So you definitely want make sure that your conditions are consistent with each other if you’re taking this approach. But coming up soon, you’ll be looking at new keywords, like
else, to help you manage these kind complementary conditions.
else keyword can’t exist in isolation. It has to be accompanied by an
if statement. The syntax for that would look something like this. You have your
if keyword, then you have the condition, as you’ve just seen, then you have your indented block. Again, as you’ve just seen, the indented block will only run if the condition is evaluating to
else keyword is linked to the original
if statement. The way it works is that if the condition on the original
if statement evaluates to
False, then its indented block won’t run, but the indented block of the
else block will run.
else keyword is stand-alone. It’s always
else with a colon. With the addition of this
else keyword, the
if block is now all linked up together. So, the
if block stretches from line 3 to 7, includes
if grade >= 50: print("You passed!")
else: print("You failed :(") So that’s actually quite readable.
You passed! Now, if you change that grade to
40, the way the
if block works now is that it checks
if grade >= 50. Grade
40 is not, so that’s
False, so this indented block on line 4 will not run.
So then it’s going to look for other parts of its block. The
else keyword is another part of its block. And it’ll say, okay, since the
else has been reached and the condition before that was
False, that means that this will be printed.
print("You failed :(") It acts like a fallback. Basically the way that the
if block works now is that you have one condition, and if that is met, it’ll present one behavior. In any other case where that condition is not met, it will print
"You failed :(" So let’s see that in action.
Bear in mind that you can add in a whole bunch of spaces here, and that
else portion of the
if block will still be linked up. So if you run and save this, you’ll see that it still has the same behavior.
This is necessary in all cases. And then you have your
else block at the end, which again is optional, and it will run if none of the conditions in between run. You have your
elif keyword, and this one takes a condition, and it behaves in exactly the same way as the
If this condition evaluates to
True, then it will run this indented block. The special thing about
elif is that you can have many of them between the
else. You can have ten of them, twenty of them, as many as you like, but you can only have one
if and one
else per structure.
So in the whole
if structure, it will test them all out one by one, until it reaches the first one that is true. If one down the line would evaluate to
True, it doesn’t matter because once it reaches the first one that’s true, that’s the one that will execute. Now it’s time to apply that to the school grading example.
14:31 Picking up where you left off on your grading program, now what you’ll want do is create a stratified grading structure that will be able to give you an A at a certain grade, a B, a C, and also tell you if you failed.
Let’s start off with a comment—with a triple-quoted comment, which allows you to make multiline comments—and write a plan for your program. Say you want an
A grade to be
B grade to be
C grade to be
50-59, and fail to be
less than 50.
All right, with your knowledge now of
else keywords, how might you go about creating this program? First of all, you’ll probably want to start off with the highest grade and work your way down.
You can do it in reverse order, but here you’re going to do it from the top starting down. So instead of
50 and just checking if they passed, you can say, if it’s
>= 70, which is the
A grade you defined above, you can just say,
"You passed with an 'A'".
So now you want another condition to be part of this same
if structure. So what keyword will you use here? That’s right, an
elif keyword. The
elif keyword allows you to add in another condition, unlike the
else keyword, which has no condition. It’s just like a fallback.
So you can say
if grade >= 60, now you can define a complex conditional statement here, which checks the range, but since this is all part of the same
if structure, you can be sure that if the first condition doesn’t pass—
if grade >= 70, you know that the number is not going to be
>= 70 by the time it gets to this condition.
And the last statement, the
print("You failed :(") you can just leave it as it iss. Now again, the
else has this sort of implicit condition built into it that basically says it’s less than
70, it’s less than
60, it’s less than
50, which you can sum up as a sort of implicit grade of less than 50, which will give you
You failed :( Now just to reiterate, line 10 to line 17 are all the same
if block. It’s all part of the same structure. You can add in spaces between the conditions. That won’t affect the whole structure.
Only one of these indented blocks can ever run on one execution. You can’t work the conditions in such a way as for the first
if indented block to run and then the third one to run, because as soon as the first one runs, then the
if block exits, and goes to the next line, the next unindented line, which is
print("Grading done.") Okay, so time to give this a bit of a test. Let’s try a grade of
80. Save and run.
19:20 Now, a quick final note. The colon is very important. If you miss out a colon, which is a very common mistake—everyone does it, from time to time—let’s just have a look at the error that you might get for that.
It’s not going to search randomly for a condition that will result in a
True value. It’s just going to go line by line, condition by condition, until it finds a
True value. Once it finds a
True value, it’s going to run that indented block and then exit.
Become a Member to join the conversation.