Python control flow using comparators and logical operators

In Python, you can use the followng six comparators to determine if one value is or isn't equal to another or whether the value is less than, less than or equal to, greater than, or greater than or equal to another.

SymbolDescription
==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.

OperatorDescription
andTrue if both conditions are true
orTrue if either condition is true
notTrue 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:

StatementResult
True and FalseFalse
False and TrueFalse
False and FalseFalse
 
True or TrueTrue
True or FalseTrue
False or TrueTrue
False or FalseFalse
 
not TrueFalse
not FalseTrue

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

 

TechRabbit ad 300x250 newegg.com

Justdeals Daily Electronics Deals1x1 px