Skip to content
Comparison and Boolean Logic
step 1/8

Reading — step 1 of 8

Learn

~3 min readMaking Decisions

Until now, your programs have been straight lines — they start at the top, execute every line in order, and reach the bottom. Real programs need to make decisions: "Is the user logged in?" "Is the balance sufficient?" "Has the file been downloaded?" Every one of these questions boils down to a single concept: a value that is either True or False. That's a boolean.

The six comparison operators

Comparisons take two values and return a boolean.

python

The single most common beginner bug: writing = (assignment) when you mean == (equality). if x = 10: is a SyntaxError. if x == 10: is what you wanted.

Comparisons work for strings, too

Strings compare alphabetically (technically, by Unicode code point):

python

The boolean type and operators

Booleans are their own type. Python has exactly two: True and False (capital first letter — true lowercase is a NameError).

The three boolean operators:

  • and — True only if BOTH sides are True
  • or — True if AT LEAST ONE side is True
  • not — flips True to False and vice versa
python

Truth tables

A      B      A and B    A or B
-----  -----  ---------  -------
True   True   True       True
True   False  False      True
False  True   False      True
False  False  False      False

Short-circuit evaluation — important!

Python evaluates and / or lazily, left to right, and STOPS as soon as it knows the answer.

python

Why you care: this lets you safely guard risky operations.

python

== versus is

Python has two equality operators that beginners confuse:

  • == — values are EQUAL.
  • is — values are the same object in memory (identity).
python

Use == for normal comparisons. Use is ONLY for the special cases is None, is True, is False.

The in operator

in checks for membership. It works on strings, lists, tuples, sets, dicts:

python

Readability bonus: if user not in banned_users reads like English.

Common mistakes

  • = instead of == — a classic. Now a SyntaxError, but watch for it.
  • Comparing None with ==: it works, but the idiomatic style is if x is None:.
  • Capitalization: true, false, TRUE are all NameError. The bools are True and False exactly.
  • Chaining and/or without parens when mixing: a and b or c is (a and b) or cand binds tighter than or. Add parens to be explicit.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…