Booleans and Comparisons
Unit ID: M02-U03 Estimated active time: 18-25 minutes
A boolean answers a yes-or-no question
Python has two boolean values:
True
False
The capital letters matter. true is not the same name as True.
Comparisons produce booleans:
print(5 > 3)
print(5 < 3)
print(5 == 5)
print(5 != 5)
The outputs are True, False, True, and False.
Comparison operators
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
Do not confuse assignment = with equality comparison ==.
Store a comparison result
completed_hours = 8
required_hours = 8
requirement_met = completed_hours >= required_hours
print(requirement_met)
Output:
True
The name requirement_met clearly describes the question answered by the boolean.
Compare text carefully
print("Python" == "Python")
print("python" == "Python")
The first comparison is True; the second is False. String comparison is case-sensitive.
Cleaning text before comparison can make the intended rule explicit:
entered_status = " PLANNED "
clean_status = entered_status.strip().lower()
print(clean_status == "planned")
The result is True.
Combine simple boolean questions
Python provides and, or, and not.
hours = 3
has_notebook = True
ready = hours >= 2 and has_notebook
print(ready)
ready is True only when both parts are true.
is_beginner = True
has_previous_course = False
can_start = is_beginner or has_previous_course
print(can_start)
can_start is True when at least one part is true.
is_complete = False
print(not is_complete)
This prints True because not reverses the boolean.
Module 4 will use these values to control program branches. Here, focus on writing and explaining the question accurately.
Practice
Create values for score = 7, required_score = 8, and all_tasks_submitted = True.
Create and print:
- whether the score meets the requirement;
- whether all tasks are submitted; and
- whether both conditions are met.
The combined result should be False because the score is below the requirement.
Takeaway
Booleans represent True or False. Comparisons and boolean operators let code state precise questions. Next, we will work with strings as ordered sequences of characters.
