In our last episode we looked at loops, one of the fundamental building blocks of programming, because they allow us repeat tasks many times. We now look at on of the other main building blocks, conditional statemnts, which allow us to make choices.
In Python we can make our programs take different actions, depending on conditions using an if
statement:
num = 37
if num > 100:
print(num, "is bigger than 100")
else:
print(num, "is smaller than 100")
print("Done")
The following decision diagram helps to understand what is happening:
We enter the section of code at the top and arrive at the diamond, where the program checks whether the value in variable num
is greater than 100. If the condition is True
the program takes the left branch, and if the condition is False
it takes the right branch. Once the conditional is finished to two branches come back together.
The else
branch can be omitted as in:
num = 163
if num > 100:
print(num, "is bigger than 100")
print("Done")
Or we can have additional elif
branches:
num = 42
if num > 100:
print(num, "is bigger than 100")
elif num == 42:
print(num, "is the Answer to the Ultimate Question of Life, the Universe and Everything")
else:
print(num, "is smaller than 100")
print("Done")
We can combine conditional statements using the Boolean operators, and
and or
. If we use these it is useful to put the conditional components is parentheses (brackets) so that our intention is clear:
if (1 > 0) and (-1 > 0):
print('both parts are true')
else:
print('at least one part is false')
if (1 < 0) or (-1 < 0):
print('at least one test is true')
We can also use the not
operator to invert the condition:
if not( (1 > 0) and (-1 < 0) ):
print('not (both parts are true)')
else:
print('false that not (both parts are true)')