7  If-statements and Comparisons

In the previous chapters, we learned how to use built-in functions and functions from imported packages to perform simple tasks. But often, tasks should only be performed when a certain condition is met. An if-statement can be used to check such a condition and perform the task if the condition is met. For example:

age = 17

if age < 18:  # Check if the age is less than 18.
    print('this person is a child')  # Print if the condition is met.
this person is a child

As you can see, the line print(...) starts with 4 spaces indentation. In Python indentation is very important. Python uses indentation to determine which lines of code belong together. Lines with the same indentation are called a code block. We use code blocks to define what should be done in an if-statement. E.g. after the if-condition, all lines with indentation are only performed when the if-condition is met:

num = 99

if num > 100:
    print('This line is only executed when num > 100.')
    print('And this line too.')

    print('And so is this line.')

print('This line is always executed.')
This line is always executed.

It is also possible to specify a task that is performed when the condition is not met using else (note the use of indentation):

age = 17

if age < 18:
    print('this person is a child')
else:
    print('this person is an adult')

print('done')
this person is a child
done

If we need to check multiple conditions, the if ... else statement can be extended with (one or more) elif to specify more tasks that need to be performed on other conditions. These extended if ... else statements always start with if followed by (one or more) elif. When an else statement is included it is always the last statement, it is the default which will be executed when all previous comparisons failed:

num = -3

if num > 0:
    print(num, 'is positive')
elif num == 0:
    print(num, 'is zero')
else:
    print(num, 'is negative')
-3 is negative

If-statements often use comparisons to check if a certain condition is met. Comparisons are done with comparison operators such as >, ==.

Along with the > and == comparison operators that we have already used for comparing values above, there are a few more options to know about:

Operator Meaning
> greater than
< less than
== equal to
!= not equal to
>= greater than or equal to
<= less than or equal to

Let’s now play around with comparisons to see how they work in more detail:

4 > 3
True
4 < 3
False
a = 4 > 3
type(a)
bool

As you can see, comparisons return True or False. The data type of these values are bool which is short for Boolean value. If the value in the if-statement evaluates to True, the task is performed, if the value evaluates to False, the task is not performed.

Boolean values can also be assigned to variables:

a = True
type(a)
bool

Any value used in a comparison that is not a bool, will be automatically cast to a bool. Values that cast to False are e.g. 0 and 0.0, empty strings (''), empty lists ([]), etc.

b = 42
c = ""

print(bool(b))
print(bool(c))
True
False

and, or and not are logical operators, and are used to join two comparisons (or invert a logical expression in the case of not) to create more complex conditions.

and is used to check if two conditions both evaluate to True, and returns either the first value that evaluates to False or the last value.

a and b, bool(a and b)  # a is True, and b is 42 which also evaluates to True
(42, True)
a and c, bool(a and c)  # a is True, but c is an empty string which evaluates to False
('', False)
4 > 3 and 9 > 3
True

or is used to check if at least one of two conditions are True, and returns either the first value that evaluates to True or the last value.

3 > 4 or 9 > 3
True
name = ""
print(name or "Anonymous")  # 'name' is an empty string, which evaluates to False.

name = "Brian"
print(name or "Anonymous")  # 'name' is not empty string, which evaluates to True.
Anonymous
Brian

In the last couple of examples you can see that multiple expressions can be combined in a single line of Python code. Python evaluates the expressions one by one. 4 > 3 would return True, 9 > 3 would return True, so 4 > 3 or 9 > 3 would translate to True or True. Because at least one of the expressions on either side of the or operator is True, the whole expression results to True.

The not operator can be used to invert the Boolean value. If you apply not to an expression that evaluates to True, then you get False as a result. If you apply not to an expression that evaluates to False, then you get True as a result:

not 4 > 3
False

Logical operators bind variables with different strengths. The and is stronger than the or and gets evaluated first in a boolean expression. So a or b and c will be evaluated like a or (b and c), while in (a or b) and c first the value of the or is evaluated and then combined with and c. This leads to a different result. The strongest operator is the not.

Confusing? We think so too: so always use parentheses to eliminate the confusion :-)

a = True
b = True
c = False
print("This expression 'a or b and c' evaluates to ", a or b and c)
print("And this is the same as 'a or (b and c)')", a or (b and c))
print("But this expression evaluates '(a or b) and c' first the 'or' and generates:", (a or b) and c)
This expression 'a or b and c' evaluates to  True
And this is the same as 'a or (b and c)') True
But this expression evaluates '(a or b) and c' first the 'or' and generates: False

Now we know how to use comparisons and logical operators to create complex conditions. These complex conditions can be used in if-statements to perform tasks based on these conditions.

if (1 < 0) or (1 >= 0):
    print('at least one the above logical statements is true')
at least one the above logical statements is true

While and is only true if both parts are true

if (1 < 0) and (1 >= 0):
    print('both tests are true')
else:
    print('at least one of the tests is not true')
at least one of the tests is not true

External course material

Review these pages about comparisons and do the exercises: