Boolean

Boolean Values

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

True, False are capitalized, no quotes like around strings.

Don't use True/False as variable names.

Boolean Expression

A Boolean expression is an expression that evaluates to a Boolean value. The comparison operators, compare two values and produce True or False according to the relationship of the two values.

There are six common comparison operators:

Work with any data type:

equal to, == Not equal to, !=

Can only work with numbers:

Greater than, > Greater than or equal to, > = Less than or equal to, < = Less than, <

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

Boolean Operators

Python provides three logical operators: and, or, not, they are used to construct more complex 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: True if either of the two Boolean values is True. True or False ----- True False or False----- False

  • not: operates on only one Boolean value (or expression). Result is the opposite. not True----- False not False --- True

Example

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), this is F and F--> F

While these are all interesting and puzzling, what't the point to keep comparing cats and dogs, let's move on to next lesson, Making Decisions!

results matching ""

    No results matching ""