supplying a series of instructions, which our scripts follow in a specific order regardless of the inputs received. However, now that we have precise ways to compare values to one other, we can start to build logic into our programs; this will let our code "decide" to go in one direction or another based on the results of our comparisons.
We can do this by using if statements to test when certain conditions are True .
NOTE: The 'if' statement is one of the most commonly used 'things' in Python (or
any programming language, for that matter). If you're flying through this course, slow down at this point and really focus on integrating this material.
Here's a simple example of an if statement:
if 2 + 2 == 4:
print("2 and 2 is 4") print("Arithmetic works.")
Just like when we created for and while loops, when we use an if statement, we have a test condition and an indented block of text that will run or not based on the results of that test condition. Here, our test condition (which comes after the if
keyword) is 2 + 2 == 4 . Since this expression is True , our if statement evaluates to True and all of the code inside of our if statement is run, displaying the two lines. We happened to use two print statements, but we could really put any code inside the if statement.
If our test condition had been False (for instance, 2 + 2 != 4 ), nothing would have been displayed because our program would have jumped past all of the code inside this "if block" after finding that the if statement evaluated to False .
There are two other related keywords that we can use in combination with the if keyword: else and elif . We can add an else statement after an if statement like so:
77 Control the Flow of Your Program
if 2 + 2 == 4: print("2 and 2 is 4") print("Arithmetic works.") else: print("2 and 2 is not 4") print("Big Brother wins.")
The else statement doesn't have a test condition of its own because it is a "catch-all" block of code; our else is just a synonym for "otherwise." So if the test condition of the
if statement had been False , the two lines inside of the "else block" would have run instead. However, since our test condition ( 2 + 2 == 4 ) is True , the section of code inside the "else block" is not run.
The elif keyword is short for "else if" and can be used to add additional options (or conditions) after an if statement. For instance, we could combine an if , an elif , and an else into a single script like this:
num = 15 if num < 10: print("number is less than 10") elif num > 10: print("number is greater than 10") else: print("number is equal to 10")
After creating an integer object named num with a value of 15, we first test whether or not our num is less than 10; since this condition is False , we jump over the first print statement without running it. We land at the elif statement, which (because the test condition of the if statement was False ) offers us an alternative test; since 15 > 10, this condition is True , and we display the second print statement's text. Since one of our test conditions was True , we skip over the else statement entirely; if both the if and the elif had been False , however, we would have displayed the last line in the
else statement.
This is called branching because we are deciding which "branch" of the code to go down; we have given our code different paths to take based on the results of the test conditions. Try running the script above and changing num to be a few different values to make sure you understand how if , elif and else work together.
78 Control the Flow of Your Program
You can also try getting rid of the "else block" entirely; we don't have to give our code a path to go down, so it's completely acceptable if we skip over the entire set of if / elif statements without taking any action. For instance, get rid of the last two lines in the script above and try running it again with num = 10 .
It's important to note that elif can only be used after an if statement and that else can only be used at the end of a set of if / elif statements (or after a single if ), since using one of these keywords without an if wouldn't make any sense. Likewise, if we want to do two separate tests in a row, we should use two separate if statements. For instance, try out this short script: if 1 < 2: print("1 is less than 2") elif 3 < 4: print("3 is less than 4") else: print("Who moved my cheese?")
The first test condition ( 1 < 2 ) is True , so we print the first line inside the "if block". Since we already saw one True statement, however, the program doesn't even bother to check whether the "elif block" or the "else block" should be run; these are only
alternative options. So, even though it's True that 3 is less than 4, we only ever run the first print statement.
Just like with for and while loops, we can nest if statements inside of each other to create more complicated paths: want_cake = "yes" have_cake = "no" if want_cake == "yes": print("We want cake...") if have_cake == "no": print("But we don't have any cake") elif have_cake == "yes": print("And it's our lucky day") else: print("The cake is a lie.") In this example, we first check if we want cake - and since we do, we enter the first "if block". After displaying our desire for cake, we enter the inside set of if / elif statements. We check and display that we don't have any cake. If it had been the case 79 Control the Flow of Your Program
that have_cake was "yes" then it would have been our lucky day. On the other hand, if have_cake had been any value other than "yes" or "no" then we wouldn't have displayed a second line at all, since we used elif rather than else . If (for whatever twisted reason) we had set the value of want_cake to anything other than "yes", we would have jumped down to the bottom else and only displayed the last print statement.
Review exercises:
1. Write a script that prompts the user to enter a word using the input() function, stores that input in a variable, and then displays whether the length of that string is less than 5 characters, greater than 5 characters, or equal to 5 characters by using a set of if , elif and else statements.
80 Control the Flow of Your Program