| Symbol | Description |
|---|---|
| == | Equal to |
| != | Not equal to |
| < | Less than |
| <= | Less than or equal to |
| > | greater than |
| >= | greater than or equal to |
Note: one equals sign indicates an assignment operation, e.g. shoe_size
= 10, whereas two back-to-back equals signs indicate
a comparison operation, e.g., if shoe_size == 10: print "Shoe
size is 10".
A comparison operation provides a true or false result. E.g.,
result = 5 < 7 leads to the variable result having the value
True.
$ python Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> result = 5 < 7 >>> print result True
Boolean operators
You can also make comparisons using Boolean operatators.
| Operator | Description |
|---|---|
| and | True if both conditions are true |
| or | True if either condition is true |
| not | True if the opposite of the statement is true |
So you would have the following results where the above operators appear associated with a condition or conditions as listed below:
| Statement | Result |
|---|---|
True and False | False |
False and True | False |
False and False | False |
True or True | True |
True or False | True |
False or True | True |
False or False | False |
not True | False |
not False | True |
E.g.:
>>> print 1 < 2 and 2 < 3 True >>> print 1 < 2 and 2 > 3 False >>> print 1 < 2 or 2 < 3 True >>> print 1 < 2 or 2 > 3 True >>> print 1 > 2 or 2 > 3 False >>> print not 2 == 3 True >>> print not 2 < 3 False >>> print not 2 * 50 > 99 False
The boolean operator not returns True for
false statements and False for true statements. If you
are using the values True and False as part
of a statement, you need to start each with a capital letter. If you
use "true" or "false", you will receive an error message. E.g.:
>>> not True False >>> not False True >>> not true Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'true' is not defined >>> not false Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'false' is not defined >>>
For "not", use all lowercase letters.
>>> Not True
File "<stdin>", line 1
Not True
^
SyntaxError: invalid syntax
>>> not True
False