Comparisons (==, <, >=…)
A comparison puts two values side by side and gives back True or False.
Used in 120 lessons of the course, from 00.01.
The comparison operators are == (equal), != (not equal), <, <=, > and >=. Each one looks at two values and returns a boolean: True or False.
Watch the difference between = and ==. A single = assigns a value to a name. Two == ask whether two values are equal. So in a condition you always use ==.
You can compare numbers, strings, lists and more. Strings are compared character by character, and case matters: "a" == "A" is False.
The result usually feeds an if or a while, which decide what to do based on True or False.
In the course you will see lines like if key in GLOSSARY:. There in is a membership comparison that also returns a boolean, and the if uses it to decide.
print(3 >= 2) # True
Reach for it when: your program has to decide something based on a value: an `if`, a `while` or a filter.
Examples
Common mistake
x = 3
if x = 3:
print("three")Why: A single `=` assigns, and you can't assign inside an `if` condition. Python can't tell what you mean.
How to write it: Use == to compare: if x == 3:.
Common mistake
print("10" == 10)Why: A string and a number are never equal, even if they look alike. Python doesn't convert them for you.
How to write it: Convert one of them before comparing: int("10") == 10.
