if, else, and elif Statements

6. Boolean operators and expressions

Booleans and Boolean operators

A Boolean refers to a value that is either True or False. These two are constants in Python. 

  • we can assign a Boolean value by specifying True or False, 

x = True

  • an expression can evaluate to a Boolean value

y > 10

and operator

The Boolean expression a and b is True if and only if both a and b are True.

a b a and b
True True True
True False False
 False  True  False
 False  False  False

Examples: assume that a = 8 and b = 3, then the Boolean value of     
1)  ( a > 10 ) and ( b < 5 ) is False
2) ( a != 10 ) and ( b > 1 ) is True

or operator

The Boolean expression a or b is False if and only if both a and b are False.

a b a or b
True True True
True False True
 False  True  True
 False  False  False

Examples: assume that a = 8 and b = 3, then the Boolean value of     
1)  ( a > 10 ) or ( b < 5 ) is True
2) ( a == 10 ) or ( b > 1 ) is True

not operator

The Boolean expression not a  is False when a is True, and is True when a is False.

a not a
True False
 False  False

Examples: assume that a = 8 and b = 3, then the Boolean value of     
1) not ( a > 10 ) is True
2) not ( a * 10 > 20 ) is False

Booleans and Boolean operators

Consider the following code fragment:
if letter == 'a' or letter == 'b':
   print("Help!")
elif letter == 'c' or letter == 'd':
   print("We are in trouble!")
else:
   print("We are good!")

If letter = "a", then we will get: Help!

Consider the following code fragment:
if letter == 'a' or letter == 'b':
   print("Help!")
elif letter == 'c' or letter == 'd':
   print("We are in trouble!")
else:
   print("We are good!")

If letter = "c", then we will get: We are in trouble!