❝ Wonder is the foundation of all philosophy, research its progress, ignorance its end. ❞
— Michel de Montaigne
A short digression is in order. Put aside your first Python program for just a minute, and let's talk about Python's native datatypes. These types are the foundation on which you will build all your future Python programs.
Python has many native datatypes. Here are the important ones:
True or False.
1 and 2), floats (1.1 and 1.2), fractions (1/2 and 2/3), or even complex numbers (i, the square root of -1).
Of course, there are a lot more types than these seven. Everything is an object in Python, so there are types like module, function, class, method, file, and even compiled code. You've already seen some of these: modules have names, functions have docstrings, &c. You'll learn about classes in [FIXME xref] and files in [FIXME xref].
Strings and bytes are important enough — and complicated enough — that they get their own chapter. Let's look at the others first.
Booleans are either true or false. Python has two constants, True and False, which can be used to assign boolean values directly. Expressions can also evaluate to a boolean value. In certain places (like if statements), Python expects an expression to evaluate to a boolean value. These places are called boolean contexts. You can use virtually any expression in a boolean context, and Python will try to determine its truth value. Different datatypes have different rules about which values are true or false in a boolean context. (This will make more sense once you see some concrete examples later in this chapter.)
For example, take this snippet from humansize.py:
if size < 0:
raise ValueError('number must be non-negative')
size is an integer, 0 is an integer, and < is a numerical operator. The result of the expression size < 0 is always a boolean. You can test this yourself in the Python interactive shell:
>>> size = 1 >>> size < 0 False >>> size = 0 >>> size < 0 False >>> size = -1 >>> size < 0 True
math moduleNoneNone is a special constant in Python. It is a null value. None is not False; it is not 0; it is not an empty string. Comparing None to anything other than None will always return False.
None is the only null value. It has its own datatype (NoneType). You can assign None to any variable, but you can not create other NoneType objects. All variables whose value is None are equal to each other.
>>> type(None) <class 'NoneType'> >>> None == False False >>> None == 0 False >>> None == '' False >>> None == None True >>> x = None >>> x == None True >>> y = None >>> x == y True
© 2001-4, 2009 ℳark Pilgrim, CC-BY-3.0