Boolean conditions can be made more powerful with the use of the Boolean
operators and
, or
, and not
.
These operators act the same way they do in English are are used to either
negate (in the case of not) a condition, or allow multiple conditions to
be checked within one if
or elif
.
The operations of these operators are generally represented with truth tables:
A | B | result |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
A | B | result |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
A | result |
---|---|
True | False |
False | True |
not
is simple to use - place it outside any condition you
wish to negate:
if not(x == 0):
...
Note that conditions on either side of an and
or an or
must be complete conditions - there are no shortcuts. For example, the
following attempt to use an and
is incorrect and is a very
common error:
if x == 5 or 6:
...
will not cause a Python syntax error - it is a valid Python statement -
but it always returns True
. Why? Because the value 6 is not
actually compared to anything. You are actually asking the separate
questions "Is x equal to 5" and "Is 6, 6?", and the answer to second one
is, "Yes, 6 is 6."
The correct way to write this clause is:
if x == 5 or x == 6:
....
The variable x
is now explicitly compared to both 5 and 6.