0% found this document useful (0 votes)
6 views36 pages

Reading Sample Sap Press Python 3

The document provides an overview of numeric data types in Python, including int, float, bool, and complex, detailing their characteristics and operators. It explains arithmetic and comparison operators, as well as conversion methods between these data types. The chapter is part of 'Python 3: The Comprehensive Guide' by Johannes Ernesti and Peter Kaiser, published in 2022.

Uploaded by

aslmw8337
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views36 pages

Reading Sample Sap Press Python 3

The document provides an overview of numeric data types in Python, including int, float, bool, and complex, detailing their characteristics and operators. It explains arithmetic and comparison operators, as well as conversion methods between these data types. The chapter is part of 'Python 3: The Comprehensive Guide' by Johannes Ernesti and Peter Kaiser, published in 2022.

Uploaded by

aslmw8337
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Build and deepen your coding knowledge

from the top programming experts!

Reading Sample
This chapter covers numeric data types, a major group of data types in the
Python language. First, you’ll learn about arithmetic and comparison ope-
rators, then see how to convert numeric data types using the int, float, bool,
and complex functions. The chapter then goes into more detail on each of
these functions, starting with int data type, which is used when working
with integers. Next, you’ll see how to use the float data type to store floats,
then learn about Boolean values and using operators to create Boolean
expressions. The chapter concludes with an overview of using the complex
data type to store complex numbers.

“Numeric Data Types”

Contents

Index

The Author

Johannes Ernesti, Peter Kaiser


Python 3: The Comprehensive Guide
1036 pages, 2022, $59.95
ISBN 978-1-4932-2302-2

[Link]/5566
Chapter 11
Numeric Data Types

In this chapter, we’ll describe numeric data types, the first major group of data types in
Python. Table 11.1 lists all the data types belonging to this group and describes their pur-
pose. 11

Data Type Description Mutability* Section

int Integers Immutable Section 11.4

float Floats Immutable Section 11.5

bool Boolean values Immutable Section 11.6

complex Complex numbers Immutable Section 11.7


* All numeric data types are immutable. This doesn’t mean that there are no operators that
change numbers, but rather that a new instance of the respective data type must be cre-
ated after each change. So from the programmer's perspective, there is hardly any differ-
ence at first. For more details on the difference between mutable and immutable data
types, see Chapter 7, Section 7.3.

Table 11.1 Numeric Data Types

The numeric data types form a group because they’re related thematically. This related-
ness is also reflected in the fact that the numeric data types have many operators in
common. In the following sections, we’ll cover these common operators, and then we’ll
discuss the int, float, bool, and complex numeric data types in detail.

11.1 Arithmetic Operators


An arithmetic operator is considered an operator that performs an arithmetic calcula-
tion—for example, addition or multiplication. For all numeric data types, the arithme-
tic operators listed in Table 11.2 are defined.

Operator Result

x+y Sum of x and y

x-y Difference of x and y

Table 11.2 Common Operators of Numeric Data Types

131
11 Numeric Data Types 11.2 Comparison Operators

Operator Result Operator Equivalent

x*y Product of x and y x += y x=x+y

x/y Quotient of x and y x -= y x=x-y

x%y Remainder when dividing x by y* x *= y x=x*y

+x Positive sign x /= y x=x/y

-x Negative sign x %= y x=x%y

x ** y x to the power of y x **= y x = x ** y


11
x // y Rounded quotient of x and y* x //= y x = x // y
* The % and // operators have no mathematical meaning for complex numbers and are Table 11.3 Common Operators of Numeric Data Types
therefore not defined for the complex data type.

Table 11.2 Common Operators of Numeric Data Types (Cont.) It’s important to note that you can use any arithmetic expression for y here, while x
must be an expression that could also be used as the target of a normal assignment
such as a symbolic name or an item of a list or dictionary.
Note
Two notes for readers who are already familiar with C or a related programming lan-
guage: 11.2 Comparison Operators
First, there are no equivalents in Python for the increment and decrement operators, ++ A comparison operator is an operator that computes a truth value from two instances.
and --, from C. Table 11.4 lists the comparison operators defined for numeric data types.
Second, the % and // operators can be described as follows:
Operator Result
쐍 x // y = round(x / y)
쐍 x % y = x - y * round(x / y) x == y True if x and y are equal

Python always rounds down, while C rounds up to zero. This difference occurs only if x != y True if x and y are different
the operands have opposite signs.
x<y True if x is less than y*

x <= y True if x is less than or equal to y*


Augmented Assignments
x>y True if x is greater than y*
Besides these basic operators, there are a number of additional operators in Python.
x >= y True if x is greater than or equal to y*
Often, for example, you want to calculate the total of x and y and store the result in x—
that is, increase x by y. This requires the following statement with the operators shown * Because complex numbers can’t be arranged in a meaningful way, the complex data type
previously: only allows for using the first two operators.

x = x + y Table 11.4 Common Operators of Numeric Data Types

For such cases, Python provides so-called augmented assignments, which can be
Each of these comparison operators returns a truth value as a result. Such a value is
regarded as an abbreviated form of the preceding statement. An overview of aug-
expected, for example, as a condition of an if statement. So the operators could be
mented assignments in Python in presented in Table 11.3.
used as follows:

132 133
11 Numeric Data Types 11.4 Integers: int

if x < 4: So much for the general introduction to numeric data types. The following sections will
print("x is less than 4") cover each data type in this group in more detail.

You can concatenate as many of the comparison operators as you like into a series.
Strictly speaking, the preceding example is only a special case of this rule, as it has only
11.4 Integers: int
two operands. The meaning of such a concatenation corresponds to the mathematical
view and can be seen in the following example: For working with integers, there is the data type int in Python. Unlike many other pro-
gramming languages, this data type is not subject to any principal limits in its value
if 2 < x < 4:
range, which makes dealing with large integers in Python very convenient.1
print("x is between 2 and 4")
We've already done a lot of work with integers, so using int doesn't really need any
We’ll describe Boolean values in more detail in Section 11.6. more demonstration. Nevertheless, for the sake of completeness, here is a small exam- 11
ple:

>>> i = 1234
11.3 Conversion between Numeric Data Types
>>> i
Numeric data types can be converted into each other using the int, float, bool, and 1234
complex built-in functions. Note that in the process, information can be lost depending >>> p = int(5678)
on the transformation. As an example, let's consider some conversions in interactive >>> p
mode: 5678

>>> float(33) Since the release of Python 3.6, an underscore can be used to group the digits of a lit-
33.0 eral:
>>> int(33.5)
>>> 1_000_000
33
1000000
>>> bool(12)
>>> 1_0_0
True
100
>>> complex(True)
(1+0j)
Grouping doesn’t change the numerical value of the literal, but it serves to increase the
readability of numerical literals. Whether and how you group the digits is up to you.
Instead of a concrete literal, a reference can also be used or a reference can be linked to
the resulting value:

>>> var1 = 12.5 11.4.1 Numeral Systems


>>> int(var1) Integers can be written in Python in multiple numeral systems:2
12
쐍 Numbers written without a special prefix, as in the previous example, are inter-
>>> var2 = int(40.25)
preted in the decimal system (base 10). Note that such a number must not be pre-
>>> var2
ceded by leading zeros:
40
v_dez = 1337

Note
The complex data type assumes a special role in the conversions presented here as it
can’t be reduced to a single numerical value in a meaningful way. For this reason, a 1 In Python 2, there were still two data types for integers: int for the limited number space of 32 bits
conversion such as int(1+2j) fails. or 64 bits, and long with an unlimited value range.
2 If you don’t know what a numeral system is, you can easily skip this section.

134 135
11 Numeric Data Types 11.4 Integers: int

쐍 The prefix 0o ("zero-o") indicates a number written in the octal system (base 8). Note Note that the numeral systems are only alternate notations of the same values. The int
that only digits from 0 to 7 are allowed here: data type, for example, doesn’t switch to a kind of hexadecimal mode as soon as it con-
v_oct = 0o2471 tains such a value; the numeral system is only of importance for assignments or out-
puts. By default, all numbers are output in the decimal system:
The lowercase o in the prefix can also be replaced with a capital O. However, we rec-
ommend that you always use a lowercase o because the uppercase O is almost indis- >>> v1 = 0xFF
tinguishable from the zero in many fonts. >>> v2 = 0o777
쐍 The next and far more common variant is the hexadecimal system (base 16), which is >>> v1
255
identified by the prefix 0x or 0X (“zero-x”). The number itself may be formed from
>>> v2
the digits 0–9 and the letters A–F or a–f:
511
v_hex = 0x5A3F 11
쐍 In addition to the hexadecimal system, the dual system, also referred to as binary We’ll return to how numbers can be output in other numeral systems later, in Chapter
system (base 2), is of decisive importance in computer science. Numbers in the dual 12, Section 12.5.3 in the context of strings.
system are introduced by the prefix 0b, similar to the preceding literals:
v_bin = 0b1101 11.4.2 Bit Operations
In the dual system, only the digits 0 and 1 may be used. As already mentioned, the dual system or binary system is of great importance in com-
However, you may not want to limit yourself to these four numeral systems explicitly puter science. For the int data type, some additional operators are therefore defined
supported by Python; you may want to use a more exotic one. Of course, Python that explicitly refer to the binary representation of the number. Table 11.5 summarizes
doesn’t have a separate literal for every possible numeral system. Instead, you can use these bit operators.
the following notation:
Operator Augmented Assignment Result
v_6 = int("54425", 6)
x&y x &= y Bitwise AND of x and y (AND)

This is an alternative method of creating an instance of the int data type and providing x|y x |= y Bitwise nonexclusive OR of x and y (OR)
it with an initial value. For this purpose, a string containing the desired initial value in
x^y x ^= y Bitwise exclusive OR of x and y (XOR)
the selected numeral system and the base of this numeral system as an integer are writ-
ten in the brackets. Both values must be separated by a comma. In the example, a base ~x Bitwise complement of x
6 system was used.
x << n x <<= n Bit shift by n places to the left
Python supports numeral systems with a base from 2 to 36. If a numeral system
x >> n x >>= n Bit shift by n places to the right
requires more than 10 different digits to represent a number, the letters A to Z of the
English alphabet are used in addition to the digits 0 to 9. Table 11.5 Bit Operators of the int Data Type
The v_6 variable now has the value 7505 in the decimal system.
For all numeral system literals, the use of a negative sign is possible: Because it may not be immediately clear what the individual operations do, we’ll
describe them in detail ahead.
>>> -1234
-1234
Bitwise AND
>>> -0o777
-511 The bitwise AND of two numbers is formed by linking both numbers in their binary rep-
>>> -0xFF resentation bit by bit. The resulting number has a 1 in its binary representation exactly
-255 where both of the respective bits of the operands are 1, and a 0 in all other places. Figure
>>> -0b1010101 11.1 illustrates this.
-85

136 137
11 Numeric Data Types 11.4 Integers: int

>>> bin(0b1101011 | 0b11001)


Binary Decimal
'0b1111011'
1 1 0 1 0 1 1 107

& 0 0 1 1 0 0 1 25 In the example we use the built-in function bin (see Chapter 17, Section 17.14.5) to repre-
sent the result of the bitwise OR in the binary system.
0 0 0 1 0 0 1 9
Bitwise Exclusive OR
Figure 11.1 Bitwise AND
The bitwise exclusive OR (also exclusive OR) of two numbers is formed by comparing
both numbers in their binary representation bit by bit. The resulting number has a 1 in
Let’s now try out in the interactive mode of Python whether the bitwise AND with the
its binary representation exactly where the respective bits of the operands differ from
operands selected in the graphic actually returns the expected result: 11
each other, and a 0 where they are the same. This is shown in Figure 11.3.
>>> 107 & 25
9 Binary Decimal

>>> 0b1101011 & 0b11001 1 1 0 1 0 1 1 107


9 ^ 0 0 1 1 0 0 1 25
>>> bin(0b1101011 & 0b11001)
'0b1001' 1 1 1 0 0 1 0 114

In the example we use the built-in function bin (see Chapter 17, Section 17.14.5) to repre- Figure 11.3 Bitwise Exclusive OR
sent the result of the bitwise AND in the binary system.
In the next step, we’ll try out in the interactive mode of Python whether the bitwise
Bitwise OR exclusive OR with the operands selected in the graphic actually returns the expected
The bitwise OR of two numbers is formed by comparing both numbers in their binary result:
representation bit by bit. The resulting number has a 1 in its binary representation
>>> 107 ^ 25
exactly where at least one of the respective bits of the operands is 1. Figure 11.2 illus-
114
trates this. >>> 0b1101011 ^ 0b11001
114
Binary Decimal
>>> bin(0b1101011 ^ 0b11001)
1 1 0 1 0 1 1 107 '0b1110010'
| 0 0 1 1 0 0 1 25
In the example we use the built-in function bin (see Chapter 17, Section 17.14.5) to repre-
1 1 1 1 0 1 1 123 sent the result of the bitwise exclusive OR in the binary system.

Figure 11.2 Bitwise Nonexclusive OR Bitwise Complement


The bitwise complement forms the so-called one’s complement of a dual number,
We’ll now try out in the interactive mode of Python whether the bitwise OR with the which corresponds to the negation of all occurring bits. In Python, this isn’t possible at
operands selected in the graphic actually returns the expected result: the bit level because an integer is unlimited in length and the complement must
>>> 107 | 25 always be formed in a closed number space. For this reason, the actual bit operation
123 becomes an arithmetic operation and is defined as follows:3
>>> 0b1101011 | 0b11001
3 This makes sense because the so-called two's complement is used to represent negative numbers in
123 closed number spaces. This is obtained by adding 1 to the ones’ complement.
So: –x = two's complement of x = ~x + 1. From this follows: ~x = –x – 1.

138 139
11 Numeric Data Types 11.5 Floats: float

~x = –x – 1 For the bitwise shifts too, we can follow the examples shown in the graphics in the
In the interactive mode, the functionality of the bitwise complement can be tested interactive mode:
experimentally: >>> 107 << 2
428
>>> ~9
>>> 107 >> 2
–10
26
>>> ~0b1001
>>> bin(0b1101011 << 2)
-10
'0b110101100'
>>> bin(~0b1001)
>>> bin(0b1101011 >> 2)
'-0b1010'
'0b11010'
11
In the example we use the built-in function bin (see Chapter 17, Section 17.14.5) to repre-
In the example we use the built-in function bin (see Chapter 17, Section 17.14.5) to repre-
sent the result of the bitwise complement in the binary system.
sent the result of the bit shifts in the binary system.

Bit Shift
The bit shift is used to shift the bit sequence in the binary representation of the first 11.4.3 Methods
operand to the left or right by the number of places provided by the second operand. The int data type has a method that refers to the binary representation of the integer.
Any gaps that occur on the right-hand side are filled with zeros, and the sign of the first The bit_length method calculates the number of digits needed for the binary represen-
operand is retained. Figure 11.4 and Figure 11.5 illustrate a shift of two places to the left tation of the number:
and to the right, respectively.
>>> (36).bit_length()
Binary Decimal 6
>>> (4345).bit_length()
1 1 0 1 0 1 1 107
13
n=2

1 1 0 1 0 1 1 0 0 428 The binary representation of 36 is 100100, and that of 4345 is 1000011111001. Thus, the
two numbers require 6 and 13 digits, respectively, for their binary representation.
Figure 11.4 Bit Shift by Two Places to the Left
Note
Binary Decimal Note that the parentheses around the number literals are required for integers; other-
1 1 0 1 0 1 1 107
wise there could be ambiguities with regard to the syntax for floats.

n=2

1 1 0 1 0 26
11.5 Floats: float
Figure 11.5 Bit Shift by Two Places to the Right
We mentioned floats briefly earlier. Now we’d like to describe in them in greater detail.
To store a float with limited precision,4 you can use the float data type.
The gaps that occur in the bit representation on the right- or left-hand side are filled
with zeros. As discussed previously, the literal for a float in the simplest case looks like this:

The bit shift is implemented arithmetically in Python, similar to the complement oper- v = 3.141
ator. A shift by x places to the right corresponds to an integer division by 2x. A shift by
x places to the left corresponds to a multiplication by 2x.
4 See Section 11.5.2 for further remarks on the precision.

140 141
11 Numeric Data Types 11.5 Floats: float

The parts before and after the period can be omitted if they have the value 0: 11.5.3 Infinite and Not a Number
>>> -3. The precision of float is limited. This also implies that there must be both an upper and
-3.0 lower limit for this data type. And indeed, floats that exceed a certain limit in size can
>>> .001 no longer be represented in Python. If the limit is exceeded, the number is stored as
0.001 inf5 or as -inf if the number has fallen below the lower limit. So there is no error, and
it’s still possible to compare a number that’s too high with others:
Note here that the period is an essential element of a float literal and as such must not
be omitted. >>> 3.0e999
inf
Since Python 3.6, an underscore can also be used to group the digits of a float literal:
>>> -3.0e999
>>> 3.000_000_1 -inf 11
3.0000001 >>> 3.0e999 < 12.0
False
>>> 3.0e999 > 12.0
11.5.1 Exponential Notation True
Python also supports a notation that allows you to use the exponential notation: >>> 3.0e999 == 3.0e999999999999
True
v = 3.141e-12
Although it’s possible to compare two infinitely large floats with each other, you can
A lowercase or uppercase e separates the mantissa (3.141) from the exponent (-12). only use them to a limited extent for calculations. Let's look at the following example:
Translated into mathematical notation, this corresponds to the value 3.141 · 10–12. Note
that both the mantissa and the exponent must be specified in the decimal system. As >>> 3.0e999 + 1.5e999999
no other numeral systems are supported, it’s safe to use leading zeros: inf
>>> 3.0e999 - 1.5e999999
v = 03.141e-0012 nan
>>> 3.0e999 * 1.5e999999
inf
11.5.2 Precision
>>> 3.0e999 / 1.5e999999
You may have just experimented a bit with floats and encountered a supposed error in nan
the interpreter: >>> 5 / 1e9999
0.0
>>> 1.1 + 2.2
3.3000000000000003 Two infinite floats can be easily added or multiplied. The result in both cases is again
inf. However, there’s a problem when trying to subtract or divide two such numbers.
Real numbers can’t be stored with infinite precision in the float data type, but are
Because these arithmetic operations don’t make sense, they result in nan. The nan status
instead approximated.
is comparable to inf, but it means "not a number"—that is, not calculable.
Technically savvy people and those switching from other programming languages will
Note that neither inf nor nan is a constant you could use yourself in a Python program.
be interested to know that float instances in Python are IEEE-754 floats with double
Instead, you can create float instances with the values inf and nan as follows:
precision. The float data type in Python is thus comparable to the double data type in
C, C++, and Java. >>> float("inf")
If you want to explicitly use single precision floats, you can draw on the float32 data inf
>>> float("nan")
type of the third-party NumPy library (see Chapter 43).
nan

5 Here, inf stands for infinity.

142 143
11 Numeric Data Types 11.6 Boolean Values: bool

>>> float("inf") / float("inf") Logical AND


nan The logical AND between two truth values only returns True if both operands are
already True. Table 11.7 lists all possible cases.

11.6 Boolean Values: bool x y x and y

An instance of the bool6 data type can have only two different values: true or false—or, True True True

to stay within the Python syntax, True or False. For this reason, it’s absurd to categorize False True False
bool as a numeric data type at first glance. As is common usage in many programming
True False False
languages, in Python, True is regarded as similar to 1 and False as similar to 0, so that
Boolean values can be calculated in the same way as, for example, integers. The names False False False 11
True and False are constants that can be used in the source code. Note especially that
Table 11.7 Possible Cases of Logical AND
the constants start with an uppercase letter:

v1 = True In a concrete example, the application of logical AND would look as follows:
v2 = False
if x and y:
print("x and y are True")
11.6.1 Logical Operators
One or more Boolean values can be combined into a Boolean expression using certain Logical OR
operators. When evaluated, such an expression results again in a Boolean value—that The logical OR between two truth values results in a true statement if and only if at least
is, True or False. Before it gets too theoretical, Table 11.6 shows the so-called logical oper- one of the two operands is true. Accordingly, it’s a nonexclusive OR. An operator for a
ators.7 We’ll follow that with further explanations and concrete examples. logical exclusive OR doesn’t exist in Python.8 Table 11.8 lists all possible cases.

Operator Result x y x or y

not x Logical negation of x True True True

x and y Logical AND between x and y False True True

x or y Logical (nonexclusive) OR between x and y True False True

Table 11.6 Logical Operators of the bool Data Type False False False

Table 11.8 Possible Cases of Logical OR


Logical Negation
The logical negation of a Boolean value can be quickly explained: the corresponding not
A logical OR could be implemented as follows:
operator turns True into False and False into True. In a concrete example, this would
look as follows: if x or y:
print("x or y is True")
if not x:
print("x is False") Of course, you can combine all these operators and use them in a complex expression.
else: This could look something like this:
print("x is True")
if x and y or ((y and z) and not x):
6 The name bool goes back to the British mathematician and logician George Boole (1815–1864). print("Holy cow")
7 Note that there’s a difference between logical operators, which refer to Boolean values, and binary
operators, which refer to the binary representation of a number. 8 A logical exclusive OR between x and y can be modeled using (x or y) and not (x and y).

144 145
11 Numeric Data Types 11.6 Boolean Values: bool

At this point, we don’t want to discuss this expression in further detail. Suffice to say This is a useful property because an instance of the basic data types can often be in one
that the use of parentheses has the expected effect—namely, that expressions in of two stages: "empty" and "nonempty." For example, it often happens that you want to
parentheses are evaluated first. Table 11.9 shows the truth value of the expression, as a test whether a string contains letters or not. Because a string can be converted to a
function of the three parameters x, y, and z. Boolean value, such a test is made very easy by logical operators:

x y z x and y or ((y and z) and not x) >>> not ""


True
True True True True >>> not "abc"
False True True True False

True False True False By using a logical operator, the operand is automatically interpreted as a truth value.
11
True True False True For each basic data type, a specific value is defined as False. All other values are True.
Table 11.10 lists the corresponding False value for each data type. Some of the data
False False True False
types haven’t been introduced yet, but you shouldn’t worry about that at this point.
False True False False
Basic Data Type False Value Description
True False False False
NoneType None The None value
False False False False
Numeric Data Types
Table 11.9 Possible Results of the Expression
int 0 The numeric value zero

The Combination of Logical Operators and Comparison Operators float 0.0 The numeric value zero

At the beginning of the section on numeric data types, we introduced some compari- bool False The boolean value False
son operators that yield a truth statement as a Boolean value. The following example
complex 0 + 0j The numeric value zero
shows that they can be used quite normally in combination with the logical operators:
Sequential Data Types
if x > y or (y > z and x != 0):
print("My goodness") str "" An empty string

In this case, x, y, and z must be instances of comparable types, such as int, float, or bool. list [] An empty list

tuple () An empty tuple

11.6.2 Truth Values of Non-Boolean Data Types Associative Data Types


Instances of any basic data type can be converted to a Boolean value using the built-in dict {} An empty dictionary
bool function:
Quantities
>>> bool([1,2,3])
True set set() An empty set

>>> bool("") frozenset frozenset() An empty set


False
>>> bool(-7) Table 11.10 Truth Values of the Basic Data Types
True
All other values result in True.

146 147
11 Numeric Data Types 11.7 Complex Numbers: complex

11.6.3 Evaluating Logical Operators However, these details also have an entertaining value:
Python evaluates logical expressions basically from left to right—so in the following >>> "Python" or "Java"
example, first a, then b: 'Python'

if a or b:
print("a or b are True")
11.7 Complex Numbers: complex
However, it isn’t guaranteed that every part of the expression will actually be evalu-
Surprisingly, there is a data type for storing complex numbers among the basic data
ated. For optimization reasons, Python immediately terminates the evaluation of the
types of Python. In many programming languages, complex numbers would be more
expression when the result has been obtained. So, in the preceding example, if a
of a side note in the standard library or left out altogether. If you aren’t familiar with
already has the value True, the value of b is of no further concern; b would then no lon- 11
complex numbers, you can safely skip this section. It doesn’t cover anything that
ger be evaluated. The following example demonstrates this behavior, which is referred
would be required for further learning Python.
to as lazy evaluation:
Complex numbers consist of a real part and an imaginary part. The imaginary part is a
>>> a = True
real number multiplied by the imaginary unit j.10 The imaginary unit j is defined as the
>>> if a or print("Lazy "):
solution of the following equation:
... print("Evaluation")
... j2 = –1
Evaluation In the following example, we assign the name v to a complex number:

Although the print function is called in the condition of the if statement, this screen v = 4j
output is never performed because the value of the condition is already certain after
If you specify only an imaginary part, as in the example, the real part is automatically
the evaluation of a. This detail seems unimportant, but it can lead to errors that are
assumed to be 0. To determine the real part, it is added to the imaginary part. The fol-
hard to find, especially in the context of functions with side effects.9
lowing two notations are equivalent:
In Section 11.6.1, we mentioned that a Boolean expression always yields a Boolean value
when evaluated. This is not quite correct because here too, the interpreter's way of v1 = 3 + 4j
working has been optimized in a way you should be aware of. This is clearly illustrated v2 = 4j + 3
by the following example from the interactive mode:
Instead of a lowercase j, you can also use an uppercase J as a literal for the imaginary
>>> 0 or 1 part of a complex number. It’s entirely up to your preferences which of the two options
1 you want to use.
Both the real and imaginary parts can be any real number. The following notation is
From what we have discussed so far, the result of the expression should be True, which
therefore also correct:
is not the case. Instead, Python returns the first operand here with the truth value True.
In many cases this does not make a difference, because the returned value is automat- v3 = 3.4 + 4e2j
ically converted to the truth value True without any problem.
At the beginning of the section on numeric data types, we already indicated that com-
The evaluation of the two operators or and and works as follows: The logical OR (or)
plex numbers differ from the other numeric data types. Since no mathematical order-
takes the value of the first operand that has the truth value True, or—if there is no such
ing is defined for complex numbers, instances of the complex data type can only be
operand—the value of the last operand. The logical AND (and) takes the value of the first
checked for equality or inequality. The set of comparison operators is thus limited to
operand that has the truth value False, or—if there is no such value—the value of the
== and !=.
last operand.

10 The symbol of the imaginary unit, which is actually common in mathematics, is i. Python adheres
9 See Chapter 17, Section 17.10. to the notations of electrical engineering here.

148 149
11 Numeric Data Types 11.7 Complex Numbers: complex

Furthermore, both the % modulo operator and the // operator for integer division have >>> c3 = [Link]()
no mathematical sense and are therefore not available in combination with complex >>> c3
numbers. (23+4j)

The complex data type has two attributes that make it easier to use it. For example, it can Conjugating a complex number is a self-inverse operation. This means that the result
happen that you want to make calculations only with the real part or only with the of a double conjugation is again the initial number.
imaginary part of the stored number. To isolate one of the two parts, a complex instance
provides the attributes listed in Table 11.11.

Attribute Description

[Link] Real part of x as a float


11
[Link] Imaginary part of x as a float

Table 11.11 Attributes of the complex Data Type

These can be used as shown in the following example:

>>> c = 23 + 4j
>>> [Link]
23.0
>>> [Link]
4.0

In addition to its two attributes, the complex data type has a method, which is explained
in Table 11.12 as an example of a reference to a complex number called x.

Method Description

[Link]() Returns the complex number conjugated to x

Table 11.12 Methods of the complex Data Type

The following example demonstrates the use of the conjugate method:

>>> c = 23 + 4j
>>> [Link]()
(23-4j)

The result of conjugate is again a complex number and therefore also has the conjugate
method:

>>> c = 23 + 4j
>>> c2 = [Link]()
>>> c2
(23-4j)

150 151
Contents

1 Introduction 33

1.1 Why Did We Write This Book? ......................................................................................... 33

1.2 What Does This Book Provide? ........................................................................................ 34

1.3 Structure of the Book ........................................................................................................... 34

1.4 How Should You Read This Book? .................................................................................. 35

1.5 Sample Programs ................................................................................................................... 36


1.6 Preface To the First English Edition (2022) ................................................................ 36

1.7 Acknowledgments ................................................................................................................ 37

2 The Python Programming Language 39

2.1 History, Concepts, and Areas of Application ............................................................. 39


2.1.1 History and Origin .................................................................................................. 39
2.1.2 Basic Concepts ......................................................................................................... 40
2.1.3 Possible Areas of Use and Strengths ................................................................ 41
2.1.4 Examples of Use ...................................................................................................... 42
2.2 Installing Python .................................................................................................................... 42
2.2.1 Installing Anaconda on Windows ..................................................................... 43
2.2.2 Installing Anaconda on Linux ............................................................................. 43
2.2.3 Installing Anaconda on macOS .......................................................................... 44
2.3 Installing Third-Party Modules ........................................................................................ 45

2.4 Using Python ........................................................................................................................... 45

Part I Getting Started with Python

3 Getting Started with the Interactive Mode 49

3.1 Integers ...................................................................................................................................... 49

3.2 Floats ........................................................................................................................................... 51

3.3 Character Strings ................................................................................................................... 51

7
Contents Contents

3.4 Lists .............................................................................................................................................. 52 5.2 Loops ........................................................................................................................................... 79

3.5 Dictionaries .............................................................................................................................. 53 5.2.1 The while Loop ........................................................................................................ 79


5.2.2 Termination of a Loop ........................................................................................... 80
3.6 Variables .................................................................................................................................... 54
5.2.3 Detecting a Loop Break ......................................................................................... 81
3.6.1 The Special Meaning of the Underscore ......................................................... 54
5.2.4 Aborting the Current Iteration ........................................................................... 82
3.6.2 Identifiers .................................................................................................................. 55
5.2.5 The for Loop .............................................................................................................. 84
3.7 Logical Expressions ............................................................................................................... 55 5.2.6 The for Loop as a Counting Loop ....................................................................... 85
3.8 Functions and Methods ...................................................................................................... 57 5.3 The pass Statement .............................................................................................................. 87
3.8.1 Functions ................................................................................................................... 57 5.4 Assignment Expressions ..................................................................................................... 87
3.8.2 Methods .................................................................................................................... 58 5.4.1 The Guessing Numbers Game with Assignment Expressions ................ 89
3.9 Screen Outputs ....................................................................................................................... 59

3.10 Modules .................................................................................................................................... 60


6 Files 91

4 The Path to the First Program 63 6.1 Data Streams ........................................................................................................................... 91

6.2 Reading Data from a File .................................................................................................... 92


4.1 Typing, Compiling, and Testing ...................................................................................... 63 6.2.1 Opening and Closing a File .................................................................................. 92
4.1.1 Windows ................................................................................................................... 63 6.2.2 The with Statement ............................................................................................... 93
4.1.2 Linux and macOS .................................................................................................... 64 6.2.3 Reading the File Content ..................................................................................... 94
4.1.3 Shebang ..................................................................................................................... 65 6.3 Writing Data to a File ........................................................................................................... 96
4.1.4 Internal Processes .................................................................................................. 65
6.4 Generating the File Object ................................................................................................ 97
4.2 Basic Structure of a Python Program ............................................................................ 66
6.4.1 The Built-In open Function .................................................................................. 97
4.2.1 Wrapping Long Lines ............................................................................................. 68
6.4.2 Attributes and Methods of a File Object ........................................................ 99
4.2.2 Joining Multiple Lines ........................................................................................... 69
6.4.3 Changing the Write/Read Position .................................................................. 100
4.3 The First Program .................................................................................................................. 70
4.3.1 Initialization ............................................................................................................. 71
4.3.2 Loop Header ............................................................................................................. 71
4.3.3 Loop Body .................................................................................................................. 71
7 The Data Model 103

4.3.4 Screen Output .......................................................................................................... 72


7.1 The Structure of Instances ................................................................................................. 105
4.4 Comments ................................................................................................................................. 72
7.1.1 Data Type .................................................................................................................. 106
4.5 In Case of Error ........................................................................................................................ 72 7.1.2 Value ........................................................................................................................... 107
7.1.3 Identity ....................................................................................................................... 108
7.2 Deleting References ............................................................................................................. 109
5 Control Structures 75 7.3 Mutable versus Immutable Data Types ...................................................................... 111

5.1 Conditionals ............................................................................................................................. 75


5.1.1 The if Statement ..................................................................................................... 75
5.1.2 Conditional Expressions ....................................................................................... 78

8 9
Contents Contents

8 Functions, Methods, and Attributes 115 11.4.2 Bit Operations .......................................................................................................... 137
11.4.3 Methods .................................................................................................................... 141

8.1 Parameters of Functions and Methods ........................................................................ 115 11.5 Floats: float .............................................................................................................................. 141
8.1.1 Positional Parameters ........................................................................................... 116 11.5.1 Exponential Notation ............................................................................................ 142
8.1.2 Keyword Arguments .............................................................................................. 116 11.5.2 Precision .................................................................................................................... 142
8.1.3 Optional Parameters ............................................................................................. 117 11.5.3 Infinite and Not a Number .................................................................................. 143
8.1.4 Keyword-Only Parameters .................................................................................. 117 11.6 Boolean Values: bool ........................................................................................................... 144
8.2 Attributes .................................................................................................................................. 118 11.6.1 Logical Operators .................................................................................................... 144
11.6.2 Truth Values of Non-Boolean Data Types ...................................................... 146
11.6.3 Evaluating Logical Operators .............................................................................. 148
11.7 Complex Numbers: complex ............................................................................................ 149
9 Sources of Information on Python 119

9.1 The Built-In Help Function ................................................................................................. 119

9.2 The Online Documentation ............................................................................................... 120 12 Sequential Data Types 153

9.3 PEPs .............................................................................................................................................. 120


12.1 The Difference between Text and Binary Data ........................................................ 153

12.2 Operations on Instances of Sequential Data Types ............................................... 154


12.2.1 Checking for Elements .......................................................................................... 155
Part II Data Types 12.2.2 Concatenation ......................................................................................................... 157
12.2.3 Repetition .................................................................................................................. 158
12.2.4 Indexing ..................................................................................................................... 159
10 Basic Data Types: An Overview 125 12.2.5 Slicing ......................................................................................................................... 160
12.2.6 Length of a Sequence ............................................................................................ 164
12.2.7 The Smallest and the Largest Element ............................................................ 164
10.1 Nothingness: NoneType ..................................................................................................... 126
12.2.8 Searching for an Element .................................................................................... 165
10.2 Operators .................................................................................................................................. 127 12.2.9 Counting Elements ................................................................................................ 166
10.2.1 Operator Precedence ............................................................................................. 127
12.3 The list Data Type .................................................................................................................. 166
10.2.2 Evaluation Order ..................................................................................................... 129
12.3.1 Changing a Value within the List: Assignment via [] ................................. 167
10.2.3 Concatenating Comparisons .............................................................................. 129
12.3.2 Replacing Sublists and Inserting New Elements: Assignment via [] ..... 167
12.3.3 Deleting Elements and Sublists: del in Combination with [] .................. 168
12.3.4 Methods of list Instances ..................................................................................... 169
11 Numeric Data Types 131 12.3.5 Sorting Lists: [Link]([key, reverse]) .................................................................... 171
12.3.6 Side Effects ............................................................................................................... 174
11.1 Arithmetic Operators ........................................................................................................... 131 12.3.7 List Comprehensions ............................................................................................. 177

11.2 Comparison Operators ........................................................................................................ 133 12.4 Immutable Lists: tuple ........................................................................................................ 179
12.4.1 Packing and Unpacking ........................................................................................ 179
11.3 Conversion between Numeric Data Types ................................................................. 134
12.4.2 Immutable Doesn’t Necessarily Mean Unchangeable! ............................. 181
11.4 Integers: int .............................................................................................................................. 135
11.4.1 Numeral Systems ................................................................................................... 135

10 11
Contents Contents

12.5 Strings: str, bytes, bytearray ............................................................................................ 182 15 Date and Time 247
12.5.1 Control Characters ................................................................................................. 185
12.5.2 String Methods ........................................................................................................ 187
15.1 Elementary Time Functions—time ................................................................................ 247
12.5.3 Formatting Strings ................................................................................................. 196
15.1.1 The struct_time Data Type ................................................................................. 248
12.5.4 Character Sets and Special Characters ............................................................ 207
15.1.2 Constants .................................................................................................................. 249
15.1.3 Functions ................................................................................................................... 250
15.2 Object-Oriented Date Management: datetime ....................................................... 254
13 Mappings and Sets 215 15.2.1 [Link] .......................................................................................................... 255
15.2.2 [Link] .......................................................................................................... 256
13.1 Dictionary: dict ....................................................................................................................... 215 15.2.3 [Link] ................................................................................................. 257
13.1.1 Creating a Dictionary ............................................................................................ 215 15.2.4 [Link] ................................................................................................ 259
13.1.2 Keys and Values ...................................................................................................... 216 15.2.5 Operations for [Link] and [Link] ............................. 262
13.1.3 Iteration ..................................................................................................................... 218 15.3 Time Zones: zoneinfo .......................................................................................................... 263
13.1.4 Operators .................................................................................................................. 219 15.3.1 The IANA Time Zone Database .......................................................................... 263
13.1.5 Methods .................................................................................................................... 221 15.3.2 Specifying the Time in Local Time Zones ........................................................ 265
13.1.6 Dict Comprehensions ............................................................................................ 227 15.3.3 Calculating with Time Indications in Local Time Zones ............................ 265
13.2 Sets: set and frozenset ........................................................................................................ 227
13.2.1 Creating a Set .......................................................................................................... 228
13.2.2 Iteration ..................................................................................................................... 229
13.2.3 Operators .................................................................................................................. 230
16 Enumerations and Flags 269

13.2.4 Methods .................................................................................................................... 235


13.2.5 Mutable Sets: set .................................................................................................... 236 16.1 Enumeration Types: enum ................................................................................................ 269
13.2.6 Immutable Sets: frozenset .................................................................................. 237 16.2 Enumeration Types for Bit Patterns: flag ................................................................... 271

16.3 Integer Enumeration Types: IntEnum .......................................................................... 272

14 Collections 239

Part III Advanced Programming Techniques


14.1 Chained Dictionaries ............................................................................................................ 239

14.2 Counting Frequencies .......................................................................................................... 240 17 Functions 277


14.3 Dictionaries with Default Values ................................................................................... 242
17.1 Defining a Function .............................................................................................................. 278
14.4 Doubly Linked Lists ............................................................................................................... 243
17.2 Return Values .......................................................................................................................... 280
14.5 Named Tuples ......................................................................................................................... 245
17.3 Function Objects .................................................................................................................... 282

17.4 Optional Parameters ............................................................................................................ 282

17.5 Keyword Arguments ............................................................................................................ 283

17.6 Arbitrarily Many Parameters ............................................................................................ 284

12 13
Contents Contents

17.7 Keyword-Only Parameters ................................................................................................ 286 17.14.27 len(s) ........................................................................................................................ 315


17.14.28 list([sequence]) ..................................................................................................... 315
17.8 Positional-Only Parameters .............................................................................................. 287
17.14.29 locals() ..................................................................................................................... 315
17.9 Unpacking When Calling a Function ............................................................................. 288 17.14.30 map(function, [*iterable]) ................................................................................. 316
17.10 Side Effects ............................................................................................................................... 290 17.14.31 max(iterable, {default, key}), max(arg1, arg2, [*args], {key}) ................ 317
17.14.32 min(iterable, {default, key}), min(arg1, arg2, [*args], {key}) .................. 318
17.11 Namespaces ............................................................................................................................. 293
17.14.33 oct(x) ........................................................................................................................ 318
17.11.1 Accessing Global Variables: global ................................................................ 293
17.14.34 ord(c) ........................................................................................................................ 318
17.11.2 Accessing the Global Namespace .................................................................. 294
17.14.35 pow(x, y, [z]) .......................................................................................................... 318
17.11.3 Local Functions ..................................................................................................... 295
17.14.36 print([*objects], {sep, end, file, flush}) .......................................................... 318
17.11.4 Accessing Parent Namespaces: nonlocal .................................................... 296
17.14.37 range([start], stop, [step]) ................................................................................. 319
17.11.5 Unbound Local Variables: A Stumbling Block ............................................ 297
17.14.38 repr(object) ............................................................................................................ 320
17.12 Anonymous Functions ......................................................................................................... 299 17.14.39 reversed(sequence) ............................................................................................. 320
17.13 Recursion ................................................................................................................................... 300 17.14.40 round(x, [n]) ........................................................................................................... 321
17.14.41 set([iterable]) ........................................................................................................ 321
17.14 Built-In Functions .................................................................................................................. 300
17.14.42 sorted(iterable, [key, reverse]) ......................................................................... 321
17.14.1 abs(x) ....................................................................................................................... 304
17.14.43 str([object, encoding, errors]) .......................................................................... 322
17.14.2 all(iterable) ............................................................................................................. 304
17.14.44 sum(iterable, [start]) .......................................................................................... 323
17.14.3 any(iterable) .......................................................................................................... 305
17.14.45 tuple([iterable]) .................................................................................................... 323
17.14.4 ascii(object) ............................................................................................................ 305
17.14.46 type(object) ............................................................................................................ 323
17.14.5 bin(x) ........................................................................................................................ 305
17.14.47 zip([*iterables], {strict}) ...................................................................................... 324
17.14.6 bool([x]) ................................................................................................................... 306
17.14.7 bytearray([source, encoding, errors]) ............................................................ 306
17.14.8 bytes([source, encoding, errors]) .................................................................... 307
17.14.9 chr(i) ......................................................................................................................... 307 18 Modules and Packages 325
17.14.10 complex([real, imag]) ......................................................................................... 307
17.14.11 dict([source]) ......................................................................................................... 308
18.1 Importing Global Modules ................................................................................................ 326
17.14.12 divmod(a, b) ........................................................................................................... 309
17.14.13 enumerate(iterable, [start]) ............................................................................. 309 18.2 Local Modules .......................................................................................................................... 328
17.14.14 eval(expression, [globals, locals]) ................................................................... 309 18.2.1 Name Conflicts ..................................................................................................... 329
17.14.15 exec(object, [globals, locals]) ........................................................................... 310 18.2.2 Module-Internal References ............................................................................ 330
17.14.16 filter(function, iterable) ..................................................................................... 310 18.2.3 Executing Modules ............................................................................................. 330
17.14.17 float([x]) .................................................................................................................. 311 18.3 Packages .................................................................................................................................... 331
17.14.18 format(value, [format_spec]) .......................................................................... 311 18.3.1 Importing All Modules of a Package ............................................................. 333
17.14.19 frozenset([iterable]) ............................................................................................ 311 18.3.2 Namespace Packages ......................................................................................... 333
17.14.20 globals() .................................................................................................................. 312 18.3.3 Relative Import Statements ............................................................................. 334
17.14.21 hash(object) ........................................................................................................... 312
18.4 The importlib Package ......................................................................................................... 335
17.14.22 help([object]) ......................................................................................................... 313
18.4.1 Importing Modules and Packages ................................................................. 335
17.14.23 hex(x) ....................................................................................................................... 313
18.4.2 Changing the Import Behavior ........................................................................ 335
17.14.24 id(object) ................................................................................................................. 313
17.14.25 input([prompt]) .................................................................................................... 314 18.5 Planned Language Elements ............................................................................................ 338
17.14.26 int([x, base]) ........................................................................................................... 314

14 15
Contents Contents

19 Object-Oriented Programming 341 19.12.5 Immutable Data Classes ...................................................................................... 396


19.12.6 Default Values in Data Classes .......................................................................... 396

19.1 Example: A Non-Object-Oriented Account ................................................................ 341


19.1.1 Creating a New Account ...................................................................................... 342
19.1.2 Transferring Money ............................................................................................... 342 20 Exception Handling 399
19.1.3 Depositing and Withdrawing Money .............................................................. 343
19.1.4 Viewing the Account Balance ............................................................................ 344
20.1 Exceptions ................................................................................................................................. 399
19.2 Classes ........................................................................................................................................ 346 20.1.1 Built-In Exceptions ................................................................................................. 400
19.2.1 Defining Methods .................................................................................................. 347 20.1.2 Raising an Exception ............................................................................................. 401
19.2.2 The Constructor ...................................................................................................... 348 20.1.3 Handling an Exception ......................................................................................... 401
19.2.3 Attributes .................................................................................................................. 349 20.1.4 Custom Exceptions ................................................................................................ 406
19.2.4 Example: An Object-Oriented Account ........................................................... 349 20.1.5 Re-Raising an Exception ....................................................................................... 408
19.3 Inheritance ............................................................................................................................... 351 20.1.6 Exception Chaining ................................................................................................ 410

19.3.1 A Simple Example ................................................................................................... 352 20.2 Assertions .................................................................................................................................. 411


19.3.2 Overriding Methods .............................................................................................. 353 20.3 Warnings ................................................................................................................................... 412
19.3.3 Example: Checking Account with Daily Turnover ....................................... 355
19.3.4 Outlook ...................................................................................................................... 363
19.4 Multiple Inheritance ............................................................................................................ 363
21 Generators and Iterators 415
19.5 Property Attributes ............................................................................................................... 365
19.5.1 Setters and Getters ................................................................................................ 365
21.1 Generators ................................................................................................................................ 415
19.5.2 Defining Property Attributes .............................................................................. 366
21.1.1 Subgenerators ......................................................................................................... 418
19.6 Static Methods ........................................................................................................................ 367 21.1.2 Generator Expressions .......................................................................................... 421
19.7 Class Methods ......................................................................................................................... 369 21.2 Iterators ..................................................................................................................................... 422
19.8 Class Attributes ...................................................................................................................... 370 21.2.1 The Iterator Protocol ............................................................................................. 422
21.2.2 Example: The Fibonacci Sequence .................................................................... 423
19.9 Built-in Functions for Object-Oriented Programming .......................................... 370
21.2.3 Example: The Golden Ratio ................................................................................. 424
19.9.1 Functions for Managing the Attributes of an Instance ............................. 371
21.2.4 A Generator for the Implementation of __iter__ ....................................... 424
19.9.2 Functions for Information about the Class Hierarchy ............................... 372
21.2.5 Using Iterators ......................................................................................................... 425
19.10 Inheriting Built-In Data Types .......................................................................................... 373 21.2.6 Multiple Iterators for the Same Instance ....................................................... 428
19.11 Magic Methods and Magic Attributes ......................................................................... 375 21.2.7 Disadvantages of Iterators Compared to Direct Access via Indexes ..... 430
19.11.1 General Magic Methods ....................................................................................... 375 21.2.8 Alternative Definition for Iterable Objects .................................................... 430
19.11.2 Overloading Operators ......................................................................................... 382 21.2.9 Function Iterators ................................................................................................... 431
19.11.3 Emulating Data Types: Duck Typing ................................................................ 388 21.3 Special Generators: itertools ............................................................................................ 432
19.12 Data Classes ............................................................................................................................. 393 21.3.1 accumulate(iterable, [func]) ............................................................................... 433
19.12.1 Tuples and Lists ....................................................................................................... 393 21.3.2 chain([*iterables]) ................................................................................................... 433
19.12.2 Dictionaries .............................................................................................................. 394 21.3.3 combinations(iterable, r) ..................................................................................... 434
19.12.3 Named Tuples .......................................................................................................... 394 21.3.4 combinations_with_replacement(iterable, r) .............................................. 434
19.12.4 Mutable Data Classes ........................................................................................... 395 21.3.5 compress(data, selectors) .................................................................................... 435
21.3.6 count([start, step]) ................................................................................................. 435

16 17
Contents Contents

21.3.7 cycle(iterable) .......................................................................................................... 436 23.3.3 Caches ........................................................................................................................ 457


21.3.8 dropwhile(predicate, iterable) ........................................................................... 436 23.3.4 Completing Orderings of Custom Classes ..................................................... 459
21.3.9 filterfalse(predicate, iterable) ............................................................................ 436 23.3.5 Overloading Functions .......................................................................................... 459
21.3.10 groupby(iterable, [key]) ........................................................................................ 437
21.3.11 islice(iterable, [start], stop, [step]) .................................................................... 437
21.3.12 permutations(iterable, [r]) .................................................................................. 438
21.3.13 product([*iterables], [repeat]) ............................................................................ 438
24 Annotations for Static Type Checking 463

21.3.14 repeat(object, [times]) .......................................................................................... 439


21.3.15 starmap(function, iterable) ................................................................................. 439 24.1 Annotations ............................................................................................................................. 464
21.3.16 takewhile(predicate, iterable) ............................................................................ 439 24.1.1 Annotating Functions and Methods ................................................................ 465
21.3.17 tee(iterable, [n]) ...................................................................................................... 439 24.1.2 Annotating Variables and Attributes .............................................................. 466
21.3.18 zip_longest([*iterables], {fillvalue}) .................................................................. 440 24.1.3 Accessing Annotations at Runtime .................................................................. 468
24.1.4 When are Annotations Evaluated? ................................................................... 470
24.2 Type Hints: The typing Module ....................................................................................... 471
24.2.1 Valid Type Hints ...................................................................................................... 472
22 Context Manager 441
24.2.2 Container Types ...................................................................................................... 472
24.2.3 Abstract Container Types .................................................................................... 473
22.1 The with Statement .............................................................................................................. 441
24.2.4 Type Aliases .............................................................................................................. 474
22.1.1 __enter__(self) ........................................................................................................ 443
24.2.5 Type Unions and Optional Values .................................................................... 474
22.1.2 __exit__(self, exc_type, exc_value, traceback) ............................................ 444
24.2.6 Type Variables ......................................................................................................... 475
22.2 Helper Functions for with Contexts: contextlib ...................................................... 444
24.3 Static Type Checking in Python: mypy ......................................................................... 476
22.2.1 Dynamically Assembled Context Combinations - ExitStack ................... 444
24.3.1 Installation ................................................................................................................ 476
22.2.2 Suppressing Certain Exception Types ............................................................. 445
24.3.2 Example ..................................................................................................................... 477
22.2.3 Redirecting the Standard Output Stream ...................................................... 445
22.2.4 Optional Contexts .................................................................................................. 446
22.2.5 Simple Functions as Context Manager ........................................................... 447
25 Structural Pattern Matching 479

25.1 The match Statement .......................................................................................................... 479


23 Decorators 449
25.2 Pattern Types in the case Statement ............................................................................ 480
23.1 Function Decorators ............................................................................................................. 449 25.2.1 Literal and Value Patterns ................................................................................... 481
23.1.1 Decorating Functions and Methods ................................................................ 451 25.2.2 OR Pattern ................................................................................................................. 481
23.1.2 Name and Docstring after Applying a Decorator ........................................ 451 25.2.3 Patterns with Type Checking .............................................................................. 482
23.1.3 Nested Decorators ................................................................................................. 452 25.2.4 Specifying Conditions for Matches .................................................................. 483
23.1.4 Example: A Cache Decorator .............................................................................. 452 25.2.5 Grouping Subpatterns .......................................................................................... 483
25.2.6 Capture and Wildcard Patterns ......................................................................... 484
23.2 Class Decorators ..................................................................................................................... 454
25.2.7 Sequence Patterns ................................................................................................. 486
23.3 The functools Module .......................................................................................................... 455 25.2.8 Mapping Patterns ................................................................................................... 488
23.3.1 Simplifying Function Interfaces ........................................................................ 455 25.2.9 Patterns for Objects and Their Attribute Values .......................................... 490
23.3.2 Simplifying Method Interfaces .......................................................................... 457

18 19
Contents Contents

Part IV The Standard Library 28 Regular Expressions 529

26 Mathematics 497 28.1 Syntax of Regular Expressions ......................................................................................... 529


28.1.1 Any Character .......................................................................................................... 530
26.1 Mathematical Functions: math, cmath ....................................................................... 497 28.1.2 Character Classes ................................................................................................... 530
26.1.1 General Mathematical Functions ..................................................................... 498 28.1.3 Quantifiers ................................................................................................................ 531
26.1.2 Exponential and Logarithm Functions ............................................................ 501 28.1.4 Predefined Character Classes ............................................................................. 533
26.1.3 Trigonometric and Hyperbolic Functions ....................................................... 501 28.1.5 Other Special Characters ..................................................................................... 534
26.1.4 Distances and Norms ............................................................................................ 502 28.1.6 Nongreedy Quantifiers ......................................................................................... 535
26.1.5 Converting Angles .................................................................................................. 502 28.1.7 Groups ........................................................................................................................ 536
26.1.6 Representations of Complex Numbers ........................................................... 502 28.1.8 Alternatives .............................................................................................................. 536
28.1.9 Extensions ................................................................................................................. 537
26.2 Random Number Generator: random .......................................................................... 503
26.2.1 Saving and Loading the Random State ........................................................... 504 28.2 Using the re Module ............................................................................................................. 539
26.2.2 Generating Random Integers ............................................................................. 504 28.2.1 Searching ................................................................................................................... 540
26.2.3 Generating Random Floats ................................................................................. 505 28.2.2 Matching ................................................................................................................... 540
26.2.4 Random Operations on Sequences .................................................................. 505 28.2.3 Splitting a String ..................................................................................................... 541
26.2.5 SystemRandom([seed]) ........................................................................................ 507 28.2.4 Replacing Parts of a String .................................................................................. 541
28.2.5 Replacing Problem Characters ........................................................................... 542
26.3 Statistical Calculations: statistics .................................................................................. 507
28.2.6 Compiling a Regular Expression ........................................................................ 542
26.4 Intuitive Decimal Numbers: decimal ............................................................................ 509 28.2.7 Flags ............................................................................................................................ 543
26.4.1 Using the Data Type .............................................................................................. 509 28.2.8 The Match Object ................................................................................................... 544
26.4.2 Nonnumeric Values ............................................................................................... 512
28.3 A Simple Sample Program: Searching .......................................................................... 546
26.4.3 The Context Object ................................................................................................ 513
28.4 A More Complex Sample Program: Matching .......................................................... 547
26.5 Hash Functions: hashlib ..................................................................................................... 514
26.5.1 Using the Module ................................................................................................... 516 28.5 Comments in Regular Expressions ................................................................................. 550
26.5.2 Other Hash Algorithms ........................................................................................ 517
26.5.3 Comparing Large Files ........................................................................................... 517
26.5.4 Passwords ................................................................................................................. 518
29 Interface to Operating System and
Runtime Environment 553

27 Screen Outputs and Logging 521 29.1 Operating System Functionality: os .............................................................................. 553
29.1.1 environ ....................................................................................................................... 554
27.1 Formatted Output of Complex Objects: pprint ....................................................... 521 29.1.2 getpid() ....................................................................................................................... 554
27.2 Log Files: logging ................................................................................................................... 523 29.1.3 cpu_count() .............................................................................................................. 554
29.1.4 system(cmd) ............................................................................................................. 554
27.2.1 Customizing the Message Format .................................................................... 525
29.1.5 popen(command, [mode, buffering]) .............................................................. 555
27.2.2 Logging Handlers .................................................................................................... 527
29.2 Accessing the Runtime Environment: sys .................................................................. 555
29.2.1 Command Line Parameters ................................................................................. 556
29.2.2 Default Paths ........................................................................................................... 556
29.2.3 Standard Input/Output Streams ....................................................................... 556

20 21
Contents Contents

29.2.4 Exiting the Program ............................................................................................... 556 31 Parallel Programming 587


29.2.5 Details of the Python Version ............................................................................. 557
29.2.6 Operating System Details .................................................................................... 557
31.1 Processes, Multitasking, and Threads .......................................................................... 587
29.2.7 Hooks .......................................................................................................................... 559
31.1.1 The Lightweights among the Processes: Threads ....................................... 588
29.3 Command Line Parameters: argparse .......................................................................... 561 31.1.2 Threads or Processes? ........................................................................................... 590
29.3.1 Calculator: A Simple Example ............................................................................ 562 31.1.3 Cooperative Multitasking: A Third Way .......................................................... 590
29.3.2 A More Complex Example ................................................................................... 566
31.2 Python's Interfaces for Parallelization ......................................................................... 591

31.3 The Abstract Interface: [Link] ............................................................... 592


31.3.1 An Example with a [Link] ......................................... 593
30 File System 569 31.3.2 Executor Instances as Context Managers ...................................................... 595
31.3.3 Using [Link] .................................................................. 595
30.1 Accessing the File System: os ........................................................................................... 569 31.3.4 Managing the Tasks of an Executor ................................................................. 596
30.1.1 access(path, mode) ................................................................................................ 570 31.4 The Flexible Interface: threading and multiprocessing ....................................... 602
30.1.2 chmod(path, mode) ............................................................................................... 571 31.4.1 Threads in Python: threading ............................................................................. 603
30.1.3 listdir([path]) ............................................................................................................ 571 31.4.2 Processes in Python: multiprocessing ............................................................. 611
30.1.4 mkdir(path, [mode]) and makedirs(path, [mode]) ...................................... 572
31.5 Cooperative Multitasking .................................................................................................. 613
30.1.5 remove(path) ........................................................................................................... 572
30.1.6 removedirs(path) .................................................................................................... 572 31.5.1 Cooperative Functions: Coroutines .................................................................. 613
30.1.7 rename(src, dst) and renames(old, new) ........................................................ 573 31.5.2 Awaitable Objects .................................................................................................. 614
30.1.8 walk(top, [topdown, onerror]) ............................................................................ 573 31.5.3 The Cooperation of Coroutines: Tasks ............................................................ 615
31.5.4 A Cooperative Web Crawler ................................................................................ 618
30.2 File Paths: [Link] ................................................................................................................. 575
31.5.5 Blocking Operations in Coroutines ................................................................... 625
30.2.1 abspath(path) .......................................................................................................... 576 31.5.6 Other Asynchronous Language Features ....................................................... 627
30.2.2 basename(path) ...................................................................................................... 577
31.6 Conclusion: Which Interface Is the Right One? ........................................................ 629
30.2.3 commonprefix(list) ................................................................................................ 577
30.2.4 dirname(path) ......................................................................................................... 577 31.6.1 Is Cooperative Multitasking an Option? ......................................................... 629
30.2.5 join(path, *paths) .................................................................................................... 578 31.6.2 Abstraction or Flexibility? .................................................................................... 630
30.2.6 normcase(path) ....................................................................................................... 578 31.6.3 Threads or Processes? ........................................................................................... 630
30.2.7 split(path) .................................................................................................................. 578
30.2.8 splitdrive(path) ........................................................................................................ 579
30.2.9 splitext(path) ........................................................................................................... 579 32 Data Storage 631
30.3 Accessing the File System: shutil .................................................................................... 579
30.3.1 Directory and File Operations ............................................................................ 581 32.1 XML .............................................................................................................................................. 631
30.3.2 Archive Operations ................................................................................................ 582 32.1.1 ElementTree ............................................................................................................. 633
30.4 Temporary Files: tempfile .................................................................................................. 585 32.1.2 Simple API for XML ................................................................................................. 640
30.4.1 TemporaryFile([mode, [bufsize, suffix, prefix, dir]) ..................................... 585 32.2 Databases .................................................................................................................................. 643
30.4.2 [Link]([suffix, prefix, dir]) ...................................... 586 32.2.1 The Built-In Database in Python: sqlite3 ........................................................ 646
32.3 Compressed Files and Archives ....................................................................................... 661
32.3.1 [Link](filename, [mode, compresslevel]) ................................................ 661
32.3.2 Other Modules for Accessing Compressed Data ......................................... 662

22 23
Contents Contents

32.4 Serializing Instances: pickle .............................................................................................. 662 34.3 The Easy Way: requests ...................................................................................................... 703
32.4.1 Functional Interface .............................................................................................. 663 34.3.1 Simple Requests via GET and POST .................................................................. 703
32.4.2 Object-Oriented Interface ................................................................................... 665 34.3.2 Web APIs .................................................................................................................... 704
32.5 The JSON Data Exchange Format: json ........................................................................ 665 34.4 URLs: urllib ................................................................................................................................ 705

32.6 The CSV Table Format: csv ................................................................................................. 667 34.4.1 Accessing Remote Resources: [Link] ................................................. 706
34.4.2 Reading and Processing URLs: [Link] .................................................... 710
32.6.1 Reading Data from a CSV File with reader Objects ..................................... 668
32.6.2 Using Custom Dialects: Dialect Objects ......................................................... 670 34.5 FTP: ftplib .................................................................................................................................. 713
34.5.1 Connecting to an FTP Server ............................................................................... 714
34.5.2 Executing FTP commands ................................................................................... 715
34.5.3 Working with Files and Directories .................................................................. 715
33 Network Communication 673
34.5.4 Transferring Files .................................................................................................... 716

33.1 Socket API ................................................................................................................................. 674


33.1.1 Client-Server Systems ........................................................................................... 675
33.1.2 UDP ............................................................................................................................. 677 35 Email 721
33.1.3 TCP ............................................................................................................................... 678
33.1.4 Blocking and Nonblocking Sockets ................................................................... 680 35.1 SMTP: smtplib ......................................................................................................................... 721
33.1.5 Creating a Socket .................................................................................................... 681 35.1.1 SMTP([host, port, local_hostname, timeout, source_address]) ............. 722
33.1.6 The Socket Class ...................................................................................................... 682 35.1.2 Establishing and Terminating a Connection ................................................. 722
33.1.7 Network Byte Order ............................................................................................... 685 35.1.3 Sending an Email .................................................................................................... 723
33.1.8 Multiplexing Servers: selectors ......................................................................... 686 35.1.4 Example ..................................................................................................................... 724
33.1.9 Object-Oriented Server Development: socketserver .................................. 688
35.2 POP3: poplib ............................................................................................................................ 724
33.2 XML-RPC .................................................................................................................................... 690 35.2.1 POP3(host, [port, timeout]) ................................................................................. 725
33.2.1 The Server ................................................................................................................. 691 35.2.2 Establishing and Terminating a Connection ................................................. 725
33.2.2 The Client .................................................................................................................. 694 35.2.3 Listing Existing Emails .......................................................................................... 726
33.2.3 Multicall ..................................................................................................................... 696 35.2.4 Retrieving and Deleting Emails ......................................................................... 727
33.2.4 Limitations ................................................................................................................ 697 35.2.5 Example ..................................................................................................................... 727
35.3 IMAP4: imaplib ....................................................................................................................... 728
35.3.1 IMAP4([host, port, timeout]) .............................................................................. 729
34 Accessing Resources on the Internet 701 35.3.2 Establishing and Terminating a Connection ................................................. 730
35.3.3 Finding and Selecting a Mailbox ....................................................................... 730
35.3.4 Operations with Mailboxes ................................................................................ 731
34.1 Protocols .................................................................................................................................... 701
35.3.5 Searching Emails ..................................................................................................... 731
34.1.1 Hypertext Transfer Protocol ............................................................................... 701
35.3.6 Retrieving Emails .................................................................................................... 732
34.1.2 File Transfer Protocol ............................................................................................ 701
35.3.7 Example ..................................................................................................................... 733
34.2 Solutions .................................................................................................................................... 702
35.4 Creating Complex Emails: email ..................................................................................... 734
34.2.1 Outdated Solutions for Python 2 ...................................................................... 702
35.4.1 Creating a Simple Email ....................................................................................... 734
34.2.2 Solutions in the Standard Library ..................................................................... 702
35.4.2 Creating an Email with Attachments .............................................................. 735
34.2.3 Third-Party Solutions ............................................................................................ 702
35.4.3 Reading an Email .................................................................................................... 737

24 25
Contents Contents

36 Debugging and Quality Assurance 739 38.4 Package Manager .................................................................................................................. 776
38.4.1 The Python Package Manager: pip ................................................................... 777
38.4.2 The conda Package Manager .............................................................................. 778
36.1 The Debugger .......................................................................................................................... 739
38.5 Localizing Programs: gettext ........................................................................................... 781
36.2 Automated Testing ............................................................................................................... 741
38.5.1 Example of Using gettext .................................................................................... 781
36.2.1 Test Cases in Docstrings: doctest ..................................................................... 742
38.5.2 Creating the Language Compilation ................................................................ 783
36.2.2 Unit Tests: unittest ................................................................................................ 746
36.3 Analyzing the Runtime Performance ........................................................................... 749
36.3.1 Runtime Measurement: timeit .......................................................................... 749
36.3.2 Profiling: cProfile .................................................................................................... 752 39 Virtual Environments 785
36.3.3 Tracing: trace ........................................................................................................... 756
39.1 Using Virtual Environments: venv ................................................................................. 786
39.1.1 Activating a Virtual Environment ..................................................................... 786
39.1.2 Working in a Virtual Environment .................................................................... 786
37 Documentation 759
39.1.3 Deactivating a Virtual Environment ................................................................ 787
39.2 Virtual Environments in Anaconda ............................................................................... 787
37.1 Docstrings ................................................................................................................................. 759

37.2 Automatically Generated Documentation: pydoc ................................................. 761

40 Alternative Interpreters and Compilers 789

Part V Advanced Topics 40.1 Just-in-Time Compilation: PyPy ...................................................................................... 789


40.1.1 Installation and Use ............................................................................................... 789
38 Distributing Python Projects 765 40.1.2 Example ..................................................................................................................... 790
40.2 Numba ........................................................................................................................................ 790
38.1 A History of Distributions in Python ............................................................................. 765
40.2.1 Installation ................................................................................................................ 791
38.1.1 The Classic Approach: distutils .......................................................................... 766
40.2.2 Example ..................................................................................................................... 791
38.1.2 The New Standard: setuptools .......................................................................... 766
38.1.3 The Package Index: PyPI ....................................................................................... 766 40.3 Connecting to C and C++: Cython .................................................................................. 793
40.3.1 Installation ................................................................................................................ 793
38.2 Creating Distributions: setuptools ................................................................................ 767
40.3.2 The Functionality of Cython ............................................................................... 794
38.2.1 Installation ................................................................................................................ 767
40.3.3 Compiling a Cython Program ............................................................................. 794
38.2.2 Writing the Module ............................................................................................... 767
40.3.4 A Cython Program with Static Typing ............................................................. 796
38.2.3 The Installation Script ........................................................................................... 768
40.3.5 Using a C Library ..................................................................................................... 797
38.2.4 Creating a Source Distribution .......................................................................... 773
38.2.5 Creating a Binary Distribution ........................................................................... 773 40.4 The Interactive Python Shell: IPython .......................................................................... 799
38.2.6 Installing Distributions ......................................................................................... 774 40.4.1 Installation ................................................................................................................ 799
40.4.2 The Interactive Shell .............................................................................................. 799
38.3 Creating EXE files: cx_Freeze ........................................................................................... 775
40.4.3 The Jupyter Notebook ........................................................................................... 802
38.3.1 Installation ................................................................................................................ 775
38.3.2 Usage .......................................................................................................................... 775

26 27
Contents Contents

41 Graphical User Interfaces 805 41.7 Model-View Architecture ................................................................................................... 879


41.7.1 Sample Project: An Address Book ..................................................................... 880
41.7.2 Selecting Entries ..................................................................................................... 888
41.1 Toolkits ....................................................................................................................................... 805
41.7.3 Editing Entries ......................................................................................................... 890
41.1.1 Tkinter (Tk) ................................................................................................................ 805
41.1.2 PyGObject (GTK) ...................................................................................................... 806
41.1.3 Qt for Python (Qt) ................................................................................................... 806
41.1.4 wxPython (wxWidgets) ........................................................................................ 807 42 Python as a Server-Side Programming Language
41.2 Introduction to tkinter ........................................................................................................ 807 on the Web: An Introduction to Django 893
41.2.1 A Simple Example ................................................................................................... 807
41.2.2 Control Variables .................................................................................................... 810 42.1 Concepts and Features of Django .................................................................................. 894
41.2.3 The Packer ................................................................................................................. 811
42.2 Installing Django .................................................................................................................... 895
41.2.4 Events ......................................................................................................................... 815
41.2.5 Widgets ...................................................................................................................... 821 42.3 Creating a New Django Project ....................................................................................... 896
41.2.6 Drawings: The Canvas Widget ........................................................................... 839 42.3.1 The Development Web Server ........................................................................... 897
41.2.7 Other Modules ........................................................................................................ 846 42.3.2 Configuring the Project ........................................................................................ 898
41.3 Introduction to PySide6 ...................................................................................................... 850 42.4 Creating an Application ...................................................................................................... 900
41.3.1 Installation ................................................................................................................ 850 42.4.1 Importing the Application into the Project .................................................... 901
41.3.2 Basic Concepts of Qt .............................................................................................. 850 42.4.2 Defining a Model .................................................................................................... 901
41.3.3 Development Process ............................................................................................ 852 42.4.3 Relationships between Models ......................................................................... 902
41.4 Signals and Slots .................................................................................................................... 859 42.4.4 Transferring the Model to the Database ........................................................ 903
42.4.5 The Model API .......................................................................................................... 904
41.5 Important Widgets ............................................................................................................... 861
42.4.6 The Project Gets a Face ......................................................................................... 909
41.5.1 QCheckBox ................................................................................................................ 862 42.4.7 Django's Template System .................................................................................. 915
41.5.2 QComboBox ............................................................................................................. 862 42.4.8 Processing Form Data ........................................................................................... 926
41.5.3 QDateEdit, QTimeEdit, and QDateTimeEdit .................................................. 863 42.4.9 Django’s Admin Control Panel ........................................................................... 930
41.5.4 QDialog ...................................................................................................................... 863
41.5.5 QLineEdit ................................................................................................................... 864
41.5.6 QListWidget and QListView ................................................................................ 864
41.5.7 QProgressBar ............................................................................................................ 865 43 Scientific Computing and Data Science 935
41.5.8 QPushButton ............................................................................................................ 865
41.5.9 QRadioButton .......................................................................................................... 865 43.1 Installation ............................................................................................................................... 936
41.5.10 QSlider and QDial ................................................................................................... 866
43.2 The Model Program .............................................................................................................. 936
41.5.11 QTextEdit .................................................................................................................. 866
43.2.1 Importing numpy, scipy, and matplotlib ........................................................ 937
41.5.12 QWidget .................................................................................................................... 867
43.2.2 Vectorization and the [Link] Data Type ....................................... 938
41.6 Drawing Functionality ......................................................................................................... 868 43.2.3 Visualizing Data Using [Link] ...................................................... 942
41.6.1 Tools ............................................................................................................................ 868
43.3 Overview of the numpy and scipy Modules .............................................................. 944
41.6.2 Coordinate System ................................................................................................. 870
43.3.1 Overview of the [Link] Data Type .................................................. 944
41.6.3 Simple Shapes ......................................................................................................... 871
43.3.2 Overview of scipy .................................................................................................... 952
41.6.4 Images ........................................................................................................................ 873
41.6.5 Text ............................................................................................................................. 874 43.4 An Introduction to Data Analysis with pandas ........................................................ 953
41.6.6 Eye Candy .................................................................................................................. 876 43.4.1 The DataFrame Object .......................................................................................... 954

28 29
Contents Contents

43.4.2 Selective Data Access ............................................................................................ 955 45.1.5 Exception Handling ............................................................................................... 999
43.4.3 Deleting Rows and Columns .............................................................................. 961 45.1.6 Standard Library ...................................................................................................... 1000
43.4.4 Inserting Rows and Columns .............................................................................. 961 45.2 Automatic Conversion ......................................................................................................... 1001
43.4.5 Logical Expressions on Data Records ............................................................... 962
43.4.6 Manipulating Data Records ................................................................................ 963
43.4.7 Input and Output ................................................................................................... 965
43.4.8 Visualization ............................................................................................................ 966 Appendices 1005

A Appendix ................................................................................................................................... 1005

44 Inside Knowledge 969 B The Authors .............................................................................................................................. 1017

44.1 Opening URLs in the Default Browser: webbrowser ............................................. 969


44.2 Interpreting Binary Data: struct ..................................................................................... 969 Index .......................................................................................................................................................... 1019

44.3 Hidden Password Entry ....................................................................................................... 971


44.3.1 getpass([prompt, stream]) .................................................................................. 971
44.3.2 [Link]() .................................................................................................... 972
44.4 Command Line Interpreter ................................................................................................ 972

44.5 File Interface for Strings: [Link] ............................................................................ 975

44.6 Generators as Consumers .................................................................................................. 976


44.6.1 A Decorator for Consuming Generator Functions ...................................... 978
44.6.2 Triggering Exceptions in a Generator .............................................................. 978
44.6.3 A Pipeline as a Chain of Consuming Generator Functions ....................... 979
44.7 Copying Instances: copy ..................................................................................................... 981

44.8 Image Processing: Pillow ................................................................................................... 984


44.8.1 Installation ................................................................................................................ 984
44.8.2 Loading and Saving Image Files ......................................................................... 984
44.8.3 Accessing Individual Pixels .................................................................................. 985
44.8.4 Manipulating Images ............................................................................................ 986
44.8.5 Interoperability ....................................................................................................... 992

45 From Python 2 to Python 3 993

45.1 The Main Differences ........................................................................................................... 996


45.1.1 Input/Output ........................................................................................................... 996
45.1.2 Iterators ..................................................................................................................... 997
45.1.3 Strings ........................................................................................................................ 998
45.1.4 Integers ...................................................................................................................... 999

30 31
Index

- ................................................................. 234, 386, 387 __invert__ ............................................................... 388


^ ...................................................... 139, 234, 386, 387 __ior__ ..................................................................... 388
_ ............................................................................ 54, 485 __ipow__ ................................................................. 388
__abs__ ..................................................................... 388 __irshift__ ............................................................... 388
__add__ .......................................................... 386, 391 __isub__ ................................................................... 388
__aenter__ ............................................................... 628 __iter__ ........................................................... 391, 422
__aexit__ ................................................................. 628 __itruediv__ ........................................................... 388
__aiter__ .................................................................. 628 __ixor__ ................................................................... 388
__and__ .................................................................... 386 __le__ ........................................................................ 385
__anext__ ................................................................ 628 __len__ ..................................................................... 390
__annotations__ ................................................... 469 __lshift__ ................................................................. 386
__bool__ ................................................................... 376 __lt__ ........................................................................ 385
__builtins__ ............................................................ 330 __main__ ................................................................ 330
__bytes__ ................................................................. 376 __match_args__ ................................................... 492
__call__ .................................................. 376, 378, 453 __matmul__ ........................................................... 386
__complex__ ................................................ 376, 389 __mod__ .................................................................. 386
__contains__ .......................................................... 391 __mul__ .......................................................... 386, 391
__debug__ ............................................................... 412 __name__ ................................................................ 330
__del__ ............................................................ 376, 377 __ne__ ...................................................................... 385
__delattr__ .............................................................. 379 __neg__ .................................................................... 388
__delitem__ ............................................................ 390 __next__ .................................................................. 422
__dict__ .................................................................... 379 __or__ ....................................................................... 386
__divmod__ ............................................................ 386 __pos__ .................................................................... 388
__doc__ .................................................................... 760 __pow__ ................................................................... 386
__enter__ .............................................. 390, 443, 627 __radd__ ......................................................... 387, 391
__eq__ ....................................................................... 385 __rand__ .................................................................. 387
__exit__ ................................................. 390, 443, 627 __rdivmod__ ......................................................... 387
__file__ ..................................................................... 330 __repr__ ................................................................... 376
__float__ ........................................................ 376, 389 __rfloordiv__ ......................................................... 387
__floordiv__ ........................................................... 386 __rlshift__ ............................................................... 387
__future__ ............................................................... 338 __rmatmul__ ......................................................... 387
__ge__ ....................................................................... 385 __rmod__ ................................................................ 387
__getattr__ .............................................................. 379 __rmul__ ........................................................ 387, 391
__getattribute__ ......................................... 379, 380 __ror__ ..................................................................... 387
__getitem__ ............................................................ 390 __round__ ...................................................... 376, 389
__gt__ ........................................................................ 385 __rpow__ ................................................................. 387
__hash__ ........................................................ 376, 378 __rrshift__ .............................................................. 387
__iadd__ ......................................................... 388, 391 __rshift__ ................................................................ 386
__iand__ ................................................................... 388 __rsub__ .................................................................. 387
__ifloordiv__ .......................................................... 388 __rtruediv__ .......................................................... 387
__ilshift__ ................................................................ 388 __rxor__ .................................................................. 387
__imatmul__ .......................................................... 388 __setattr__ ..................................................... 379, 380
__imod__ ................................................................. 388 __setitem__ ............................................................ 390
__imul__ ........................................................ 388, 391 __slots__ ......................................................... 379, 381
__index__ ................................................................ 376 __sub__ .................................................................... 386
__init__ ..................................................................... 376 __truediv__ ............................................................ 386
__init__.py ........................................... 331, 333, 767 __xor__ .................................................................... 386
__int__ ...................................................................... 389 := .................................................................. 87, 117, 491

1019
Index Index

... ................................................................................... 487 Archive (Cont.) Basic data type (Cont.) Built-in function (Cont.)
() ................................................................................... 487 XZ ............................................................................ 584 float ................................................................ 51, 141 enumerate .......................................................... 309
[...] ................................................................................ 117 ZIP ................................................................. 579, 584 frozenset ........................................... 215, 227, 237 eval ........................................................................ 309
[] ......................................................................... 117, 486 Arcsine ....................................................................... 501 int .................................................................... 49, 135 exec ....................................................................... 310
{...} ................................................................................ 117 Arctangent ............................................................... 501 list .................................................................... 52, 166 filter .............................................................. 178, 310
{} ......................................................................... 117, 488 argparse ..................................................................... 561 NoneType ............................................................ 126 float ....................................................................... 311
@ .................................................... 384, 386, 387, 938 Argument ....................................................... 116, 278 set ........................................................ 215, 227, 236 format .................................................................. 311
* ................................................................. 288, 386, 387 keyword ...................................................... 116, 283 str ..................................................................... 51, 182 frozenset .............................................................. 311
** ...................................................... 132, 289, 386, 387 keyword-only ..................................................... 117 tuple ...................................................................... 179 getattr .................................................................. 370
/ .......................................................................... 386, 387 optional ................................................................ 117 Batteries included .................................................... 35 globals .................................................................. 312
// ........................................................ 50, 132, 386, 387 positional ................................................... 116, 283 Bezier curve (Qt) .................................................... 878 hasattr ................................................................. 370
\ ............................................................................... 68, 69 Argument (command) ........................................ 561 Big endian ................................................................ 559 hash ....................................................................... 312
\u ................................................................................. 211 Arithmetic expression ........................................ 127 bin ............................................................................... 305 help ............................................................... 119, 313
\x ................................................................................. 209 Arithmetic mean ................................................... 508 Binary distribution .................................... 765, 773 hex ......................................................................... 313
& ..................................................... 137, 233, 386, 387 Arithmetic operator ............................................. 131 Binary operator ..................................................... 386 id .................................................................... 108, 313
% ..................................................... 132, 198, 386, 387 as .............................................................. 327, 404, 484 Binary system ......................................................... 136 input ..................................................................... 314
+ ......................................................................... 386, 387 ASCII ....................................................... 195, 208, 212 Bit operator ............................................................. 137 int ........................................................................... 314
< ................................................................................... 232 ascii (function) ........................................................ 305 bit shift ................................................................. 140 isinstance ............................................................ 371
<< ....................................................................... 386, 387 ASGI ............................................................................ 897 bitwise AND ........................................................ 137 issubclass ............................................................ 371
> ................................................................................... 232 assert .......................................................................... 411 bitwise complement ........................................ 139 iter ......................................................................... 422
>> ....................................................................... 386, 387 Assignment ................................................................ 54 bitwise exclusive OR ....................................... 139 len .............................................. 164, 219, 232, 315
| ............................................... 138, 221, 232, 386, 387 augmented ................................................ 132, 387 bitwise OR ........................................................... 138 list .......................................................................... 315
~ ................................................................................... 139 Assignment expression ........................................ 87 Bitmap ....................................................................... 101 locals ..................................................................... 315
$ ............................................................................. 43, 944 async .............................................. 592, 614, 619, 627 Block comment ........................................................ 72 map .............................................................. 178, 316
2to3 .......................................................................... 1001 async def ................................................................... 614 Bodiless tag (XML) ................................................ 632 max .................................................... 115, 164, 317
async for .......................................................... 628, 629 bool .......................................................... 144, 146, 306 min ............................................................... 164, 318
A async with ...................................................... 619, 627 Boolean expression ...................................... 55, 144 oct .......................................................................... 318
Asynchronous comprehension ....................... 629 Boolean operator ..................................................... 57 open ........................................................ 92, 97, 625
ABC ............................................................................. 473 Asynchronous generator ................................... 628 Boolean value ......................................................... 144 ord ................................................................ 212, 318
ABC (programming language) ............................ 39 Asynchronous iterator ........................................ 628 break ............................................................................. 80 pow ........................................................................ 318
abs ............................................................................... 304 asyncio ............................................................. 592, 629 Breakpoint ............................................................... 740 print ............................................................... 59, 318
Abstract base class ................................................ 473 Attribute ...................................... 118, 345, 349, 632 breakpoint (function) .......................................... 301 property ............................................................... 366
Access, random ...................................................... 633 class attribute .................................................... 369 Brush (Qt) ................................................................. 870 range ..................................................... 85, 277, 319
Admin control panel ........................................... 930 magic attribute ................................................. 375 Bubble sort .............................................................. 794 repr ........................................................................ 320
aiofiles ....................................................................... 618 property attribute ............................................ 366 Bug .............................................................................. 739 reversed ............................................................... 320
aiohttp ....................................................................... 618 Augmented assignment ........................... 132, 387 Built-in exceptions ............................................... 400 round .................................................................... 321
all ................................................................................. 304 Automated testing ................................................ 741 Built-in function ....................... 58, 115, 300, 1007 set ........................................................................... 321
Alpha blending ...................................................... 877 Average ...................................................................... 508 abs .......................................................................... 304 setattr ................................................................... 370
Anaconda .................................................................... 42 await ................................................................. 592, 614 all ............................................................................ 304 sorted .................................................................... 321
Anaconda Navigator ............................................ 787 Awaitable object .................................................... 614 any ......................................................................... 305 staticmethod ............................................ 368, 450
Anaconda PowerShell ............................................ 43 ascii ........................................................................ 305 str ........................................................................... 322
Anaconda Prompt ................................................... 43 B bin .......................................................................... 305 sum ........................................................................ 323
and ................................................................................. 56 bool .............................................................. 146, 306 tuple ...................................................................... 323
Annotation .................................................... 463, 464 Backslash .................................................................... 68 breakpoint .......................................................... 301 type ..................................................... 106, 125, 323
Anonymous function ......................................... 299 Base class .................................................................. 351 bytearray ............................................................. 306 zip .......................................................................... 324
Antialiasing (Qt) .................................................... 878 BaseException ........................................................ 400 bytes ...................................................................... 307 Built-in module ..................................................... 325
any .............................................................................. 305 Basic data type chr ................................................................ 212, 307 Busy waiting ........................................................... 686
API ............................................................................... 704 bool ........................................................................ 144 classmethod ....................................................... 369 Button (tkinter) ..................................................... 823
Arccosine .................................................................. 501 bytearray ............................................................. 182 complex ............................................................... 307 Byte code ............................................................. 40, 65
Archive ...................................................................... 579 bytes ....................................................................... 182 delattr ................................................................... 370 Byte order ................................................................ 685
BZ2 .......................................................................... 584 complex ................................................................ 149 dict ......................................................................... 308 bytearray ......................................................... 182, 306
TAR ............................................................... 579, 584 dict ............................................... 53, 215, 241, 242 divmod ................................................................. 309

1020 1021
Index Index

bytes ................................................................. 182, 307 collections (Cont.) Convex polygon .................................................... 844 Decorator ................................................................. 449
BZ2 .............................................................................. 584 namedtuple ......................................................... 245 Cooperative multitasking .............. 591, 613, 629 nested ................................................................... 452
Column index ............................................... 955, 956 Coordinate system (Qt) ...................................... 870 of a class .............................................................. 454
C Combination ........................................................... 434 Coordinate system (tkinter) ............................. 839 of a function ............................................. 449, 451
Combobox (Qt) ....................................................... 862 Coordinated Universal Time (UTC) ..... 248, 264 of a method ........................................................ 451
C/C++ ............................................................... 790, 793 Command line interpreter ................................ 972 copy ............................................................................ 981 def ...................................................................... 279, 614
Cache .......................................................................... 452 Command line parameters ..................... 556, 561 Coroutine ................................................................. 613 Default path ............................................................ 556
Cache (for function) ............................................. 457 Command prompt ................................. 43, 63, 561 Cosine ........................................................................ 501 defaultdict ............................................................... 242
Call by Reference ................................................... 290 Comment ................................................................... 72 Counter ........................................................... 241, 242 del ............................................................ 110, 168, 220
Call by Sharing ....................................................... 291 Communication socket ...................................... 676 Counting loop ........................................................... 85 delattr ........................................................................ 370
Call by Value ........................................................... 290 Comparison ............................................................... 55 Coverage analysis ................................................. 756 Delegate (Qt) ........................................................... 883
Callstack .................................................................... 408 Comparison operator ................................ 133, 384 cProfile ...................................................................... 752 DeprecationWarning .......................................... 412
Canvas (tkinter) ..................................................... 839 Compiler .................................................... 40, 65, 793 CPU ............................................................................. 554 deque (data type) .................................................. 244
Capture pattern ..................................................... 484 just-in-time ............................................................ 66 CPython ................................ 66, 590, 601, 789, 798 Deserialize ............................................................... 662
Cartesian coordinates ............................... 502, 503 Complement ........................................................... 139 Critical Section ............................................. 605, 690 Development environment (IDE) ......... 45, 1014
Cartesian product ................................................. 438 complex .......................................................... 149, 307 CSV .................................................................... 667, 966 Development web server (Django) ................ 897
case ............................................................................. 480 Complex number ........................................ 149, 502 dialect ................................................................... 668 Dialog (Qt) ...................................................... 858, 863
Case-sensitive ............................................................ 55 conjugated .......................................................... 150 CUDA ......................................................................... 790 modal ................................................................... 863
cdef ................................................................... 796, 798 imaginary part .................................................. 149 cx_Freeze ................................................................. 775 nonmodal ........................................................... 863
ChainMap (dictionarys) ...................................... 239 real part ................................................................ 149 Cython ....................................................................... 793 dict .............................................................. 53, 215, 308
Character class ............................................. 530, 533 Complex plane ....................................................... 502 Dict comprehension .................................. 216, 227
Character literal ..................................................... 529 Comprehension D Dictionary ..................................... 53, 215, 241, 242
Character set ........................................................... 208 asynchronous ..................................................... 629 chained ................................................................ 239
Character string ........................................................ 51 dict ................................................................ 216, 227 Data class ........................................................ 393, 455 Difference set ......................................................... 234
Checkbox (Qt) ......................................................... 862 generator expression ...................................... 421 Data science ............................................................ 953 symmetric ........................................................... 234
Checkbutton (tkinter) ......................................... 824 list ........................................................................... 177 Data stream ................................................................ 91 Distribution ............................................................ 765
Children (DOM) ..................................................... 634 Concatenation (of sequences) .......................... 157 Data type ........................................................ 106, 125 distutils ............................................................ 766, 767
chr ..................................................................... 212, 307 [Link] ..................................... 591, 630 container ............................................................. 239 divmod .................................................. 309, 386, 387
cimport ..................................................................... 797 Conditional ...................................................... 75, 479 conversion ........................................................... 134 Django ....................................................................... 894
Class .................................................................. 346, 347 Conditional expression ........................................ 78 immutable ................................................ 111, 181 application ................................................ 894, 900
attribute ............................................................... 349 Connection object ................................................. 684 mapping .............................................................. 215 field lookup ........................................................ 908
base class ............................................................. 351 Connection socket ................................................ 675 mutable ................................................................ 111 migration ............................................................ 903
constructor ......................................................... 348 Console ...................................................................... 561 numeric ................................................................ 131 path ....................................................................... 911
data class ............................................................. 393 Console application ................................................ 63 sequential ............................................................ 153 project .................................................................. 894
instance ................................................................ 346 Constructor .............................................................. 348 set ........................................................................... 215 view ....................................................................... 910
method ................................................................. 347 factory function ................................................ 368 Database ................................................................... 643 Docstring ........................................................ 742, 759
Class attribute ........................................................ 369 Consumer (generator) ......................................... 976 cursor .................................................................... 647 doctest ...................................................................... 742
Class decorator ....................................................... 454 Consumer (queue) ................................................ 620 join ......................................................................... 653 Document Object Model (XML) 씮 DOM (XML)
Class method .......................................................... 369 Container ........................................................ 239, 390 query ..................................................................... 644 Documentation ............................................ 119, 759
classmethod (function) ...................................... 369 Context manager ........................................ 389, 442 transaction ......................................................... 649 Dollar sign ........................................................ 43, 944
Client ................................................................ 675, 677 asynchronous ........................................... 619, 627 Date ............................................................................ 247 DOM (XML) ............................................................. 633
Client-server system ............................................ 675 Context object ........................................................ 441 Date edit (Qt) .......................................................... 863 child ....................................................................... 634
cmath ......................................................................... 497 contextlib ................................................................. 444 datetime ................................................................... 254 children ................................................................ 634
cmd ............................................................................. 972 continue ...................................................................... 82 Daylight Saving Time (DST) .............................. 265 node ...................................................................... 633
Code point ............................................................... 210 Control (GUI) ........................................................... 805 Deadlock ................................................................... 610 Root ....................................................................... 634
Codepage .................................................................. 208 Control character .................................................. 185 Debugging ............................................................... 739 siblings ................................................................. 634
coding (file header) .............................................. 214 Control structure ..................................................... 75 breakpoint .......................................................... 740 double ....................................................................... 142
collections ................................................................ 239 conditional ............................................................ 75 post mortem ...................................................... 741 Drawing (Qt) ........................................................... 868
ChainMap ............................................................ 239 conditional expression ..................................... 78 decimal (module) .................................................. 509 Drawing (tkinter) .................................................. 839
counter ....................................................... 241, 242 loop .......................................................................... 79 Decimal system ..................................................... 135 DRY principle (Django) ....................................... 895
defaultdict ........................................................... 242 structural pattern matching ........................ 479 decode ....................................................................... 209 Dual system ................................................... 136, 137
deque ..................................................................... 244 Control variable (tkinter) ................................... 810 Duck typing ......................................... 388, 463, 794

1022 1023
Index Index

E F Function (Cont.) GUI ............................................................................. 805


local ....................................................................... 295 drawing (Qt) ...................................................... 868
Egg ............................................................................... 766 Factorial ....................................................................... 83 name ..................................................................... 279 drawing (tkinter) .............................................. 839
ElementTree (XML) .............................................. 633 Factory function .................................................... 368 namespace .......................................................... 293 layout (Qt) .......................................................... 851
elif .................................................................................. 76 False .................................................................... 55, 144 optional parameter ......................................... 282 layout (tkinter) ................................................. 811
Ellipsis ....................................................................... 487 Fibonacci sequence .............................................. 423 overloading ........................................................ 459 modal dialog ..................................................... 863
else ......................................................... 77, 79, 81, 404 Field lookup (Django) .......................................... 908 parameter ........................................................... 278 non-modal dialog ............................................ 863
Email .......................................................................... 721 File ................................................................................. 92 positional-only parameter ........................... 287 Qt (Toolkit) ......................................................... 850
header ................................................................... 734 temporary ............................................................ 585 recursive ............................................................... 300 Tkinter (toolkit) ................................................ 805
email (module) ....................................................... 734 File access rights .................................................... 571 return value .............................................. 278, 279 gzip ............................................................................. 661
Emoji .......................................................................... 211 File descriptor ........................................................... 99 trigonometric .................................................... 501
encode ....................................................................... 209 File dialog (tkinter) ............................................... 847 Function annotations ............................... 463, 465 H
Encoding ...................................................................... 98 File object .................................................. 92, 99, 707 Function call .................................................... 57, 278
Encoding declaration .......................................... 214 File path ..................................................................... 575 Function decorator .................................... 449, 451 Harmonic mean .................................................... 508
End of file (EOF) ........................................................ 91 File system ............................................................... 569 Function iterator ................................................... 431 hasattr ....................................................................... 370
Entry widget (tkinter) .......................................... 826 File Transfer Protocol Function name ....................................................... 279 Hash ........................................................................... 179
Enum ......................................................................... 481 see FTP ................................................................... 713 Function object ...................................................... 282 hash (function) ...................................................... 312
enum ................................................................ 269, 270 File-like object ......................................................... 555 Function parameters .............................................. 58 Hash collision ........................................................ 515
enumerate (function) .......................................... 309 filter ............................................................................ 178 functools .................................................................. 455 Hash function ........................................................ 514
Enumeration ........................................................... 269 Filter (Django) ......................................................... 918 Future import ......................................................... 339 Hash randomization ........................................... 230
alias ....................................................................... 271 filter (function) ....................................................... 310 Hash value ............................................ 217, 312, 514
flag ......................................................................... 271 finally ......................................................................... 404 G hashable ................................................................... 379
integer .................................................................. 272 Finder (importlib) ................................................. 336 hashlib ...................................................................... 514
Escape sequence ................................. 185, 209, 534 Fire and Forget ........................................................ 617 Garbage collection ................................................ 110 HDF5 .......................................................................... 966
\N ............................................................................ 211 First in, first out (FIFO) ........................................ 620 Gaussian distribution ......................................... 505 Help ............................................................................ 119
\u ............................................................................ 211 Flag (enum) .............................................................. 272 Generator ....................................................... 416, 976 interactive .......................................................... 119
\x ............................................................................. 209 Flag (RegExp) ........................................................... 543 asynchronous .................................................... 628 help (function) .............................................. 119, 313
eval ............................................................................. 309 float ............................................................ 51, 141, 311 consuming .......................................................... 976 hex .............................................................................. 313
Event (Qt) ................................................................. 859 Font (tkinter) ........................................................... 848 subgenerator ...................................................... 418 Hexadecimal system .......................................... 136
Event (tkinter) ........................................................ 815 for ..................................................... 84, 177, 628, 629 Generator expression ......................................... 421 History function ...................................................... 49
Event handler (Qt) ................................................ 859 format ........................................................................ 311 Generics .................................................................... 472 Hook (function) ..................................................... 559
Event handler (tkinter) ....................................... 815 Frequency distribution ....................................... 240 Geometric mean ................................................... 508 HTML ................................................................ 546, 966
Excel ........................................................................... 966 from .................................................................. 327, 333 GET (HTTP) ............................................ 701, 703, 927 HTTP .......................................................................... 701
except ........................................................................ 402 from/cimport ......................................................... 797 getattr ........................................................................ 370 HTTPS ........................................................................ 701
Exception ........................................... 399, 999, 1011 frozenset ...................................... 215, 227, 237, 311 getpass ....................................................................... 971 Hyperbolic cosine ................................................ 501
BaseException ................................................... 400 f-string ............................................................. 198, 206 Getter method ....................................................... 365 Hyperbolic function ............................................ 501
built-in .................................................................. 400 FTP ..................................................................... 701, 713 gettext ....................................................................... 781 Hyperbolic sine ..................................................... 501
chaining ............................................................... 410 control channel ................................................. 714 language compilation .................................... 783 Hyperbolic tangent ............................................. 501
handling ............................................................... 401 data channel ....................................................... 714 GIL ..................................................................... 590, 798 Hypotenuse ............................................................ 502
raise ....................................................................... 401 mode ...................................................................... 714 Git ............................................................................. 1015
re-raise .................................................................. 408 ftplib ................................................................. 702, 713 Global ......................................................................... 295 I
exec ............................................................................ 310 Function ................................................... 57, 115, 277 Global Interpreter Lock -> see GIL .................. 590
Exit code ................................................................... 556 anonymous ......................................................... 299 Global module ....................................................... 325 IANA time zone database .................................. 263
Exponent ........................................................ 142, 499 argument ............................................................. 278 Global namespace ................................................ 293 id ........................................................................ 108, 313
Exponential function .......................................... 501 body ....................................................................... 279 Global reference .................................................... 293 IDE ............................................................................ 1014
Exponential notation .......................................... 142 built-in .................................................................. 300 Global variable ....................................................... 589 LiClipse ............................................................... 1015
Expression call .................................................................. 57, 278 globals ....................................................................... 312 PyCharm ........................................................... 1014
arithmetic ........................................................... 127 definition ............................................................. 279 GNU gettext API .................................................... 781 PyDev .................................................................. 1015
Boolean ......................................................... 55, 144 hyperbolic ............................................................ 501 Golden ratio ............................................................ 423 Spyder ................................................................. 1016
logical ............................................................ 55, 144 interface ............................................................... 279 Gradient (Qt) ........................................................... 876 Visual Studio Code ........................................ 1015
self-documenting ............................................. 206 keyword argument .......................................... 283 Graphical user interface -> see GUI ............... 805 Identifiers ................................................................... 55
Extension ....................................................... 767, 794 keyword-only parameter ............................... 286 GTK ............................................................................. 806 Identity (of an instance) .................................... 108

1024 1025
Index Index

Identity comparison (of instances) ............... 109 Inverse hyperbolic sine ....................................... 501 Keyword (Cont.) Listen mode ............................................................ 685
IDLE ..................................................................... 45, 739 Inverse hyperbolic tangent ............................... 502 False ................................................................ 55, 144 ListWidget (Qt) ....................................................... 864
IEEE-754 .................................................................... 142 [Link] ................................................................ 975 finally .................................................................... 404 Literal ........................................................................... 49
if ........................................................... 76, 79, 178, 483 IP address .................................................................. 674 for .................................................................... 84, 177 Literal pattern ........................................................ 481
Image processing .................................................. 984 IPv6 ............................................................................. 681 from ............................................................. 327, 333 Little endian ........................................................... 559
Images (Qt) .............................................................. 873 IPython ...................................................................... 799 global .................................................................... 295 Loader (importlib) ................................................ 337
Imaginary part ....................................................... 149 Notebook ............................................................. 802 if ...................................................... 76, 79, 178, 483 loc ............................................................................... 957
IMAP4 ........................................................................ 728 is ......................................................................... 109, 127 import ................................................ 326, 333, 338 Local function ........................................................ 295
mailbox ................................................................ 729 isinstance .................................................................. 371 in ................................................ 155, 177, 221, 232 Local module ................................................. 325, 328
imaplib ...................................................................... 728 issubclass .................................................................. 371 is .................................................................... 109, 127 Local namespace ................................................... 293
Immutable ............................................ 111, 125, 181 iter ............................................................................... 422 lambda ................................................................. 299 Local reference ...................................................... 293
Immutable data type ........................................... 111 Iterable object ................................................. 84, 422 match .................................................................... 480 Local time ................................................................ 248
Import Cartesian product ............................................. 438 None ...................................................................... 126 Localization ............................................................ 781
absolute ............................................................... 334 chain ...................................................................... 433 nonlocal ............................................................... 296 locals .......................................................................... 315
relative .................................................................. 334 combination ....................................................... 434 not ......................................................... 56, 144, 221 Lock object .............................................................. 605
import ....................................................................... 333 group ..................................................................... 437 not in ........................................................... 156, 232 Log file ...................................................................... 523
import statement ................................ 60, 326, 338 partial sum .......................................................... 433 or ................................................................................ 57 Logarithm function ............................................. 501
Importer ................................................................... 335 permutation ....................................................... 438 pass ........................................................................... 87 Logging ..................................................................... 523
importlib .................................................................. 335 repeat .................................................................... 439 raise ....................................................................... 401 Logging handler .................................................... 527
finder ..................................................................... 336 Iterator ............................................................. 422, 997 return .................................................................... 280 Logical expression ............................................... 144
loader .................................................................... 337 asynchronous ..................................................... 628 True ................................................................. 55, 144 Logical operator .................................................... 144
in ..................................................... 155, 177, 221, 232 Iterator protocol ............................................ 84, 422 try ........................................................................... 402 logical AND ........................................................ 145
in place ...................................................................... 158 itertools ..................................................................... 432 while ......................................................................... 79 logical negation ............................................... 144
Indentation ................................................................ 67 with ........................................................................ 441 logical OR ............................................................ 145
Index (in a sequence) .......................................... 159 J yield ............................................................. 416, 976 Logical expression .................................................. 55
IndexError ............................................................... 160 Keyword argument .................................... 116, 283 long ............................................................................ 135
inf ............................................................. 143, 499, 512 JIT --> Just-in-time compiler ............................. 790 Keyword-only parameter .................................. 117 Loop .............................................................................. 79
Infinite ...................................................................... 143 Join (SQL) .................................................................. 653 asynchronous .................................................... 628
Inheritance .............................................................. 351 JSON ........................................................ 665, 704, 966 L body ......................................................................... 79
multiple inheritance ....................................... 363 Jupyter Notebook .................................................. 802 break ........................................................................ 80
input ........................................................................... 314 JupyterLab ................................................................ 802 Label (tkinter) ......................................................... 827 continue ................................................................. 82
Installation script .................................................. 768 Just-in-time compiler .................................. 66, 790 LabelFrame (tkinter) ............................................ 828 counting loop ....................................................... 85
Instance ................................................... 58, 103, 346 Numba .................................................................. 790 lambda ...................................................................... 299 else ............................................................................ 81
data type ............................................................. 106 PyPy ....................................................................... 789 Language compilation ........................................ 783 for .............................................................................. 84
identity ................................................................. 108 Language element, planned ............................. 338 while ......................................................................... 79
value ...................................................................... 107 K LaTeX ......................................................................... 944 Loose coupling (Django) .................................... 894
Instantiation .................................................... 58, 346 Layout (Qt) ............................................................... 851 Lower median ........................................................ 508
int ............................................................... 49, 135, 314 Keras ............................................................................. 42 Layout (tkinter) ...................................................... 811
Integer ...................................................... 49, 135, 999 Key-value pair ......................................................... 215 Lazy evaluation ............................................... 79, 148 M
Integer division ........................................................ 50 Keyword .......................................................... 55, 1005 Leap second ............................................................. 249
Integrated Development Environment 씮 IDE and ............................................................................ 56 len .................................................. 164, 219, 232, 315 Magic attribute ...................................................... 375
IntEnum .................................................................... 272 as ................................................................... 327, 484 Library ....................................................................... 325 __annotations__ ............................................. 469
Interactive help ..................................................... 119 assert ..................................................................... 411 LiClipse (IDE) ........................................................ 1015 __dict__ .............................................................. 379
Interactive mode .............................................. 45, 49 break ........................................................................ 80 Lightweight process ............................................. 589 __doc__ ............................................................... 760
history function ................................................... 49 case ......................................................................... 480 Line comment ........................................................... 72 __match_args__ .............................................. 492
Interface ................................................. 116, 279, 455 class ........................................................................ 347 Line edit (Qt) ........................................................... 864 __slots__ .................................................... 379, 381
Internationalization ............................................ 781 continue ................................................................. 82 List .................................................................................. 52 Magic line (program header) .............................. 65
Interpreter .......................................................... 40, 66 def ........................................................................... 279 doubly linked ..................................................... 243 Magic method ........................................................ 375
CPython ........................... 66, 590, 601, 789, 798 del ....................................................... 110, 168, 220 side effect ............................................................. 175 __abs__ ............................................................... 388
PyPy ....................................................................... 789 elif ............................................................................. 76 list (data type) ........................................ 52, 166, 315 __add__ ..................................................... 386, 391
Intersection (of sets) ............................................ 233 else .................................................... 77, 79, 81, 404 List comprehension ............................................. 177 __and__ .............................................................. 386
Inverse hyperbolic cosine ................................. 501 except .................................................................... 402 Listbox (tkinter) ..................................................... 829 __bytes__ ........................................................... 376

1026 1027
Index Index

Magic method (Cont.) Magic method (Cont.) Method (Cont.) Non-convex polygon .......................................... 844
__call__ ............................................ 376, 378, 453 __radd__ .................................................... 387, 391 static ...................................................................... 368 None .......................................................................... 126
__complex__ ........................................... 376, 389 __rand__ ............................................................. 387 Microsoft Excel ...................................................... 966 NoneType ................................................................ 126
__contains__ ..................................................... 391 __rdiv__ ............................................................... 387 Migration (Django) ............................................... 903 nonlocal ................................................................... 296
__del__ ....................................................... 376, 377 __rdivmod__ ...................................................... 387 MIME .......................................................................... 734 Non-modal dialog (Qt) ....................................... 863
__delattr__ ......................................................... 379 __repr__ ............................................................... 376 min ................................................................... 164, 318 Normal distribution ............................................ 505
__delitem__ ....................................................... 390 __rfloordiv__ ..................................................... 387 Modal dialog (Qt) .................................................. 863 not ....................................................................... 56, 144
__div__ ................................................................ 386 __rlshift__ ........................................................... 387 Modal value (statistics) ....................................... 508 Not a number (NaN) ............................................ 143
__divmod__ ....................................................... 386 __rmatmul__ ..................................................... 387 Mode not in ...................................................... 156, 221, 232
__enter__ .................................................. 390, 443 __rmod__ ............................................................ 387 interactive ...................................................... 45, 49 Notebook ................................................................. 802
__eq__ .................................................................. 385 __rmul__ ................................................... 387, 391 Mode (statistics) .................................................... 508 NotImplemented .................................................. 389
__exit__ ..................................................... 390, 443 __ror__ ................................................................. 387 Model (Django) ............................................ 894, 901 Numba ...................................................................... 790
__float__ ................................................... 376, 389 __round__ ................................................. 376, 389 Model API (Django) .............................................. 904 Number
__floordiv__ ....................................................... 386 __rpow__ ............................................................. 387 Model class (Qt) ..................................................... 879 complex ............................................................... 149
__ge__ .................................................................. 385 __rrshift__ ........................................................... 387 Model-view concept (Django) ....... 894, 900, 901 float ................................................................ 51, 141
__getattr__ ........................................................ 379 __rshift__ ............................................................ 386 Model-view concept (Qt) .......................... 851, 879 integer .................................................. 49, 135, 999
__getattribute__ .................................... 379, 380 __rsub__ .............................................................. 387 Modifier (tkinter) .................................................. 816 Numeral system ................................................... 135
__getitem__ ............................................. 390, 430 __rxor__ .............................................................. 387 Module ..................................................... 60, 325, 767 decimal system ................................................. 135
__gt__ .................................................................. 385 __setattr__ ................................................ 379, 380 built-in .................................................................. 325 dual system ............................................... 136, 137
__hash__ ................................................... 376, 378 __setitem__ ........................................................ 390 executing ............................................................. 330 hexadecimal system ....................................... 136
__iadd__ .................................................... 388, 391 __str__ .................................................................. 376 global .................................................................... 325 octal system ....................................................... 136
__iand__ ............................................................. 388 __sub__ ................................................................ 386 local ............................................................. 325, 328 Numeric data type ............................................... 131
__idiv__ ............................................................... 388 __xor__ ................................................................ 386 name conflict ..................................................... 329 NumPy ................................... 42, 142, 791, 935, 953
__ifloordiv__ ..................................................... 388 Mailbox ..................................................................... 729 ModuleNotFoundError ...................................... 330 ndarray ....................................................... 938, 944
__ilshift__ ........................................................... 388 Main Event Loop (Qt) ........................................... 858 Modulo ...................................................................... 499
__imatmul__ ..................................................... 388 Mantissa .......................................................... 142, 499 Monty Python ........................................................... 39 O
__imod__ ............................................................ 388 map (function) ............................................. 178, 316 Multicall .................................................................... 696
__imul__ ................................................... 388, 391 Mapping .................................................................... 215 Multiple inheritance ............................................ 363 Object ............................................................... 341, 345
__index__ ................................................. 376, 389 Mapping patterns .................................................. 488 Multiplexing server ................................... 675, 686 awaitable ............................................................ 614
__init__ ................................................................ 376 match ......................................................................... 480 Multiprocessing ................................. 592, 611, 630 file-like .................................................................. 555
__int__ ................................................................. 389 Match object (RegExp) ......................................... 544 Multitasking ............................................................ 587 iterable ................................................................. 422
__invert__ ........................................................... 388 Matching (RegExp) ............................ 529, 544, 547 cooperative ...................................... 591, 613, 629 oct ............................................................................... 318
__ior__ ................................................................. 388 math ........................................................................... 497 preemptive .......................................................... 590 Octal system ........................................................... 136
__ipow__ ............................................................. 388 MATLAB ..................................................................... 935 Mutable ........................................................... 111, 125 Ones' complement ............................................... 139
__irshift__ ........................................................... 388 matplotlib ................................................ 42, 935, 942 Mutable data type ................................................. 111 One-to-many relation ........................................ 902
__isub__ .............................................................. 388 max ......................................................... 115, 164, 317 mypy .......................................................................... 476 One-way coding .................................................... 515
__iter__ ...................................................... 391, 422 MD5 ............................................................................ 516 open ............................................................. 92, 97, 625
__ixor__ .............................................................. 388 Median ....................................................................... 508 N openpyxl .................................................................. 966
__le__ ................................................................... 385 Member ..................................................................... 345 Operand ................................................................... 127
__len__ ................................................................. 390 Memory view .......................................................... 796 Name conflict ......................................................... 329 Operating system ................................................. 557
__lshift__ ............................................................ 386 Menu (tkinter) ........................................................ 831 Named expression .................................................. 89 Operator ............................................................ 50, 127
__lt__ .................................................................... 385 Menu bar (tkinter) ................................................. 831 namedtuple ............................................................. 245 arithmetic ........................................................... 131
__matmul__ ...................................................... 386 Menu button (tkinter) ......................................... 833 Namespace .................................................... 293, 326 binary ................................................................... 386
__mod__ ............................................................. 386 Message box (tkinter) .......................................... 848 global .................................................................... 293 bit operator ........................................................ 137
__mul__ ..................................................... 386, 391 Metaclass ........................................................ 346, 373 local ....................................................................... 293 Boolean ................................................................... 57
__ne__ .................................................................. 385 Method ........................................... 58, 115, 345, 347 Namespace package ............................................. 333 comparison operator ............................ 133, 384
__neg__ ............................................................... 388 class method ....................................................... 369 NaN ................................................................... 143, 965 logical ................................................................... 144
__next__ .............................................................. 422 definition ............................................................. 347 nan ........................................................... 143, 499, 512 logical AND ........................................................ 145
__nonzero__ ...................................................... 376 getter method .................................................... 365 ndarray (NumPy) ........................................ 938, 944 logical negation ............................................... 144
__or__ .................................................................. 386 magic method .................................................... 375 Network byte order .............................................. 685 logical OR ............................................................ 145
__pos__ ................................................................ 388 overriding ............................................................ 353 Node (DOM) ............................................................ 633 overloading ........................................................ 382
__pow__ .............................................................. 386 setter method ..................................................... 365 nogil ........................................................................... 798 relational operator ............................................ 55

1028 1029
Index Index

Operator (Cont.) PEP 257 (Docstrings) ............................................ 121 PyPy ..................................................................... 66, 789 Qt (Cont.)
unary ..................................................................... 388 PEP 8 (Style Guide) ................................................ 121 PyQt ............................................................................ 806 progress bar ....................................................... 865
Operator precedence ............................... 128, 1005 Permutation ............................................................ 438 PySide6 ............................................................ 806, 850 push button ....................................................... 865
Option (command) .............................................. 561 PhD thesis ................................................................ 162 Python 2 ................................................................... 993 QML ....................................................................... 852
Optional parameter ................................... 117, 282 pickle .......................................................................... 662 conversion ........................................................ 1001 radio button ...................................................... 865
OptionMenu (tkinter) ......................................... 834 PIL ................................................................................ 984 Python API .................................................................. 40 signal ........................................................... 851, 859
or .................................................................................... 57 Pillow .......................................................................... 984 Python Database API Specification ............... 644 slider ..................................................................... 866
ord ..................................................................... 212, 318 pip ...................................................................... 766, 777 Python debugger (PDB) ............................ 301, 739 slot ................................................................ 851, 859
Ordering ................................................................... 459 Pipe ............................................................................. 536 Python distribution ................................................ 42 splitter .................................................................. 855
os ....................................................................... 553, 569 Planned language element ................................ 338 Python Enhancement Proposal -> see PEP . 120 text edit ............................................................... 866
[Link] ....................................................................... 575 Platform independence ........................................ 40 Python Imaging Library -> see PIL ................. 984 transformation ................................................. 878
OSI Model ................................................................. 673 Polar coordinates ........................................ 502, 503 Python package index -> see PyPI .................. 766 transparency ..................................................... 877
Polygon ........................................................... 844, 873 Python package Manager -> see pip .............. 777 view class ............................................................ 879
P convex ................................................................... 844 Python shell ............................................................... 45 widget ................................................ 852, 861, 867
non-convex ......................................................... 844 Python Software Foundation -> see PSF ......... 40 Qt Designer ............................................................. 853
Package ........................................................... 331, 767 POP3 ........................................................................... 724 Python version ...................................................... 557 Qt for Python ......................................................... 806
__init__.py ................................................ 331, 333 poplib ......................................................................... 724 Python website ......................................................... 42 Quantifier (RegExp) ............................................. 531
namespace package ........................................ 333 Port (network) ......................................................... 675 PYTHONHASHSEED ............................................. 230 nongreedy ........................................................... 535
Package manager .................................................. 776 Positional argument ............................................ 283 PyTorch ........................................................................ 42 Query (database) ................................................... 644
Packer (tkinter) ............................................ 808, 811 Positional parameter ........................................... 283 Queue ........................................................................ 620
Packing (sequence) ............................................... 179 Positional-only parameter ................................ 287 Q Consumer ............................................................ 620
Padding (tkinter) ................................................... 814 POST (HTTP) ........................................ 701, 703, 927 Producer .............................................................. 620
Painter (Qt) .............................................................. 869 Postmortem debugger ........................................ 741 QML (Qt) ................................................................... 852 Queue (network) ................................................... 677
Painter path (Qt) .................................................... 878 pow .............................................................................. 318 qsort ........................................................................... 798
pandas ...................................................... 42, 935, 953 PowerShell ....................................................... 63, 561 Qt ....................................................................... 806, 850 R
Parallel server ......................................................... 675 pprint ................................................................. 60, 521 alpha blending .................................................. 877
Parameter ............................................... 58, 116, 278 Precedence (operator) ......................................... 128 anti-aliasing ....................................................... 878 Radio button (Qt) .................................................. 865
any number ........................................................ 284 Preemptive multitasking ................................... 590 Bezier curve ........................................................ 878 Radio button (tkinter) ........................................ 825
keyword ..................................................... 116, 283 Prime number ........................................................ 603 brush ..................................................................... 870 Rainbow table ........................................................ 519
keyword-only ........................................... 117, 286 print ........................................................... 59, 318, 996 checkbox .............................................................. 862 raise ............................................................................ 401
optional ..................................................... 117, 282 Procedure ................................................................. 277 combobox ........................................................... 862 random ..................................................................... 503
positional .................................................. 116, 283 Process ................................................... 554, 587, 630 coordinate system ........................................... 870 Random access ...................................................... 633
positional-only .................................................. 287 Processor .................................................................. 554 date edit ............................................................... 863 range .......................................................... 85, 277, 319
unpack .................................................................. 288 Producer (queue) ................................................... 620 delegate ................................................................ 883 Rapid Prototyping ................................................... 41
Parent (DOM) .......................................................... 634 Profiler ....................................................................... 752 dialog .......................................................... 858, 863 Raspberry Pi ............................................................... 41
Parser (XML) ............................................................ 632 Program file ............................................................... 63 drawing ................................................................ 868 Raw string ................................................................ 186
Partial sum .............................................................. 433 Programming paradigm ....................................... 40 drawing text ....................................................... 874 raw_input ................................................................ 997
pass ................................................................................ 87 Progress bar (Qt) .................................................... 865 event ...................................................................... 859 re ................................................................................. 529
Password ........................................................ 518, 971 Prompt ......................................................................... 68 event handler ..................................................... 859 Real part ................................................................... 149
Path ......................................................... 556, 569, 575 Proper subset .......................................................... 232 gradient ............................................................... 876 Recursion ................................................................. 300
Pattern property (function) ............................................... 366 images .................................................................. 873 depth ..................................................................... 300
capture pattern ................................................. 484 Property attribute ................................................. 366 layout .................................................................... 851 Reference ........................................................ 103, 105
literal pattern .................................................... 481 Protocol layer .......................................................... 673 line edit ................................................................. 864 global .................................................................... 293
mapping pattern .............................................. 488 Pseudorandom number ..................................... 503 list widget ............................................................ 864 local ....................................................................... 293
sequence pattern .............................................. 486 PSF (organization) ................................................... 40 main event loop ................................................ 858 Reference count .................................................... 110
type checking pattern .................................... 482 PSF license .................................................................. 40 modal dialog ...................................................... 863 Reference implementation .............................. 789
Payload (HTTP) ...................................................... 704 Push button (Qt) .................................................... 865 model class ......................................................... 879 RegExp -> see Regular expression ................. 529
PBKDF2 ..................................................................... 519 PyCharm (IDE) ........................................... 464, 1014 model-view concept .............................. 851, 879 Regular expression .............................................. 529
pd ................................................................................. 954 PyDev (IDE) ........................................................... 1015 non-modal dialog ............................................ 863 alternative .......................................................... 536
Pen (Qt) ..................................................................... 869 PyGObject ................................................................. 806 painter .................................................................. 869 character class ......................................... 530, 533
PEP .............................................................................. 120 PyPI ................................................................... 766, 777 painter path ....................................................... 878 character literal ................................................ 529
PEP 249 ...................................................................... 644 pyplot (matplotlib) ............................................... 942 pen ......................................................................... 869 extension ............................................................ 537

1030 1031
Index Index

Regular expression (Cont.) Server (Cont.) SQLite Standard library (Cont.)


group ..................................................................... 536 parallel .................................................................. 675 adaptation .......................................................... 658 struct ..................................................................... 969
match object ...................................................... 544 serial ...................................................................... 675 conversion ........................................................... 658 sys .......................................................................... 555
matching ................................................... 544, 547 Set ...................................................................... 215, 227 sqlite3 ........................................................................ 646 tempfile ............................................................... 585
quantifier ................................................... 531, 535 difference ............................................................. 234 Stable sorting method ........................................ 173 threading ......................................... 592, 603, 630
searching ............................................................. 546 intersection ......................................................... 233 Standard deviation ............................................... 508 time ....................................................................... 247
special characters ............................................ 534 proper subset ...................................................... 232 Standard dialog (tkinter) .................................... 847 timeit .................................................................... 749
syntax ................................................................... 529 subset .................................................................... 232 Standard library .................................... 40, 60, 1000 Tkinter .................................................................. 805
Relational database .............................................. 644 symmetric difference ...................................... 234 argparse ............................................................... 561 tkinter ................................................................... 807
Relational operator ................................................. 55 set ................................................... 215, 227, 236, 321 asyncio ................................................................. 592 trace ...................................................................... 756
repr ............................................................................. 320 setattr ......................................................................... 370 cmath .................................................................... 497 typing ................................................ 465, 469, 471
Request handler .................................................... 688 Setter method ......................................................... 365 cmd ........................................................................ 972 unittest ................................................................ 746
requests .......................................................... 702, 703 setuptools ................................................................. 766 collections ........................................................... 239 urllib ...................................................................... 702
Reserved word .............................................. 55, 1005 SHA ............................................................................. 516 [Link] ................................. 591, 630 [Link] ......................................................... 710
return ......................................................................... 280 Shebang ............................................................. 65, 788 contextlib ............................................................ 444 [Link] ..................................................... 706
Return value ................................. 58, 115, 278, 279 Shell .................................................................... 43, 561 copy ....................................................................... 981 urllib2 ................................................................... 702
reversed .................................................................... 320 Shortcut function .................................................. 915 cProfile .................................................................. 752 venv ....................................................................... 786
Root (DOM) ............................................................. 634 shutil .......................................................................... 579 csv ........................................................................... 668 warnings ............................................................. 412
round ......................................................................... 321 Siblings (DOM) ....................................................... 634 datetime .............................................................. 254 webbrowser ........................................................ 969
Row index ...................................................... 955, 956 Side effect .................................... 114, 175, 290, 981 decimal ................................................................. 509 xml ......................................................................... 631
RPM ............................................................................ 773 Signal (Qt) ....................................................... 851, 859 distutils ....................................................... 766, 767 xmlrpc .................................................................. 690
Runtime measurement ...................................... 749 Simple API for XML -> see SAX ........................ 640 doctest .................................................................. 742 zoneinfo ............................................................... 263
Runtime performance ........................................ 749 Sine .............................................................................. 501 ElementTree (XML) .......................................... 633 standard library .................................................... 325
site-packages ........................................................... 325 email ..................................................................... 734 Statement ................................................................... 67
S Sleeping thread ...................................................... 588 enum ..................................................................... 270 body ......................................................................... 67
Slicing ..................................................... 161, 957, 961 ftplib ............................................................ 702, 713 header ..................................................................... 67
Salt .................................................................... 230, 515 Slider (Qt) .................................................................. 866 functools .............................................................. 455 Static method ......................................................... 368
SAX (XML) ................................................................ 640 Slot (Qt) ............................................................ 851, 859 getpass ................................................................. 971 Static typing .................................................. 794, 796
scikit-learn .................................................................. 42 SMTP ........................................................................... 721 gettext .................................................................. 781 staticmethod .......................................................... 450
Scilab .......................................................................... 935 smtplib ...................................................................... 721 gzip ........................................................................ 661 staticmethod (function) .................................... 368
SciPy ................................................. 42, 935, 952, 953 Socket ......................................................................... 674 hashlib .................................................................. 514 statistics ................................................................... 507
Scrapy ........................................................................ 618 blocking ................................................................ 680 http ........................................................................ 702 stderr ......................................................................... 556
Screen output ............................................................ 59 byte order ............................................................. 685 imaplib ................................................................. 728 stdin .................................................................... 91, 556
Scrollbar (tkinter) .................................................. 835 communication socket ................................... 676 importlib .............................................................. 335 stdout ................................................................. 91, 556
Searching ........................................................ 529, 546 connection object ............................................. 684 [Link] ........................................................... 975 str ...................................................... 51, 182, 322, 998
select .......................................................................... 686 connection socket ............................................. 675 itertools ................................................................ 432 Stream .......................................................................... 91
self ............................................................................... 347 IPv6 ........................................................................ 681 logging ................................................................. 523 String ......................................................... 51, 182, 998
Self-documenting expression ......................... 206 listen mode .......................................................... 685 math ...................................................................... 497 control character ............................................. 185
Semicolon ................................................................... 69 non-blocking ...................................................... 680 multiprocessing ............................. 592, 611, 630 escape sequence ...................................... 185, 209
Sequence Patterns ................................................ 486 socketserver ............................................................ 688 os .................................................................. 553, 575 formatting .......................................................... 197
Sequence unpacking ........................................... 180 sorted ......................................................................... 321 [Link] .................................................................. 575 line break ............................................................ 185
Sequential data type ............................................ 153 Sorting method pickle ..................................................................... 662 raw string ............................................................ 186
concatenation ................................................... 157 stable ..................................................................... 173 poplib .................................................................... 724 special characters ............................................ 208
indexing ..................................................... 159, 165 Source code ................................................................ 63 pprint ............................................................. 60, 521 whitespace .......................................................... 186
length .................................................................... 164 Source distribution ..................................... 765, 773 random ................................................................ 503 String formatting ................................................. 197
maximum ........................................................... 164 Sources of Information ....................................... 119 select ...................................................................... 686 StringIO .................................................................... 975
minimum ............................................................ 164 Special characters ........................................ 208, 534 shutil ........................................................... 579, 584 struct ......................................................................... 969
slicing .................................................................... 161 Spinbox (tkinter) ................................................... 836 smtplib ................................................................. 721 Structural pattern matching ............................ 479
Serial server ............................................................. 675 Splitter (Qt) .............................................................. 855 socket .................................................................... 674 Structured Query Language --> see SQL ...... 644
Serialize ..................................................................... 662 Spyder (IDE) .......................................................... 1016 socketserver ........................................................ 688 Subgenerator ......................................................... 418
Server ......................................................................... 675 SQL .............................................................................. 644 sqlite3 .................................................................... 646 Subset ........................................................................ 232
multiplexing ............................................. 675, 686 SQL Injection ........................................................... 650 statistics ............................................................... 507 Subversion (SVN) ................................................ 1015

1032 1033
Index Index

sum ............................................................................. 323 tkinter (Cont.) typing ..................................................... 465, 469, 471 W
Symmetric difference set .................................. 234 label ........................................................................ 827 tzdata ......................................................................... 264
Syntax ........................................................................... 66 LabelFrame ......................................................... 828 Wallis product ............................................... 596, 791
Syntax analysis ...................................................... 632 listbox .................................................................... 829 U Walrus operator ....................................................... 89
Syntax error ............................................................... 66 menu ...................................................................... 831 Warning .................................................................... 412
sys ............................................................................... 555 menu bar .............................................................. 831 UDP ............................................................................. 677 warnings (module) ............................................... 412
menu button ....................................................... 833 u-literal ...................................................................... 186 Web API .................................................................... 704
T message box ....................................................... 848 Unary operator ...................................................... 388 Web crawler ............................................................ 618
modifier ................................................................ 816 Unbound local variable ...................................... 298 webbrowser ............................................................ 969
Tag (Django) ............................................................ 919 OptionMenu ....................................................... 834 UnboundLocalError ............................................. 298 Wheel ............................................................... 766, 795
Tag (XML) ................................................................. 631 packer .......................................................... 808, 811 Underscore ................................................................. 54 while ............................................................................. 79
bodiless ................................................................. 632 padding ................................................................ 814 unhashable .................................................... 217, 228 Whitespace .............................................. 95, 186, 533
Tangent ..................................................................... 501 radio button ....................................................... 825 Unicode ........................................................... 210, 212 whl .............................................................................. 766
TAR .................................................................... 579, 584 scrollbar ................................................................ 835 unicode (function) ................................................ 998 Widget (GUI) ........................................................... 805
Task ............................................................................. 616 spinbox ................................................................. 836 UnicodeDecodeError ........................................... 213 Widget (Qt) ........................................... 852, 861, 867
TCP .............................................................................. 678 standard dialog ................................................. 847 Uniform distribution .......................................... 505 Widget (tkinter) ..................................................... 821
tempfile .................................................................... 585 text widget .......................................................... 837 Uniform Resource Locator -> see URL .......... 705 Wildcard ................................................................... 485
Template (Django) ................................................ 915 widget .................................................................... 821 Unit test .................................................................... 746 Window (GUI) ........................................................ 805
Template inheritance (Django) ....................... 921 Toolkit (GUI) ............................................................ 805 unittest (module) .................................................. 746 Winter time ............................................................ 265
Temporary file ....................................................... 585 PyGObject ............................................................ 806 Unix epoch .............................................................. 247 with ............................................................................ 441
TensorFlow ................................................................. 42 Qt .................................................................. 806, 850 Unix timestamp .................................................... 247 asynchronous ........................................... 619, 627
Terminator (iteration) ........................................ 431 Tkinter ................................................................... 805 Unpacking ............................................. 180, 216, 229 Working directory ................................................ 569
Test wxPython ............................................................. 807 Upper median ........................................................ 508 Wrapper function ........................................ 449, 451
automated .......................................................... 741 trace ............................................................................ 756 URL .......................................................... 705, 706, 969 WSGI .......................................................................... 897
Test-driven development .................................. 741 Traceback ........................................................ 400, 560 urllib ........................................................................... 702 wxPython ................................................................ 807
Testing Traceback object .................................................... 444 [Link] ............................................................... 710
doctest .................................................................. 742 Tracer ......................................................................... 756 [Link] .......................................................... 706 X
unittest ................................................................. 746 Transaction (database) ........................................ 649 urllib2 ........................................................................ 702
Text edit (Qt) ........................................................... 866 Transformation (Qt) ............................................. 878 urllib3 ........................................................................ 702 XLSX ........................................................................... 966
Text widget (tkinter) ............................................ 837 Transmission Control Protocol ....................... 678 UTC ................................................................... 248, 264 XML ............................................................................ 631
The Qt Company ................................................... 806 Transparency (Qt) ................................................. 877 attribute .............................................................. 632
Thread ............................................................. 589, 630 Trigonometric function ...................................... 501 V bodiless tag ........................................................ 632
sleeping ................................................................ 588 Trolltech .................................................................... 806 declaration ......................................................... 631
threading ............................................... 592, 603, 630 True ..................................................................... 55, 144 Value .......................................................................... 107 Document Object Model ............................... 633
Time ........................................................................... 247 Truth value ....................................................... 55, 147 Boolean ...................................................... 144, 147 DOM ...................................................................... 633
time (module) ........................................................ 247 try ................................................................................ 402 Value comparison ................................................ 107 element ................................................................ 631
Time slice ................................................................. 588 Tuple Variable ....................................................... 54, 55, 105 parser .................................................................... 632
Time zone ................................................................ 263 named ................................................................... 245 global .................................................................... 589 path ....................................................................... 639
timeit ......................................................................... 749 unpacking ............................................................ 180 unbound local ................................................... 298 SAX ........................................................................ 640
Timestamp .............................................................. 247 tuple .................................................................. 179, 323 Variance .................................................................... 508 tag .......................................................................... 631
Tk ................................................................................. 805 Tuple packing .......................................................... 179 Vectorization (numpy) ....................................... 939 XML-RPC .................................................................. 690
Tkinter ....................................................................... 805 Two's complement ............................................... 139 venv ............................................................................ 786 multicall .............................................................. 696
tkinter ........................................................................ 807 type ......................................................... 106, 125, 323 View (Django) ...................................... 894, 901, 910 XZ ................................................................................ 584
button ................................................................... 823 Type alias .................................................................. 474 View class (Qt) ........................................................ 879
canvas ................................................................... 839 Type checking pattern ......................................... 482 Virtual environment ........................................... 785 Y
checkbutton ....................................................... 824 Type comment ....................................................... 463 Virtual machine ........................................................ 66
control variable ................................................ 810 Type hint ......................................................... 463, 471 virtualenv ................................................................. 787 yield ........................................................ 416, 628, 976
drawing ................................................................ 839 Type union ............................................................... 474 Visual Studio Code (IDE) ................................. 1015 yield from ................................................................ 418
entry widget ....................................................... 826 Type variable ........................................................... 475
event ...................................................................... 815 Typing
event handler ..................................................... 815 static ...................................................................... 794
font ........................................................................ 848

1034 1035
Index

Z
ZIP ..................................................................... 579, 584
zip (function) .......................................................... 324
zlib .............................................................................. 661
zoneinfo .................................................................... 263

1036
Build and deepen your coding knowledge
from the top programming experts!

Johannes Ernesti and Peter Kaiser received their doctorates in


mathematics and computer science, respectively, from the
Karlsruhe Institute of Technology (KIT).

They have been developing Python software professionally and


privately for more than 20 years, currently as part of their research
in neural machine translation at DeepL.

This book served as the basis for several trainings in companies and
universities. At KIT, a Python lecture based on this book has been
held annually since 2015.

Johannes Ernesti, Peter Kaiser


Python 3: The Comprehensive Guide
1036 pages, 2022, $59.95 We hope you have enjoyed this reading sample. You may recommend or pass it
ISBN 978-1-4932-2302-2 on to others, but only in its entirety, including all pages. This reading sample and
all its parts are protected by copyright law. All usage and exploitation rights are
[Link]/5566 reserved by the author and the publisher.

You might also like