Boolean

Boolean Values

The Python type for storing true and false values is called bool. There are only two Boolean values: True and False.

Notes:

  • True and False are capitalized. There are no quotation marks around them, since they are not strings.

  • Do not use the terms True/False as variable names.

Boolean Expressions

A Boolean expression is an expression that evaluates to a Boolean value. Comparison operators compare two values and return True or False according to the relationship of the two values.

There are six common comparison operators:

  • Works with any data type:

    ==: equal to
    !=: not equal to

  • Only work with numbers and strings:

    >: greater than
    <: less than
    >=: greater than or equal to
    <=: less than or equal to

Run the following examples and check the console results:

print(25 == 5*5)    # True
print(25 != 25)     # False
print(25 > 5**2)    # False
print(25 >= 5**2)   # True

print('hi' == 'Hi')         # False (stings are case sensitive)
print('Cat' != 'Chicken')   # True

p = 10
t = 1
print(p < t)       # False

Logical Operators

Python has three logical operators: and, or, not. They are used to construct more complex Boolean expressions.

The Truth Tables:

and: If both are True, the result is True

True  and True  ----> True
True  and False ----> False
False and True  ----> False
False and False ----> False

or: If either of the two values is True, then the result is True.

True  or True  ----> True
True  or False ----> True
False or False ----> False

not: operates on only one Boolean expression. The result is the opposite of the expression's Boolean value.

not True  ----> False
not False ----> True

Examples

print(False and True)          # False
print(4 == 2*2 and 2 == 3)     # False
print((5 < 10) or (10 >= 5*2)) # True

print('Cat' == 'Dog' and not (6==8 or 3==3)) # False
# F and not(F or T) --> F and F --> F

results matching ""

    No results matching ""