Lesson 9 of 30 · Making Decisions
Booleans and Comparisons
Learn True and False in Python and the six comparison operators. Compare numbers and strings and avoid the classic = versus == mistake.
- 6 min read
- Beginner
- Reviewed
- What a boolean is and where booleans come from
- The six comparison operators
- The difference between = and ==
Yes-or-no questions
Programs constantly ask questions. Is the password correct? Is the user old enough? Is the model accurate enough to stop training?
The answer to a yes-or-no question is a boolean: either True or False.
is_logged_in = True has_paid = False print(is_logged_in) print(type(has_paid))
Comparison operators
Most booleans are not typed by hand. They are the result of a comparison.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 5 > 8 | False |
< | Less than | 5 < 8 | True |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 6 <= 5 | False |
age = 20 print(age == 20) print(age != 20) print(age > 18) print(age < 18) print(age >= 20)
Change age to 15 and predict each answer before you run it.
= is not ==
This is the most common mistake in all of programming, so it gets its own section.
- One equals sign stores a value:
age = 20 - Two equals signs compare two values:
age == 20
score = 50 # store 50 in score print(score == 50) # is score equal to 50? print(score == 99) # is score equal to 99?
Saving the result of a comparison
A comparison produces a value, so you can store it in a variable. Good names for booleans often start with is_ or has_.
temperature = 31
is_hot = temperature > 30
print("Is it hot?", is_hot)Comparing strings
== and != work on text too. The comparison is exact: capital letters and spaces count.
answer = "Yes" print(answer == "Yes") print(answer == "yes") print(answer.lower() == "yes")
Comparing different types
A number and a string are never equal, even when they look the same.
print(5 == 5.0) print(5 == "5")
5 == 5.0 is True because both are numbers with the same value. 5 == "5" is False because one is a number and the other is text. This is why you convert input before comparing it.
Store the result of a comparison in is_adult, then print Adult: True.
age = 20 # Create a variable called is_adult that is True when age is 18 or more. # Then print it so the output is exactly: Adult: True
Which line checks whether x is equal to 10?
Summary
- A boolean is
TrueorFalse. ==,!=,>,<,>=and<=compare two values and return a boolean.=stores a value.==compares two values.- String comparisons are exact, including capital letters.
Next, you will use booleans to make your program choose what to do.
Finished reading? Tick it off to track your progress.