= 37
num if num > 100:
print('greater')
else:
print('not greater')
not greater
if
and else
How can we use Python to automatically recognize differences in data such that it can change what code is run depending on the data and take a different action for each? In this chapter, we’ll learn how to write code that runs only when certain conditions are true.
We can ask Python to take different actions, depending on a condition, with an if
statement:
= 37
num if num > 100:
print('greater')
else:
print('not greater')
not greater
The second line of this code uses the keyword if
to tell Python that we want to make a choice. If the test that follows the if
keyword is true, the body of the if
(i.e., the lines indented underneath it) are executed. If the test is false, the body of the else
is executed instead. Only one or the other is ever executed:
The diagram below shows how this choice is being made.
The layout of code in Python is actually pretty important. The whitespace is structural and the amount of it tells us something about where we are in a program. Whitespace is particularly important in if
. By convention the indent under each new if
or else
should be four spaces.
if x > y:
do_something()
An if
within an if
needs further indentation - it must also be four spaces further in, so a total of eight spaces.
if x > 100:
print("bigger than 100")
if x < 120:
print("but smaller than 120")
else:
print("and bigger than 120")
else:
print("x is too small")
This rule propagates, so a third level would need twelve spaces etc.
Note how the code above is structured now. Code at the same indentation is in the same group of code - at the same level. We can easily see which if
and else
go together as pairs. This is the point of using whitespace like this - it gives us clean and visually consistent programs which the designers of Python value.
A common gotcha is that you always have to undo the indent at the end of the block. The first bit of the rest of the code must always be fully at the left of the page or Python will interpret the code incorrectly.
These indentation rules apply in other places in Python code and we’ll come across them in due course.
if
sConditional statements don’t have to include an else
. If there isn’t one, Python simply does nothing if the test is false:
= 53
num print('before conditional...')
if num > 100:
print(num,' is greater than 100')
print('...after conditional')
before conditional...
...after conditional
We can also chain several tests together using elif
, which is short for “else if”. The following Python code uses elif
to print the sign of a number.
= -3
num
if num > 0:
print(num, 'is positive')
elif num == 0:
print(num, 'is zero')
else:
print(num, 'is negative')
-3 is negative
Note that the if
and elif
bits are mutually exclusive. Only one of them ever gets executed.
Note that to test for equality we use a double equals sign ==
rather than a single equals sign =
which is already used to assign values.
Python has all the standard logical operators that let us combine tests. Most commonly there is and
and or
. An and
operator is only true if both parts are true:
if (1 > 0) and (-1 > 0):
print('both parts are true')
else:
print('at least one part is false')
at least one part is false
while or
is true if at least one part is true:
if (1 < 0) or (-1 < 0):
print('at least one test is true')
at least one test is true
True
and False
are special words in Python called booleans
, which represent truth values. A statement such as 1 < 0
returns the value False
, while -1 < 0
returns the value True
.
True
and False
booleans are not the only values in Python that are true and false. In fact, any value can be used in an if
or elif
.
if '':
print('empty string is true')
if 'word':
print('word is true')
if []:
print('empty list is true')
if [1, 2, 3]:
print('non-empty list is true')
if 0:
print('zero is true')
if 1:
print('one is true')
word is true
non-empty list is true
one is true
It may seem strange to set things up this way, but in Python in practice it allows for some nice and easy to read and write constructions.
Sometimes it is useful to check whether some condition is not true. The Boolean operator not
can do this explicitly.
if not '':
print('empty string is not true')
if not 'word':
print('word is not true')
if not not True:
print('not not True is true')
empty string is not true
not not True is true
if 4 > 5:
print('A')
elif 4 == 5:
print('B')
elif 4 < 5:
print('C')
Which of the following would be printed if you were to run this code? Why did you pick this answer?
if 4 > 5:
print('A')
if 4 <= 5:
print('B')
if 4 < 5:
print('C')
Which of the following would be printed if you were to run this code? Why did you pick this answer?
if 4 > 5:
print('A')
elif 4 <= 5:
print('B')
elif 4 < 5:
print('C')
Which of the following would be printed if you were to run this code? Why did you pick this answer?