Python Crash Course
)}

Boolean Data Types

A boolean type can have one of two values:

True or False.

‍Assigning Boolean Type Variables

course_is_awesome = True course_is_not_awesome = False

T‍hat's it. We assigned two variables; one that holds the boolean True and another that holds the boolean False.

However, the way we declared these variable isn't very useful; we should make use of comparison operators to take advantage of boolean types.‍

Comparison Operators

  • less than <
  • greater than >
  • less than or equal <=
  • greater than or equal >=
  • equal to ==
  • not equal to !=

T‍hese comparison operators are often used to return a boolean value. For example:

comparison_operation = 1 > 2 print(comparison_operation)

>‍> False

We tried using the comparison operator to determine if 1 is bigger than 2 using the greater than operator >. Since this comparison operation is false, the operator returns False as a result.

This changes if we replace it with the smaller than operator <

comparison_operation = 1 < 2 print(comparison_operation)

>‍> True

Logical Operators

  • or operator
  • and operator
  • not operator

The **or** Operator

If any of the or operator's comparisons are true , it returns True , otherwise it returns False.

When both comparisons are true:

‍comparison_operation = 1 < 2 or 2 < 3 print(comparison_operation)

>‍> True

When a single comparison is true

comparison_operation = 1 < 2 or 2 > 3 print(comparison_operation)

>> True

When both comparisons are false

comparison_operation = 1 > 2 or 2 > 3 print(comparison_operation)

False

  1. In the first example, since both comparisons were true, the result returned is True
  2. In the second example, one of the comparisons was true. However, since the or operator only requires a single comparison to be true, the result we got was True
  3. In the third example, both comparisons were false; so the result we got was False

The and Operator

The and Operator requires all it's comparisons to be true to produce a boolean result of True. Otherwise, the boolean result will always be False.

When both comparisons are true

‍‍comparison_operation = 1 < 2 and 2 < 3 print(comparison_operation)

‍>> True

When a single comparison is true

comparison_operation = 1 < 2 and 2 > 3 print(comparison_operation)

‍>> False

When both comparisons are false

comparison_operation = 1 > 2 and 2 > 3 print(comparison_operation)

‍>> False

‍‍

The not Operator

The not flips your current boolean value

for example:

comparison_operation = 1 < 2
print(comparison_operation)

‍>> True

T‍he execution above defaults to True . Now, what happens if we use the not operator on it.

comparison_operation = not 1 < 2 print(comparison_operation)

>> False

‍as you can see, the not Operator flipped the boolean value from True to False

Feedback Summary
4.8
8 students
5

75%
4

25%
3

0%
2

0%
1

0%
Written Reviews
There are no written reviews yet.