Topic 1.4
True, False and None
In one line
A bool is either True or False, the answer to a yes-or-no question. None is Python's way of saying "no value here". Every value also has a truthiness: empty and zero values count as false, nearly everything else as true.
Think of it like this
A light switch and an empty hook. A switch is either on or off, nothing in between: that is a bool. A hook on the wall may have a coat hanging on it, or nothing. "Nothing there" is not the same as a coat with the colour "none": it is the absence of a coat. Python calls the absence None.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- bool
- The type with only two values,
TrueandFalse. - None
- The special value meaning "no value". Its type is
NoneType. - Truthy
- A value that counts as true in a condition.
- Falsy
- A value that counts as false in a condition:
0,"",None,False, empty containers (a container is a value that holds other values, such as a list; Phase 4). - Condition
- A yes-or-no question that decides what the program does next.
- Subclass
- A type built on another.
boolis built onint. - Singleton
- A value of which only one copy exists. There is exactly one
None. - Return value
- What a function gives back. With no
return, that value isNone.
Step by step
01bool is a kind of int
True is the number 1 wearing a name, and False is 0. That is why you can add them. Programmers use this to count: (a > 0) + (b > 0) + (c > 0) is how many of three numbers are positive.
print(True + True, True * 10) # 2 10
print(isinstance(True, int)) # True
print(type(True), type(None)) # <class 'bool'> <class 'NoneType'>02Truthiness: what counts as false
Python turns any value into true or false using a short list of rules. Zero is false. Empty is false. None is false. Everything else is true. The bool() function applies those rules and shows you the result.
You will use truthiness constantly in Phase 2: if name: means "if there is a name". It is short and readable, but only when you really mean "not empty".
print(bool(0), bool(1), bool(-5), bool(0.0)) # False True True False
print(bool(""), bool("False"), bool(" ")) # False True True
print(bool([]), bool([0])) # False True
print(bool(None)) # False03None means nothing here
Start a variable at None when you do not know its value yet. Later you give it a real value. There is only one None in the whole program, so the right check is identity: result is None. We will study is properly in Topic 1.8.
print() is a function that shows text and returns None. If you store its result, you get None, which is why shown = print("hello") prints hello first and print(shown) prints None.
result = None
print(result is None) # True
shown = print("hello") # prints hello
print(shown) # None040 is not None
A student with 0 marks and a student who has not been marked yet are different. 0 is falsy but is a real number, None is falsy and means no value. score is None separates them; not score does not.
score = 0
print(score is None, score == 0, bool(score)) # False True False05Using None by mistake
The most common beginner error with None is calculating with it. If a name is None because something returned nothing, None + 10 raises a TypeError that mentions NoneType. When you see 'NoneType' in an error, ask: which earlier line was supposed to give me a value and did not?
06True and False cannot be renamed
True, False and None are keywords. You cannot assign to them. True = 5 is a SyntaxError with the message cannot assign to True. (In the old Python 2 you could, with confusing results.)
Try it yourself
- 1
Count with True
Write
a = 5,b = -2,c = 9. Print(a > 0) + (b > 0) + (c > 0). Predict the answer, then run. It counts how many are positive. - 2
Test the truthiness of your own values
Call
bool()on0.1,"0","",[],[None]andNone. Write your prediction before running each one.
Code & diagrams
Predict each line of the bool() group first. Which surprised you?
Expected output
2 10
True
<class 'bool'> <class 'NoneType'>
False True True False
False True True
False True
FalseThe word hello is printed by print itself. The None on the next line is what print returned.
Expected output
None
True
True
<class 'NoneType'>
hello
None
False True FalseRealistic bugs: treating 0 as missing, trusting bool("False"), and assigning the result of list.sort(). The dictionary and list in it are taught in Phase 4; for now read them as a record and a list of values.
Expected output
age given: True | age is falsy: True
nickname missing: True
bool of the word: True | parsed: False
3 4 0.75
{1: 'c'}
None [1, 2, 3]Break it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Add to None
Add 10 to a variable that holds None.
bonus = None
total = bonus + 10Break #2
Assign to True
Try to store 5 in True.
True = 5Myth vs fact
Myth
bool("False") is False.
Fact
Any non-empty text is truthy, including the word "False". If you read the word "False" from a file or a user, you must compare the text yourself.
Myth
None, 0 and "" are all the same.
Fact
They are all falsy, but they are different values: a number, empty text and "no value". Code that must tell them apart uses is None or == 0.
Myth
== None and is None are equivalent, so it does not matter.
Fact
is None is the right test. A class (a blueprint for making your own kinds of value; Phase 8) can define == to say yes to anything, but nothing can change what is None means. Linters (tools that read code and warn about suspicious lines; Topic 11.6) flag == None.
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
TrueandFalseare built-in singletons, likeNone.True is Truealways holds, which is whyif x is Trueworks, but it is almost never what you want: writeif x:for truthiness orif x == Trueonly in tests. - ▸
boolcannot be subclassed (class B(bool)raisesTypeError), which keeps the two values truly unique. - ▸
Because
True == 1andhash(True) == hash(1), they collide as dictionary keys and set members:{1: "a", True: "b"}is{1: "b"}, and{0, False, 0.0}has one element. The same applies to1.0. Arithmetic works too:~Trueis-2(bitwise not on the int 1), a surprise when someone writes~flaginstead ofnot flag. Bitwise&,|and^on two bools return a bool, butand/orreturn an operand (Topic 1.8). - ▸
Noneis the only instance ofNoneType, andNoneTypecannot be created again, sois Noneis both correct and the fastest test. A function with noreturnreturnsNoneimplicitly, and so does a method likelist.sort()that mutates in place.lst = lst.sort()therefore setslsttoNone, one of the most common bugs in real code. - ▸
Truthiness for your own classes is controlled by
__bool__or__len__(Phase 8). That is why a container is falsy when it is empty. NumPy arrays refuse truthiness for arrays with more than one element and raiseValueError, to stop you writingif array:. - ▸
In AI code,
Nonemarks "not set" in a lot of configuration:max_tokens=Noneoften means "use the default". Usingis Nonerather than falsiness there avoids bugs where0was a real choice.
Remember this
- 1
TrueandFalseare the only two values of typebool. They start with a capital letter. Comparisons produce them:5 > 3isTrue,2 == 3isFalse. You will use them in Phase 2 to decide which lines of the program run. - 2
boolis a **subclass ofint**.Truebehaves like 1 andFalselike 0, soTrue + Trueis2andTrue * 10is10. This is a historical decision. It is handy for counting how many conditions are true, but it also meansisinstance(True, int)isTrue. (isinstance(value, type)asks "is this value of that type?"; Topic 1.6 covers it.) - 3
Noneis a single special value, the only value of typeNoneType. It means "no value" or "nothing here yet". A function that does not return anything gives backNone(evenprintdoes: it shows text, then returnsNone). Always test for it with **is None**, not== None. - 4
Every Python value can be treated as true or false when it appears in a condition. This is called its truthiness. The falsy values are:
False,None, zero of every kind (0,0.0), and anything empty ("",[], and the empty dictionary and set you will meet in Phase 4). Everything else is truthy. - 5
bool(x)shows the truthiness ofx. Be careful with text:bool("False")isTrue, because the text is not empty. Andbool(" ")(one space) isTruetoo. Truthiness only asks "is there something here?", never "does it say yes?". - 6
Do not mix up the three "empties":
0is a number,""is empty text,Noneis no value at all. All three are falsy, but they are different. A score of0is a real result; a score ofNonemeans "not marked yet". Treating them the same is a classic bug.
Explain it without notes
Which values are falsy in Python? Give at least five.
Why should you test x is None and not x == None?
What is the relationship between bool and int?
Why does bool("False") return True?
Practice
Set x = 0 and y = None. Print bool(x) and bool(y), and then x is None and y is None.
Set a = 3, b = 0, c = 7 and print how many of them are non-zero by adding up bool() values.
Store the result of print("hi") in a variable and print the variable. Say what it shows.
Trade-offs
- ↔
Short truthiness checks vs. explicit checks.
if name:is short, but it treats0and""the same. Use an explicit test (is None,== 0,len(x) == 0) when the difference matters. - ↔
**
Nonefor "missing" vs. a special value.**Noneis clear and cannot be mistaken for real data, but any code that uses the value must check for it. A hiddenNoneis the cause of manyTypeErrors.
Done when you can
Done when you can list the falsy values of Python.
Done when you can explain why
True + Trueis 2.Done when you can say why
is Noneis the correct check.Done when you can tell
0,""andNoneapart and say when each is used.Done when you can read a
TypeErrorthat mentionsNoneType.