1. Comparisons
Comparisons compare two values and produce a boolean: True or False.
| Operator | Meaning |
|---|---|
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
== | equal to |
!= | not equal to |
A comparison is an expression, so it produces a value you can print directly: print(10 > 3) shows True.
= assigns a value to a variable; == compares two values. age = 18 stores 18, while age == 18 asks whether they are equal.
Strings are compared exactly, character by character, so case matters: "apple" and "Apple" are different.
Coming from JavaScript? == compares values without coercion ("1" == 1 is False), so there is no ===. The idiom to check for no value is value is None, not value === null.
Compare with greater than
Use the greater-than operator (>) to compare 10 and 3, and print the result. The comparison produces a boolean.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Compare with equality
Use the equality operator (==) to compare 5 and 5, and print the result. == checks whether both values are equal; it does not assign anything.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Compare with not equal
Use the not-equal operator (!=) to compare 5 and 5, and print the result. != is True when the values are different.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Text is case-sensitive
Compare the strings "apple" and "Apple" with ==, and print the result. The two strings have different capital letters, so they are not equal.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Two comparisons, one print
Print the results of two comparisons in a single print() call, separated by a comma: first 7 >= 7, then 7 <= 6. print() puts a space between the two values.
Print exactly:
Create a free account to save your progress and unlock chapter 2.