Reference · module 8
True, False and None
Everything this module explains, on one page.
What counts as true
Know which values are falsy.
- An if does not need a comparison. Any value counts as true or false on its own.
- Everything empty is false: "", [], {}, and 0. Everything else, including "0" and [0], is true.
- So if items: reads as «if there are any items». Writing len(items) > 0 says the same thing, longer.
The mistake you are about to make
if items == True:
if items:
"If the list is true" invites a comparison with True. A non-empty list is truthy but it does not equal True, so the comparison fails where a bare if works.
and, or, not
Combine conditions.
- and is true only when both sides are. or is true when at least one is. not flips a single value.
- They stop early. In a and b, if a is false then b is never looked at, because the answer is already known.
- That is useful: if items and items[0] == 1 is safe, because the index is only reached when the list is not empty.
The mistake you are about to make
if items[0] == 1 and items:
if items and items[0] == 1:
The order inside and looks irrelevant — both sides get checked anyway. It matters: Python stops as soon as the answer is known, so the emptiness check goes first.
None
Handle the absence of a value.
- None is the value that means «no value». It is not zero and not an empty string; it is the absence of an answer.
- Compare it with is, not ==: x is None. There is only one None in the whole program, so identity is the right question.
- A function with no return statement returns None. So does a bare return with nothing after it.
The mistake you are about to make
if x == None:
if x is None:
The == version works and looks familiar. None takes is: there is exactly one None in the program, so the question is about identity, not value.
Comparing
Compare values correctly.
- A single = stores a value. A double == asks a question. Mixing them is the first error everyone meets.
- "5" == 5 is False. Text and numbers are different things, and Python does not quietly convert.
- == asks «same value», is asks «same object». For numbers and strings you almost always want ==.
The mistake you are about to make
"5" == 5 → True
"5" == 5 → False
There is a five on each side, so they look equal. Python never converts types quietly: text and number are never equal, however alike they look.
Functions that answer yes or no
Return a condition directly.
- A comparison already is True or False, so return n % 2 == 0 needs no if around it.
- Writing if cond: return True else: return False is four lines saying what one line says.
- Name such a function as a question: is_even, has_access, looks_valid. Then the if reads like a sentence.
The mistake you are about to make
if cond: return True — else: return False
return cond
The function is supposed to hand back True or False, so both cases get spelled out. The comparison is already one of them: four lines collapse into one.