Reading Sample Sap Press Python 3
Reading Sample Sap Press Python 3
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.
Contents
Index
The Author
[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
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.
Operator Result
131
11 Numeric Data Types 11.2 Comparison Operators
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*
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:
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
& 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
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.
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
142 143
11 Numeric Data Types 11.6 Boolean Values: bool
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
Table 11.6 Logical Operators of the bool Data Type False False False
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:
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
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
>>> 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
>>> 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
7
Contents Contents
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.2 The Online Documentation ............................................................................................... 120 12 Sequential Data Types 153
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
14 Collections 239
12 13
Contents Contents
14 15
Contents Contents
16 17
Contents Contents
18 19
Contents Contents
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
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
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
26 27
Contents Contents
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
30 31
Index
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
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
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!
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.