Reading — step 1 of 8
Learn
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.
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):
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 Trueor— True if AT LEAST ONE side is Truenot— flips True to False and vice versa
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.
Why you care: this lets you safely guard risky operations.
== versus is
Python has two equality operators that beginners confuse:
==— values are EQUAL.is— values are the same object in memory (identity).
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:
Readability bonus: if user not in banned_users reads like English.
Common mistakes
=instead of==— a classic. Now aSyntaxError, but watch for it.- Comparing
Nonewith==: it works, but the idiomatic style isif x is None:. - Capitalization:
true,false,TRUEare allNameError. The bools areTrueandFalseexactly. - Chaining
and/orwithout parens when mixing:a and b or cis(a and b) or c—andbinds tighter thanor. 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…