There are only two Boolean values. They are True and False. Capitalization is important, since true and false are not Boolean values (remember Python is case sensitive). A boolean expression is an expression that evaluates to a Boolean value. The equality operator, ==, compares two values and produces a Boolean value related to whether the two values are equal to one another.

- Code: Select all
`print(5 == 5) # Outputs True`

print(5 == 6) # Outputs False

Boolean values are not strings!

It is extremely important to realize that True and False are not strings. They are not surrounded by quotes. They are the only two values in the data type bool.

Here are the Most Common Comparison Operators:

- Code: Select all
`x != y # x is not equal to y`

x > y # x is greater than y

x < y # x is less than y

x >= y # x is greater than or equal to y

x <= y # x is less than or equal to y

Logical Operators

There are three logical operators: and, or, and not. The meaning of these operators is similar to their meaning in English.

Examples:

x > 0 and x < 10 is true only if x is greater than 0 and at the same time, x is less than 10.

n % 2 == 0 or n % 3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or divisible by 3. In this case, one, or the other, or both of the parts has to be true for the result to be true.

Finally, the not operator negates a boolean expression, so not x > y is true if x > y is false, that is, if x is less than or equal to y.

Common Mistake!

There is a very common mistake that occurs when programmers try to write boolean expressions. For example, what if we have a variable number and we want to check to see if its value is 5,6, or 7. In words we might say: “number equal to 5 or 6 or 7”. However, if we translate this into Python, number == 5 or 6 or 7, it will not be correct. The or operator must join the results of three equality checks. The correct way to write this is number == 5 or number == 6 or number == 7. This may seem like a lot of typing but it is absolutely necessary. You cannot take a shortcut.

Uses for Boolean

Boolean functions are always used in while loops.

They are always used in if statements.

These things will be commonly used in all Python programs, so Boolean functions must be known.