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.
The first keyword is the
if keyword. Now, whenever you use the
if keyword, you are creating a branch. The statement starts with
if, and then you insert a condition.
This condition just needs to be something that evaluates
False. You can even put in the
False directly if you want to.
It just needs to be something that
if can understand as
False. After the condition, you insert a colon (
:), which starts an indented block.
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.
For example, here you have
if True: so this indented block that starts with
print("Hello!") will always run, no matter what. And then you have another
if statement here.
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
So the full result of this program is that it will print
"Hello" and then print
"done". The middle
print("Hello") statement will not execute.
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 how would you create an expression that takes
grade and evaluates to
False depending on whether the value is greater than or equal 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.
04:20 After this expression, you add a colon. Now that starts an indented block. Now you have to put something in this indented block. So how about a message to indicate a passing grade?
So you could use a
print() function here to say
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
So then this condition will run. So that means the indented block belonging to the condition will run, which prints
"You passed!" And then the final
print() function call
is unindented. It’s not indented like the
print() function call that says
"You passed!" It’s unindented, which means it’s not part of the
if structure. It’s separate.
So this will run unconditionally unless you encountered an error or something went wrong before that. But if everything goes normally, the
print() function on line 6 will always run.
So that’s your first
if block. Now you can play around with the
grade value. So let’s try something like
40. Save and run.
And now you’ll note that the only message you get is
Grading done. Since the conditional expression evaluates to
False, the indented block of that condition will not run.
So it just skips over this and goes straight 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:
Okay, so now, if a grade is greater or equal to
"You passed!", but if a grade is less than 50, it will say
"You failed :("
So if you save and run this, and now you have that message,
You failed :(
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.
Now it’s time to look at the
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
Now, afterwards, you have the option to add an
else block. That’s by adding the
else keyword with a colon (
else keyword can’t have a condition.
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.
So, to repeat that: if the condition is
False, then the
else block will run. So this is a handy way to express something with just one condition.
Say you were looking at your school grading example, and you just had a pass or fail around 50. You could say,
if [condition] grade over 50, then you passed.
else, you fail.
10:31 So if you don’t pass, you fail. Now let’s extend the school grading example with this new knowledge.
Now you know about the
else keyboard, so how might you change this code to be able to take advantage of the
else keyword? There’s just one line that you need to change.
It’s line 6. If you insert the
else keyword here—and remember, you don’t add any expressions, any conditional expressions on the right of the
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.
It will take a grade of say,
55, and if the grade is
>= 50, it will print
"You passed!" And then it’s not going to continue with the rest of the
It’s going to exit the
if block and go right to line 8, or the next line, line 9, where it says
print("Grading done.") So let’s save that and see that in action.
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.
Save and run, and it says
You failed :(
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.
13:00 Usually you don’t add in so many spaces here. You’ll just have this on consecutive lines like this. But if you add in spaces, that’s not a problem. It’ll still run the same.
Now for another optional part of the
if statement, the
elif keyword. It’s another optional keyword. You’ve got your
if and your condition at the top.
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.
And it’s important to note that if the
elif condition evaluates to
True, then that one will run and none of the other ones will run.
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'".
Now I’m using single quotes (
') here, because this is enclosed in double quotes (
"), and you can’t use double quotes here or else that will give you strange errors.
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.
>= 70 condition is implicit by the time you get to line 12, where you’re asking if
grade >= 60.
16:52 So here you can pretty much copy this message from
grade >= 70, except you change the grade to a
'B'. So now you’re just missing the
C grade. How might you go about that?
You can actually just copy most of the last
elif part and just paste it, change the condition to be
>= 50, and change the grade to a
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.
You passed with an 'A'
Grading done. So how about try a grade of
70. So what grade should that be?
You passed with an 'A' because it’s greater than or equal to to
So how about
'B'. Correct. How about 60? Should also be a
'B'. Nice. How about
You passed with a 'C'. Great. How about
It should also be a
'C'. Fantastic. And how about
You failed :( Oh, dear. Anyway, that is your branch program.
19:13 Congratulations. You’ve coded a program that will run very differently under different conditions.
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.
You’re getting a
SyntaxError. So if you see a
expected ':' then it’s probably because you’ve missed out a colon on your
if block somewhere.
19:43 Also note that the order is extremely important. The first conditional expression here will be the first one to run, and then it will try the next indented block.
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.
In this lesson, you’ve learned about the
if keyword, the
else keyword, the
elif keyword, and the
else block, and you’re now ready to start creating branches for your program.
Become a Member to join the conversation.