Conditional Statements
Now we will put boolean expressions and comparison and logical operators to use by forming complete conditional statements. The premise behind a conditional statement is we use these tools to change the behavior of our program based on whether or not a condition is met. There are two types of conditional statements: if statements and while loops. We’ve already discussed while loops in a previous lesson. Here we focus on if statements.
The if statement
The syntax of an if statement looks like this:
if <boolean>:
<instructions>
The statement will work as long as there is something that evaluates to a boolean following the if, followed by a colon. Then, just like when using loops, the instructions to be executed if the statement evaluates to True should all be indented. Once indentation stops, program flow returns to outside of the if statement and back of the main body of the code. Let’s do an example.
[1]:
#Solve ax^2 + bx + c = 0 for x
a = 2
b = 5
c = -3
if (b**2 - 4 * a * c) > 0:
result1 = (-b + (b**2 - 4 * a * c)**(1/2))/(2*a) ##remember, ** is the exponent operator
result2 = (-b - (b**2 - 4 * a * c)**(1/2))/(2*a)
print("Result 1: {}, Result 2: {}".format(result1,result2))
Result 1: 0.5, Result 2: -3.0
Again, the instructions after the if statement are only executed if the expression b**2 - 4 * a * c evaluates to True. If it doesn’t, then program execution skips those instructions and proceeds to the line that is indented at the same level as the if statement.
Note that we can do things like nest an if statement in a for loop:
[2]:
myText = "Time altitude latitude longitude density"
i = 0
for word in myText.split():
if word == "density":
densityColumn = i
i += 1
print(densityColumn)
4
This example splits a text string and searches the resulting list for the word “density”, then returns its position, in this case 4 (starting from 0). Note the i += 1 line here. Since that line is indented at the same level as the if statement, it is not part of the if instructions. That line is executed every time the program flow passess through the for loop instructions. Only if the value of word is “density” do the instructions inside the if statement get executed.
The else clause
If statements allow us to make our programs do something if some condition is true. But what if we want to do one thing if our condition is true, but do something else if the condition is false? That’s the purpose of the else clause. Let’s modify the quadratic example from above to see how this works.
[3]:
#Solve ax^2 + bx + c = 0 for x
a = 1
b = 2
c = 10
discriminant = b**2 - 4 * a * c
if discriminant > 0:
result1 = (-b + (discriminant)**(1/2))/(2*a) ##remember, ** is the exponent operator
result2 = (-b - (discriminant)**(1/2))/(2*a)
else:
print("The result is complex!")
realpart = -b/(2*a)
imagpart = (-discriminant)**(1/2)/(2*a)
result1 = "{} + {}i".format(realpart,imagpart)
result2 = "{} - {}i".format(realpart,imagpart)
print("Result 1: {}, Result 2: {}".format(result1,result2))
The result is complex!
Result 1: -1.0 + 3.0i, Result 2: -1.0 - 3.0i
The important thing is that it isn’t possible for both sets of instructions to be executed. Either the discrimiant is greater than 0 and the first set is executed or it isn’t and the second set is executed. The if-else statement makes it possible to have 2 separate branches of program flow. When the program runs, exactly one branch of instructions will be executed while the other will not.
One more thing to note, as we’ve seen it is possible to use an if statement without the else clause, but it isn’t possible to use the else clause with out the initial if statement.
The elif clause
In python, elif is shorthand for “else if”. Maybe your test is more complex than simply true or false. Maybe there are more than two branches that you want to choose depending on what your program is doing. In the density example above, our text list had 5 words in it, but we only extracted information about a single one. What if we wanted to know the position of “time” and “altitude” as well? That means we need three branches! The elif clause allows us to do exactly that.
[4]:
myText = "Time altitude latitude longitude density"
i = 0
for word in myText.split():
if word == "density":
densityColumn = i
elif word == "Time":
timeColumn = i
elif word == "altitude":
altitudeColumn = i
i += 1
print(densityColumn, timeColumn, altitudeColumn)
4 0 1
We can use as many elif clauses as we want. But, we are limited to 1 if clause (it must be the first branch) and 1 else clause (if used, it must be the last branch). Also, each condition is checked in order. Once one of the conditions is met, the corresponding branch is executed and then the entire statement ends. So, if more than one condition is true, only the branch corresponding to the first one will be executed.