Conditional statements
Contents
7.3. Conditional statements#
Conditional statements are statements that only execute when certain conditions are met. They are also an example of control flow statements because they, like loops, control the order through which statements are executed in our code. Unlike loops, which repeat lines of code over and over, conditional statements create decisions in Python – you can think of them like creating forks in the road for the computer. Under some conditions, the computer will do one thing, while under another it will do another. Of course, as ever, we also tell the computer what those things are.
if
statements#
The simplest conditional statement in Python is an if
statement. This instructs the computer to carry out a line of code provided a given condition is met. For example, the below code will print the value 2 because \(x<10\).
x = 2
if x < 10:
print(x)
2
An if
statement contains the following components:
if
tells the computer we are creating a conditional statementAfter that we write a
test_expression
, which is what the computer will evaluate to True or False (in the above example, our test expression isx < 10
.We put a
:
at the end of theif
statementBelow that, we includes
statement(s)
for what the computer should do if the condition is True
Put together, they look like:
if
test_expression:
statement for if
The below code, however, will not print anything, because the condition \(x<10\) is not met. Notice, as we saw in the loops section, while it doesn’t print anything, it also doesn’t throw an error, as there’s nothing syntactically incorrect in the code. The condition simply is not met, so the statement print(x)
is not carried out.
x = 11
if x < 11:
print(x)
if ... else
statements#
Suppose we want to specify something for the compute to do if the condition \(x<10\) is not met. In other words, rather than just return nothing, we want it to carry out something. In this case, we can use an if...else
statement, which allows us to provide two mutually exclusive conditions under which the computer will carry out particular statements. For example, we could write:
x = 11
if x < 11:
print(x)
else:
print('x is too big to print')
x is too big to print
In this case, we printed the string 'x is too big to print'
because the value of \(x\) did not satisfy the condition under if
. The general syntax for if...else
statements is:
if
test_expression:
statement for if
else:
statement for else
Again, notice the all-important :
after both the line containing if
and after else
.
if ... elif ... else
statements#
We don’t need to limit ourselves to just two conditions under which there are instructions. We can use elif
to add additional conditions. For example:
x = 11
if x < 11:
print('x is too small to print')
elif x==11:
print('x is 11, as we all hoped')
else:
print('alas, x is too big to print, sorry to say')
x is 11, as we all hoped
In the above example, the condition x==11
was True, so our program printed 'x is 11, as we all hoped
. The general syntax for if...elif...else
statements is:
if
test_expression:
statement for if
elif:
statement for elif
else:
statement for else
Finally, we don’t need to limit ourselves to simply three conditions. Provided the conditions are mutually exclusive, we can list many. To do this, we use more than one elif
, as below:
x = 12
if x < 11:
print('x is too small to print')
elif x==11:
print('x is 11, as we all hoped')
elif x==12:
print('x is so close, yet so far')
else:
print('alas, x is too big to print, sorry to say')
x is so close, yet so far
There is in principle no limit to the number of elif
statements we can use in Python, though in practice we may be limited by computational power – as well as our ability to keep track of what on Earth we’re doing. Generally speaking, it’s rare to see lots of elif
statements for both practical and aesthetic reasons. Note, however, we can only use if
and else
once per conditional statement.
We also generally want to make sure that all of our conditions are mutually exclusive; i.e., that there are not cases where, for example both the if
and elif
statements are true. As can be seen in the below example, when this is the case, the program only prints the first instance when the condition is satisfied. While the below code does not generate an error, it’s worth evaluating our goals and asking if we need to keep the code that complicated (it could be that we do, but those circumstances are difficult to think of!).
x=12
if x==12:
print('x is 12')
elif x==12:
print('or did this one run')
else:
print(nope)
x is 12
Finally, we can combine conditional statements with other techniques, such as with a for
loop below:
for i in range(10):
if i < 5:
print(i, 'is low')
else:
print(i, 'is high')
0 is low
1 is low
2 is low
3 is low
4 is low
5 is high
6 is high
7 is high
8 is high
9 is high
And, we can define the whole thing as a function!
def my_cool_function(new_number):
'''Turn the whole loop with conditions above into a function we can re-use!'''
for i in range(10):
if i < 5:
print(i + new_number)
else:
print(i, "is already high, so let's not add a new number")
And admire it in action:
my_cool_function(5)
5
6
7
8
9
5 is already high, so let's not add a new number
6 is already high, so let's not add a new number
7 is already high, so let's not add a new number
8 is already high, so let's not add a new number
9 is already high, so let's not add a new number
A word on control flow statements#
Defining our own functions and writing control flow statements such as loops and conditional statements are three very useful techniques for taking our code to the next level. Without control flow statements, we’re limited to just running our code in the order it appears from top to bottom in our program. Being able to execute certain lines of code repeadedly and/or only under certain conditions, as well as to simply and quickly re-use entire blocks of (possibly quite complicated) code by calling functions we’ve defined, we are quickly able to elevate our code from that of beginners to much more sophisticated programs. While of course there is much more out there in the world of programming – and as stated earlier in this book, one of our many goals is to inspire you to pursue further explicit coding on your own if you’re finding this part as enjoyable as we do – already with these techniques in your toolbox, you’re already equipped to build much more sophisticated programs – and thus do more sophisticated data science work!
Next steps in programming#
As we continue – you will notice we continue to introduce coding techniques that you may not have seen yet. Fear not: you are more than ready to practice becoming a real data scientist who can make sense of novel code on their own. For everything new you encounter, if you’re not sure exactly what it does, try writing it out on your own, turning it into human words (in your mind, out loud, and/or in writing, as is helpful), and tweaking small bits at a time to see what each component does. We promise: getting good at this skill is so much more helpful in the long term than simply acquiring new syntax that we spoonfeed you. (Even if it’s frustrating in the moment.)
That said: of course, as we introduce fundamentally new techniques in coding, we’ll of course flag them. We simply won’t stop to break down every line of code, as we expect you are now able to “read” or work through it yourself. Again, think of the analogy to learning Spanish: You can practice in a classroom all you want, but there will be a point where you need to go to Mexico City and just start having conversations. At that point, there will be lots of words you don’t know, but slowly you’ll get better at making sense of them given the context, and eventually your language ability will skyrocket. You can think of the rest of the book as your language immersion experience :).
Now: you may recall we gave you a little taste of this already, espcially in chapters 4 and 5 (you can think of those as field trips while still in Spanish class!). If you’d like, go back now, revisit that code, and bask in the glory that is how much you currently understand it. And, heck, while you’re there, practice it all again, and keep experimenting with it. Have fun!