❝ 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 datatypes. Every variable has a datatype, even though you don't declare it explicitly. Based on each variable's original assignment, Python figures out what type it is and keeps tracks of that internally.
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
Numbers are awesome. There are so many to choose from. Python supports both integers and floating point numbers. There's no type declaration to distinguish them; Python tells them apart by the presence or absence of a decimal point.
>>> type(1) ① <class 'int'> >>> 1 + 1 ② 2 >>> 1 + 1.0 ③ 2.0 >>> type(2.0) <class 'float'>
type() function to check the type of any value or variable. As you might expect, 1 is an int.
int to an int yields an int.
int to a float yields a float. Python coerces the int into a float to perform the addition, then returns a float as the result.
As you just saw, some operators (like addition) will coerce integers to floating point numbers as needed. You can also coerce them by yourself.
>>> float(2) ① 2.0 >>> int(2.0) ② 2 >>> int(2.5) ③ 2 >>> int(-2.5) ④ -2 >>> 1.12345678901234567890 ⑤ 1.1234567890123457 >>> type(1000000000000000) ⑥ <class 'int'>
int to a float by calling the float() function.
float to an int by calling int().
int() function will truncate, not round.
int() function truncates negative numbers towards 0. It's a true truncate function, not a a floor function.
☞Python 2 had separate types for
intandlong. Theintdatatype was limited bysys.maxint, which varied by platform but was usually232-1. Python 3 has just one integer type, which behaves mostly like the oldlongtype from Python 2. See PEP 237 for details.
You can do all kinds of things with numbers.
>>> 11 / 2 ① 5.5 >>> 11 // 2 ② 5 >>> −11 // 2 ③ −6 >>> 11.0 // 2 ④ 5.0 >>> 11 ** 2 ⑤ 121 >>> 11 % 2 ⑥ 1
/ operator performs floating point division. It returns a float even if both the numerator and denominator are ints.
// operator performs a quirky kind of integer division. When the result is positive, you can think of it as truncating (not rounding) to 0 decimal places, but be careful with that.
// operator rounds “up” to the nearest integer. Mathematically speaking, it's rounding “down” since −6 is less than −5, but it could trip you up if you expecting it to truncate to −5.
// operator doesn't always return an integer. If either the numerator or denominator is a float, it will still round to the nearest integer, but the actual return value will be a float.
** operator means “raised to the power of.” 112 is 121.
% operator gives the remainder after performing integer division. 11 divided by 2 is 5 with a remainder of 1, so the result here is 1.
☞In Python 2, the
/operator usually meant integer division, but you could make it behave like floating point division by including a special directive in your code. In Python 3, the/operator always means floating point division. See PEP 238 for details.
FIXME fractions, math module, numbers in a boolean context
FIXME
FIXME
One of Python's most important datatypes is the dictionary, which defines one-to-one relationships between keys and values.
☞A dictionary in Python is like a hash in Perl 5. In Perl 5, variables that store hashes always start with a
%character. In Python, variables can be named anything, and Python keeps track of the datatype internally.
Creating a dictionary is easy. The syntax is similar to sets, but instead of values, you have key-value pairs. Once you have a dictionary, you can look up values by their key.
>>> a_dict = {"server":"db.diveintopython3.org", "database":"mysql"} ①
>>> a_dict
{'server': 'db.diveintopython3.org', 'database': 'mysql'}
>>> a_dict["server"] ②
'db.diveintopython3.org'
>>> a_dict["database"] ③
'mysql'
>>> a_dict["db.diveintopython3.org"] ④
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'db.diveintopython3.org'
'server' is a key, and its associated value, referenced by a_dict["server"], is 'db.diveintopython3.org'.
'database' is a key, and its associated value, referenced by a_dict["database"], is 'mysql'.
a_dict["server"] is 'db.diveintopython3.org', but a_dict["db.diveintopython3.org"] raises an exception, because 'db.diveintopython3.org' is not a key.
Dictionaries do not have any predefined size limit. You can add new key-value pairs to a dictionary at any time, or you can modify the value of an existing key. Continuing from the previous example:
>>> a_dict
{'server': 'db.diveintopython3.org', 'database': 'mysql'}
>>> a_dict["database"] = "blog" ①
>>> a_dict
{'server': 'db.diveintopython3.org', 'database': 'blog'}
>>> a_dict["user"] = "mark" ②
>>> a_dict ③
{'server': 'db.diveintopython3.org', 'user': 'mark', 'database': 'blog'}
>>> a_dict["user"] = "dora" ④
>>> a_dict
{'server': 'db.diveintopython3.org', 'user': 'dora', 'database': 'blog'}
>>> a_dict["User"] = "mark" ⑤
>>> a_dict
{'User': 'mark', 'server': 'db.diveintopython3.org', 'user': 'dora', 'database': 'blog'}
'user', value 'mark') appears to be in the middle. In fact, it was just a coincidence that the elements appeared to be in order in the first example; it is just as much a coincidence that they appear to be out of order now.
user key back to "mark"? No! Look at the key closely — that's a capital U in "User". Dictionary keys are case-sensitive, so this statement is creating a new key-value pair, not overwriting an existing one. It may look similar to you, but as far as Python is concerned, it's completely different.
Dictionaries aren't just for strings. Dictionary values can be any datatype, including integers, booleans, arbitrary objects, or even other dictionaries. And within a single dictionary, the values don't all need to be the same type; you can mix and match as needed. Dictionary keys are more restricted, but they can be strings, integers, and a few other types. You can also mix and match key datatypes within a dictionary.
In fact, you've already seen a dictionary with non-string keys and values, in your first Python program.
SUFFIXES = {1000: ('KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'),
1024: ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')}
Let's tear that apart in the interactive shell.
>>> SUFFIXES = {1000: ('KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'),
... 1024: ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')}
>>> len(SUFFIXES) ①
2
>>> SUFFIXES[1000] ②
('KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
>>> SUFFIXES[1024] ③
('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB')
>>> SUFFIXES[1000][3] ④
'TB'
len() function gives you the number of items in a dictionary.
1000 is a key in the SUFFIXES dictionary; its value is a tuple of eight items (eight strings, to be precise).
1024 is a key in the SUFFIXES dictionary; its value is also a tuple of eight items.
SUFFIXES[1000] is a tuple, you can address individual items in the tuple by their 0-based index.
NoneNone 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