Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

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.

00:43 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 ifelifelse block, how these keywords chain together to allow you to form branches.

01:06 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.

01:20 This condition just needs to be something that evaluates True or False. You can even put in the True or False directly if you want to.

01:29 It just needs to be something that if can understand as True or False. After the condition, you insert a colon (:), which starts an indented block.

01:41 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.

01:52 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.

02:15 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.

02:30 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 True.

02:52 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.

03:22 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 0 and 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 True or False.

03:51 So how would you create an expression that takes grade and evaluates to True or False depending on whether the value is greater than or equal to 50?

03:58 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?

04:34 So you could use a print() function here to say "You passed!"

04:42 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.

05:15 Then you have an if block. It starts off with the if keyword, and then it has a conditional expression, which evaluates to True or False. This takes grade, which is 60, and asks if 60 is greater than or equal to 50, which evaluates to True.

05:32 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

05:47 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.

05:57 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.

06:10 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.

06:22 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.

06:35 So it just skips over this and goes straight to "Grading done."

06:41 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:

07:32 print("You failed :(")

07:39 Okay, so now, if a grade is greater or equal to 50, say "You passed!", but if a grade is less than 50, it will say "You failed :("

07:51 So if you save and run this, and now you have that message, You failed :(

07:56 These two 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 < 50.

08:12 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?

08:32 So if you save this and run it, you’ll see that you get both messages now, because if a grade 55, 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 elif and else, to help you manage these kind complementary conditions.

09:13 Now it’s time to look at the else keyword.

09:17 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 True.

09:38 Now, afterwards, you have the option to add an else block. That’s by adding the else keyword with a colon (:). The else keyword can’t have a condition.

09:49 The 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.

10:09 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.

10:19 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.

10:40 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.

10:52 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.

11:02 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.

11:27 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 if block.

11:38 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.

11:48 It says 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.

12:06 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.

12:42 Save and run, and it says You failed :(

12:47 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.

13:14 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.

13:24 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 condition.

13:42 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 if and 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.

14:01 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.

14:10 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.

14:46 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 70+, a B grade to be 60-69, a C grade to be 50-59, and fail to be less than 50.

15:15 All right, with your knowledge now of if, elif, and 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.

15:28 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'".

15:47 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.

15:56 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.

16:16 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.

16:42 So the >= 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

16:56 the 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?

17:06 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 'C'.

17:19 And the last statement, the else: 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.

17:58 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.

18:30 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 70.

18:45 So how about 65? 'B'. Correct. How about 60? Should also be a 'B'. Nice. How about 55? You passed with a 'C'. Great. How about 50?

19:02 It should also be a 'C'. Fantastic. And how about 49? 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.

19:32 You’re getting a SyntaxError. So if you see a SyntaxError 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.

19:52 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.

20:10 In this lesson, you’ve learned about the if keyword, the else keyword, the elif keyword, and the ifelifelse block, and you’re now ready to start creating branches for your program.

Become a Member to join the conversation.