Conditional expressions, involving keywords such as if, elif, and else, provide Python programs with the ability to perform different actions depending on a boolean condition: True or False. This section covers the use of Python conditionals, boolean logic, and ternary statements.
- <expression> if <conditional> else <expression> # Ternary Operator
Boolean Logic Expressions
Boolean logic expressions, in addition to evaluating to
False, return the value that was interpreted as
False. It is Pythonic way to represent logic that might otherwise require an if-else test.
and operator evaluates all expressions and returns the last expression if all expressions evaluate to
True. Otherwise it returns the first value that evaluates to
or operator evaluates the expressions left to right and returns the first value that evaluates to
True or the last value (if none are
When you use this approach, remember that the evaluation is lazy. Expressions that are not required to be evaluated to determine the result are not evaluated. For example:
In the above example,
print_me is never executed because Python can determine the entire expression is
False when it encounters the
False). Keep this in mind if
print_me needs to execute to serve your program logic.
Testing for multiple conditions
A common mistake when checking for multiple conditions is to apply the logic incorrectly.
This example is trying to check if two variables are each greater than 2. The statement is evaluated as -
if (a) and (b > 2). This produces an unexpected result because
bool(a) evaluates as
a is not zero.
Each variable needs to be compared separately.
Another, similar, mistake is made when checking if a variable is one of multiple values. The statement in this example is evaluated as -
if (a == 3) or (4) or (6). This produces an unexpected result because
bool(6) each evaluate to
Again each comparison must be made separately
Using the in operator is the canonical way to write this.
Conditional Expression (or "The Ternary Operator")
The ternary operator is used for inline conditional expressions. It is best used in simple, concise operations that are easily read.
- The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order).
- Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
The result of this expression will be as it is read in English - if the conditional expression is True, then it will evaluate to the expression on the left side, otherwise, the right side.
Tenary operations can also be nested, as here:
They also provide a method of including conditionals in lambda functions.
Conditional Expression Evaluation Using List Comprehensions
Python allows you to hack list comprehensions to evaluate conditional expressions.
False (which equates to 0 in Python). So what Python is evaluating is:
__cmp__ method returned 3 possible values: 0, 1, -1, where cmp(x,y) returned
0: if both objecs were the same
1: x > y
-1: x < y
This could be used with list comprehensions to return the first(ie. index 0), second(ie. index 1) and last(ie. index -1) element of the list. Giving us a conditional of this type:
Finally, in all the examples above Python evaluates both branches before choosing one. To only evaluate the chosen branch:
where adding the
() at the end ensures that the lambda functions are only called/evaluated at the end. Thus, we only evaluate the chosen branch.
The else statement will execute it's body only if preceding conditional statements all evaluate to False.
if statements checks the condition. If it evaluates to
True, it executes the body of the
if statement. If it evaluates to
False, it skips the body.
The condition can be any valid expression:
if, elif, and else
In Python you can define a series of conditionals using
if for the first one,
elif for the rest, up until the final (optional)
else for anything not caught by the other conditionals.
Number is bigger than 2
else if instead of
elif will trigger a syntax error and is not allowed.
Testing if an object is None and assigning it
You'll often want to assign something to an object if it is
None, indicating it has not been assigned. We'll use
The simplest way to do this is to use the
is None test.
(Note that it is more Pythonic to say
is None instead of
But this can be optimized slightly by exploiting the notion that
not None will evaluate to
True in a boolean expression. The following code is equivalent:
But there is a more Pythonic way. The following code is also equivalent:
This does a Short Circuit evaluation. If
aDate is initialized and is
not None, then it gets assigned to itself with no net effect. If it
is None, then the
datetime.date.today() gets assigned to
The following values are considered falsey, in that they evaluate to
False when applied to a boolean operator.
0, or any numerical value equivalent to zero, for example
- Empty sequences:
- Empty mappings:
- User-defined types where the
__len__methods return 0 or
All other values in Python evaluate to
Note: A common mistake is to simply check for the Falseness of an operation which returns different Falsey values where the difference matters. For example, using
if foo() rather than the more explicit
if foo() is None
Using the cmp function to get the comparison result of two objects
Python 2 includes a
cmp function which allows you to determine if one object is less than, equal to, or greater than another object. This function can be used to pick a choice out of a list based on one of those three options.
Suppose you need to print
'greater than' if
x > y,
'less than' if
x < y and
x == y.
cmp(x,y) returns the following values
|x < y||-1|
|x == y||0|
|x > y||1|