Lesson 2 of 6 · Numbers, Strings and Operators · 2 min read · Updated
Comparison and logical operators
Asking questions of values: bigger, equal, inside, the same object — and combining the answers.
A comparison asks a question and answers True or False. Every if and while you write is built from them.
a = 10
b = 3
print(a > b, a == b, a != b)
print(a >= 10, b <= 2)
print(a > 5 and b > 5)
print(a > 5 or b > 5)
print(not a > 5)
True False True
True False
False
True
False
Warning
One = stores a value; two == compare. Writing if marks = 100: is a SyntaxError in Python — which is kinder than languages where it silently changes marks.
in and not in
print("py" in "python")
print(3 in [1, 2, 3])
print("z" not in "python")
True
True
True
in asks whether something is inside a string, list or other collection. It reads like English and replaces a whole loop.
is versus ==
x = [1, 2]
y = [1, 2]
z = x
print(x == y)
print(x is y)
print(x is z)
True
False
True
== asks "do these hold the same value?". is asks "are these the very same object?". x and y are two separate lists that happen to be equal; z is just another name for x.
Note
Use is for one job: checking for None, as in if result is None:. For numbers and strings, always use ==.
Which runs first
print(2 + 3 * 4)
print((2 + 3) * 4)
print(10 - 4 - 3)
14
20
3
Python follows school maths: ** first, then * / // %, then + -, then comparisons, then not, and, or. When in doubt, add brackets — they cost nothing and the reader will thank you.
a = [5] and b = [5]. What is a is b?
Try this now
- Ask for an age and print whether the person can vote (18 or over) and is under 60, using
and. - Ask for a letter and print whether it is a vowel using
in "aeiou".
Create a free account to save your progress, or sign in.