Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: Python Programming full Tutorial with Exercises
Description: Here you can find the full python course and there is also exercises, examples that make your study more easier and enjoyable.

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Python Tutorial
Release 3
...
0

Guido van Rossum
and the Python development team

September 02, 2018

Python Software Foundation
Email: docs@python
...
1 Invoking the Interpreter
...
2 The Interpreter and Its Environment
...
1 Using Python as a Calculator
...
2 First Steps Towards Programming
...
1 if Statements
...
2 for Statements
...
3 The range() Function
...
4 break and continue Statements, and else
4
...

4
...

4
...

4
...



...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...
1 More on Lists
...
2 The del statement
...
3 Tuples and Sequences
...
4 Sets
...
5 Dictionaries
...
6 Looping Techniques
...
7 More on Conditions
...
8 Comparing Sequences and Other


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...
1 More on Modules
...
2 Standard Modules
...
3 The dir() Function
6
...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...


43
44
46
47
48


...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...


7 Input and Output
53
7
...
53
7
...
57
8 Errors and Exceptions

61
i

8
...
2
8
...
4
8
...
6
8
...

Exceptions
...

Raising Exceptions
...

Defining Clean-up Actions
...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...


...


...


...



...


...


...


...
1 A Word About Names and Objects
9
...

9
...

9
...

9
...

9
...

9
...

9
...

9
...

9
...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...



...


...


...


...


...


69
69
69
72
75
77
78
79
79
80
81

10 Brief Tour of the Standard Library
10
...

10
...

10
...

10
...
5 String Pattern Matching
...
6 Mathematics
...
7 Internet Access
...
8 Dates and Times
...
9 Data Compression
...
10 Performance Measurement
...
11 Quality Control
...
12 Batteries Included
...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...
1 Output Formatting
...
2 Templating
...
3 Working with Binary Data Record Layouts
...
4 Multi-threading
...
5 Logging
...
6 Weak References
...
7 Tools for Working with Lists
...
8 Decimal Floating Point Arithmetic
...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...
1 Introduction
...
2 Creating Virtual Environments
...
3 Managing Packages with pip
...
1 Tab Completion and History Editing
...
2 Alternatives to the Interactive Interpreter
...
1 Representation Error
...
1 Interactive Mode
...
1 Contributors to the Python Documentation
...
1 History of the software
...
2 Terms and conditions for accessing or otherwise using Python
...
3 Licenses and Acknowledgements for Incorporated Software
...
7
...
It has efficient high-level data structures and
a simple but effective approach to object-oriented programming
...

The Python interpreter and the extensive standard library are freely available in source or binary form for all
major platforms from the Python Web site, https://www
...
org/, and may be freely distributed
...

The Python interpreter is easily extended with new functions and data types implemented in C or C++
(or other languages callable from C)
...

This tutorial introduces the reader informally to the basic concepts and features of the Python language
and system
...

For a description of standard objects and modules, see library-index
...
To write extensions in C or C++, read extending-index and c-api-index
...

This tutorial does not attempt to be comprehensive and cover every single feature, or even every commonly
used feature
...
After reading it, you will be able to read and write Python modules
and programs, and you will be ready to learn more about the various Python library modules described in
library-index
...


CONTENTS

1

Python Tutorial, Release 3
...
0

2

CONTENTS

CHAPTER

ONE

WHETTING YOUR APPETITE

If you do much work on computers, eventually you find that there’s some task you’d like to automate
...
Perhaps you’d like to write a small custom database,
or a specialized GUI application, or a simple game
...
Perhaps you’re writing a test suite for such
a library and find writing the testing code a tedious task
...

Python is just the language for you
...
You could
write a C/C++/Java program, but it can take a lot of development time to get even a first-draft program
...

Python is simple to use, but it is a real programming language, offering much more structure and support
for large programs than shell scripts or batch files can offer
...
Because of its more general data types Python is applicable to a much
larger problem domain than Awk or even Perl, yet many things are at least as easy in Python as in those
languages
...
It
comes with a large collection of standard modules that you can use as the basis of your programs — or as
examples to start learning to program in Python
...

Python is an interpreted language, which can save you considerable time during program development
because no compilation and linking is necessary
...
It is also a handy desk calculator
...
Programs written in Python are typically
much shorter than equivalent C, C++, or Java programs, for several reasons:
• the high-level data types allow you to express complex operations in a single statement;
• statement grouping is done by indentation instead of beginning and ending brackets;
• no variable or argument declarations are necessary
...
Once you
3

Python Tutorial, Release 3
...
0

are really hooked, you can link the Python interpreter into an application written in C and use it as an
extension or command language for that application
...
Making references to Monty Python skits in documentation is not only allowed, it is
encouraged!
Now that you are all excited about Python, you’ll want to examine it in some more detail
...

In the next chapter, the mechanics of using the interpreter are explained
...

The rest of the tutorial introduces various features of the Python language and system through examples,
beginning with simple expressions, statements and data types, through functions and modules, and finally
touching upon advanced concepts like exceptions and user-defined classes
...
Whetting Your Appetite

CHAPTER

TWO

USING THE PYTHON INTERPRETER

2
...
7 on those machines where it is
available; putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing
the command:
python3
...
1 Since the choice of the directory where the interpreter lives is an installation option, other
places are possible; check with your local Python guru or system administrator
...
g
...
)
On Windows machines, the Python installation is usually placed in C:\Program Files\Python37\, though
you can change this when you’re running the installer
...
If that doesn’t work, you can exit the interpreter by typing
the following command: quit()
...
Perhaps the quickest check to see whether command line editing is
supported is typing Control-P to the first Python prompt you get
...
If
nothing appears to happen, or if ^P is echoed, command line editing isn’t available; you’ll only be able to
use backspace to remove characters from the current line
...

A second way of starting the interpreter is python -c command [arg]
...
Since Python statements often contain spaces or other
characters that are special to the shell, it is usually advised to quote command in its entirety with single
quotes
...
These can be invoked using python -m module [arg]
...

When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode
afterwards
...

1

On Unix, the Python 3
...
x executable
...
7
...


2
...
1 Argument Passing
When known to the interpreter, the script name and additional arguments thereafter are turned into a list
of strings and assigned to the argv variable in the sys module
...
The length of the list is at least one; when no script and no arguments are given, sys
...
When the script name is given as '-' (meaning standard input), sys
...

When -c command is used, sys
...
When -m module is used, sys
...
Options found after -c command or -m module are not consumed by
the Python interpreter’s option processing but left in sys
...


2
...
2 Interactive Mode
When commands are read from a tty, the interpreter is said to be in interactive mode
...
The interpreter prints a welcome message
stating its version number and a copyright notice before printing the first prompt:
$ python3
...
7 (default, Sep 16 2015, 09:25:04)
[GCC 4
...
2] on linux
Type "help", "copyright", "credits" or "license" for more information
...
As an example, take a look at this if
statement:
>>> the_world_is_flat = True
>>> if the_world_is_flat:

...

Be careful not to fall off!

For more on interactive mode, see Interactive Mode
...
2 The Interpreter and Its Environment
2
...
1 Source Code Encoding
By default, Python source files are treated as encoded in UTF-8
...
To display all these characters properly, your editor must recognize that the file is UTF-8, and it
must use a font that supports all the characters in the file
...
The syntax is as follows:
# -*- coding: encoding -*-

where encoding is one of the valid codecs supported by Python
...
Using the Python Interpreter

Python Tutorial, Release 3
...
0

For example, to declare that Windows-1252 encoding is to be used, the first line of your source code file
should be:
# -*- coding: cp1252 -*-

One exception to the first line rule is when the source code starts with a UNIX “shebang” line
...
For example:
#!/usr/bin/env python3
# -*- coding: cp1252 -*-

2
...
The Interpreter and Its Environment

7

Python Tutorial, Release 3
...
0

8

Chapter 2
...
Note that a secondary prompt on a line
by itself in an example means you must type a blank line; this is used to end a multi-line command
...

Comments in Python start with the hash character, #, and extend to the end of the physical line
...

A hash character within a string literal is just a hash character
...

Some examples:
# this is the first comment
spam = 1 # and this is the second comment
#
...
"

3
...
Start the interpreter and wait for the primary prompt, >>>
...
)

3
...
1 Numbers
The interpreter acts as a simple calculator: you can type an expression at it and it will write the value
...
For example:
>>>
4
>>>
20
>>>
5
...
6

2 + 2
50 - 5*6
(50 - 5*6) / 4
8 / 5

# division always returns a floating point number

The integer numbers (e
...
2, 4, 20) have type int, the ones with a fractional part (e
...
5
...
6) have type
float
...


9

Python Tutorial, Release 3
...
0

Division (/) always returns a float
...
666666666666667
>>>
>>> 17 // 3 # floor division discards the fractional part
5
>>> 17 % 3 # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2 # result * divisor + remainder
17

With Python, it is possible to use the ** operator to calculate powers1 :
>>> 5 ** 2
25
>>> 2 ** 7
128

# 5 squared
# 2 to the power of 7

The equal sign (=) is used to assign a value to a variable
...
75 - 1
14
...
This means that when you are
using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>> tax = 12
...
50
>>> price * tax
12
...
0625
>>> round(_, 2)
113
...
Don’t explicitly assign a value to it — you
would create an independent local variable with the same name masking the built-in variable with its magic
behavior
...
To avoid this and get
9, you can use (-3)**2
...
An Informal Introduction to Python

Python Tutorial, Release 3
...
0

In addition to int and float, Python supports other types of numbers, such as Decimal and Fraction
...
g
...


3
...
2 Strings
Besides numbers, Python can also manipulate strings, which can be expressed in several ways
...
') or double quotes ("
...
\ can be used to escape
quotes:
>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote
...
or use double quotes instead
"doesn't"
>>> '"Yes," they said
...
'
>>> "\"Yes,\" they said
...
'
>>> '"Isn\'t," they said
...
'

In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with
backslashes
...
The string is enclosed in double quotes if the string contains a single quote
and no double quotes, otherwise it is enclosed in single quotes
...
'
'"Isn\'t," they said
...
')
"Isn't," they said
...
\nSecond line
...
\nSecond line
...

Second line
...
One way is using triple-quotes: """
...
End of
lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of
the line
...
') and double ("
...
The only difference between the two is that within single quotes you don’t need to escape " (but you have to escape
\') and vice versa
...
1
...
7
...
e
...

>>> 'Py' 'thon'
'Python'

This feature is particularly useful when you want to break long strings:
>>> text = ('Put several strings within parentheses '

...
')
>>> text
'Put several strings within parentheses to have them joined together
...

SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'

...
There is no separate character
type; a character is simply a string of size one:
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
>>> word[5] # character in position 5
'n'

Indices may also be negative numbers, to start counting from the right:

12

Chapter 3
...
7
...

In addition to indexing, slicing is also supported
...
This makes sure that s[:i] + s[i:]
is always equal to s:
>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults
to the size of the string being sliced
...
Then the right edge of the last character of a string of n characters
has index n, for example:
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0
1
2
3
4
5
6
-6 -5 -4 -3 -2 -1

The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the
corresponding negative indices
...

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds
...

Attempting to use an index that is too large will result in an error:
>>> word[42] # the word only has 6 characters
Traceback (most recent call last):
File "", line 1, in
IndexError: string index out of range

3
...
Using Python as a Calculator

13

Python Tutorial, Release 3
...
0

However, out of range slice indexes are handled gracefully when used for slicing:
>>> word[4:42]
'on'
>>> word[42:]
''

Python strings cannot be changed — they are immutable
...

TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'

...

string-methods Strings support a large number of methods for basic transformations and searching
...

formatstrings Information about string formatting with str
...

old-string-formatting The old formatting operations invoked when strings are the left operand of the %
operator are described in more detail here
...
1
...
The most versatile
is the list, which can be written as a list of comma-separated values (items) between square brackets
...

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

Like strings (and all other built-in sequence type), lists can be indexed and sliced:
>>> squares[0] # indexing returns the item
1
>>> squares[-1]
(continues on next page)

14

Chapter 3
...
7
...
This means that the following slice
returns a new (shallow) copy of the list:
>>> squares[:]
[1, 4, 9, 16, 25]

Lists also support operations like concatenation:
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike strings, which are immutable, lists are a mutable type, i
...
it is possible to change their content:
>>>
>>>
64
>>>
>>>
[1,

cubes = [1, 8, 27, 65, 125] # something's wrong here
4 ** 3 # the cube of 4 is 64, not 65!
cubes[3] = 64 # replace the wrong value
cubes
8, 27, 64, 125]

You can also add new items at the end of the list, by using the append() method (we will see more about
methods later):
>>>
>>>
>>>
[1,

cubes
...
append(7 ** 3) # and the cube of 7
cubes
8, 27, 64, 125, 216, 343]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

The built-in function len() also applies to lists:
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

It is possible to nest lists (create lists containing other lists), for example:

3
...
Using Python as a Calculator

15

Python Tutorial, Release 3
...
0

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3
...
For instance,
we can write an initial sub-sequence of the Fibonacci series as follows:
>>>

...

>>>

...


...

• The first line contains a multiple assignment: the variables a and b simultaneously get the new values
0 and 1
...
The right-hand side expressions are
evaluated from the left to the right
...
In Python, like in C,
any non-zero integer value is true; zero is false
...
The test used
in the example is a simple comparison
...

• The body of the loop is indented: indentation is Python’s way of grouping statements
...
In practice you will prepare more
complicated input for Python with a text editor; all decent text editors have an auto-indent facility
...
Note that each line
within a basic block must be indented by the same amount
...
It differs from just writing
the expression you want to write (as we did earlier in the calculator examples) in the way it handles
multiple arguments, floating point quantities, and strings
...
An Informal Introduction to Python

Python Tutorial, Release 3
...
0

>>> i = 256*256
>>> print('The value of i is', i)
The value of i is 65536

The keyword argument end can be used to avoid the newline after the output, or end the output with
a different string:
>>> a, b = 0, 1
>>> while a < 1000:

...

a, b = b, a+b

...
2
...
7
...
An Informal Introduction to Python

CHAPTER

FOUR

MORE CONTROL FLOW TOOLS

Besides the while statement just introduced, Python knows the usual control flow statements known from
other languages, with some twists
...
1 if Statements
Perhaps the most well-known statement type is the if statement
...

x = 0

...
elif x == 0:

...
elif x == 1:

...
else:

...

More

There can be zero or more elif parts, and the else part is optional
...
An if … elif … elif … sequence is a substitute for the
switch or case statements found in other languages
...
2 for Statements
The for statement in Python differs a bit from what you may be used to in C or Pascal
...
For example (no pun intended):
>>> # Measure some strings:

...

print(w, len(w))

...
7
...
Iterating over a sequence does not implicitly
make a copy
...


...

words
...

>>> words
['defenestrate', 'cat', 'window', 'defenestrate']

With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over
and over again
...
3 The range() Function
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy
...

print(i)

...
It is possible to let the range start at another number, or to specify a
different increment (even negative; sometimes this is called the ‘step’):
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70

To iterate over the indices of a sequence, you can combine range() and len() as follows:
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):

...

0 Mary
1 had
2 a
3 little
4 lamb

In most such cases, however, it is convenient to use the enumerate() function, see Looping Techniques
...
More Control Flow Tools

Python Tutorial, Release 3
...
0

>>> print(range(10))
range(0, 10)

In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t
...

We say such an object is iterable, that is, suitable as a target for functions and constructs that expect
something from which they can obtain successive items until the supply is exhausted
...
The function list() is another; it creates lists from iterables:
>>> list(range(5))
[0, 1, 2, 3, 4]

Later we will see more functions that return iterables and take iterables as argument
...
4 break and continue Statements, and else Clauses on Loops
The break statement, like in C, breaks out of the innermost enclosing for or while loop
...
This is exemplified by the following loop, which searches for prime numbers:
>>> for n in range(2, 10):

...

if n % x == 0:

...

break

...

# loop fell through without finding a factor

...

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(Yes, this is the correct code
...
)
When used with a loop, the else clause has more in common with the else clause of a try statement than it
does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else
clause runs when no break occurs
...

The continue statement, also borrowed from C, continues with the next iteration of the loop:
>>> for num in range(2, 10):

...

print("Found an even number", num)

...

print("Found a number", num)
Found an even number 2
(continues on next page)

4
...
break and continue Statements, and else Clauses on Loops

21

Python Tutorial, Release 3
...
0

(continued from previous page)

Found
Found
Found
Found
Found
Found
Found

a number 3
an even number 4
a number 5
an even number 6
a number 7
an even number 8
a number 9

4
...
It can be used when a statement is required syntactically but the program
requires no action
...

pass # Busy-wait for keyboard interrupt (Ctrl+C)

...

pass

...
The pass is silently ignored:
>>> def initlog(*args):

...


4
...


...


...


...

>>>

...
"""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
# Now call the function we just defined:
fib(2000)
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

The keyword def introduces a function definition
...
The statements that form the body of the function start at the next
line, and must be indented
...
(More about docstrings can be found in the section Documentation

22

Chapter 4
...
7
...
) There are tools which use docstrings to automatically produce online or printed documentation,
or to let the user interactively browse through code; it’s good practice to include docstrings in code that you
write, so make a habit of it
...
More
precisely, all variable assignments in a function store the value in the local symbol table; whereas variable
references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in
the global symbol table, and finally in the table of built-in names
...

The actual parameters (arguments) to a function call are introduced in the local symbol table of the called
function when it is called; thus, arguments are passed using call by value (where the value is always an object
reference, not the value of the object)
...

A function definition introduces the function name in the current symbol table
...
This value can be assigned
to another name which can then also be used as a function
...
In fact, even functions without a return statement do return a value, albeit a rather boring
one
...
Writing the value None is normally suppressed by the
interpreter if it would be the only value written
...


...


...


...


...
"""
result = []
a, b = 0, 1
while a < n:
result
...
return without an expression argument
returns None
...

• The statement result
...
A method is a function
that ‘belongs’ to an object and is named obj
...


4
...
Defining Functions

23

Python Tutorial, Release 3
...
0

expression), and methodname is the name of a method that is defined by the object’s type
...
Methods of different types may have the same name without causing
ambiguity
...
In this example it is equivalent to result = result + [a], but more efficient
...
7 More on Defining Functions
It is also possible to define functions with a variable number of arguments
...


4
...
1 Default Argument Values
The most useful form is to specify a default value for one or more arguments
...
For example:
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)

This function can be called in several ways:
• giving only the mandatory argument: ask_ok('Do you really want to quit?')
• giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)
• or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or
no!')
This example also introduces the in keyword
...

The default values are evaluated at the point of function definition in the defining scope, so that
i = 5
def f(arg=i):
print(arg)
i = 6
f()

will print 5
...
This makes a difference when the default is
a mutable object such as a list, dictionary, or instances of most classes
...
More Control Flow Tools

Python Tutorial, Release 3
...
0

def f(a, L=[]):
L
...
append(a)
return L

4
...
2 Keyword Arguments
Functions can also be called using keyword arguments of the form kwarg=value
...
")
print("-- Lovely plumage, the", type)
print("-- It's", state, "!")

accepts one required argument (voltage) and three optional arguments (state, action, and type)
...
0, 'dead')
parrot(110, voltage=220)
parrot(actor='John Cleese')

#
#
#
#

required argument missing
non-keyword argument after a keyword argument
duplicate value for the same argument
unknown keyword argument

In a function call, keyword arguments must follow positional arguments
...
g
...
This also includes non-optional arguments (e
...

parrot(voltage=1000) is valid too)
...
Here’s an example
that fails due to this restriction:

4
...
More on Defining Functions

25

Python Tutorial, Release 3
...
0

>>> def function(a):

...

>>> function(0, a=0)
Traceback (most recent call last):
File "", line 1, in
TypeError: function() got multiple values for keyword argument 'a'

When a final formal parameter of the form **name is present, it receives a dictionary (see typesmapping)
containing all keyword arguments except for those corresponding to a formal parameter
...
(*name must occur before
**name
...
",
"It's really very, VERY runny, sir
...

It's really very, VERY runny, sir
...


4
...
3 Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number
of arguments
...
Before the
variable number of arguments, zero or more normal arguments may occur
...
write(separator
...
Any formal parameters which occur after

26

Chapter 4
...
7
...

>>> def concat(*args, sep="/"):

...
join(args)

...
")
'earth
...
venus'

4
...
4 Unpacking Argument Lists
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for
a function call requiring separate positional arguments
...
If they are not available separately, write the function call with the
*-operator to unpack the arguments out of a list or tuple:
>>>
[3,
>>>
>>>
[3,

list(range(3, 6))
4, 5]
args = [3, 6]
list(range(*args))
4, 5]

# normal call with separate arguments

# call with arguments unpacked from a list

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:
>>> def parrot(voltage, state='a stiff', action='voom'):

...

print("if you put", voltage, "volts through it
...

print("E's", state, "!")

...
E's bleedin' demised !

4
...
5 Lambda Expressions
Small anonymous functions can be created with the lambda keyword
...
Lambda functions can be used wherever function objects are required
...
Semantically, they are just syntactic sugar for a
normal function definition
...


...
Another use is to pass a small function
as an argument:

4
...
More on Defining Functions

27

Python Tutorial, Release 3
...
0

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs
...
7
...

The first line should always be a short, concise summary of the object’s purpose
...
This line should begin with a capital letter and end
with a period
...
The following lines should be one or more paragraphs describing
the object’s calling conventions, its side effects, etc
...
This is done using the following convention
...
(We can’t use the first line since it is generally adjacent to the string’s opening quotes
so its indentation is not apparent in the string literal
...
Lines that are indented less should not occur, but if they
occur all their leading whitespace should be stripped
...

Here is an example of a multi-line docstring:
>>> def my_function():

...


...

No, really, it doesn't do anything
...

"""

...

>>> print(my_function
...

No, really, it doesn't do anything
...
7
...

Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect
on any other part of the function
...
Return annotations are defined by a
literal ->, followed by an expression, between the parameter list and the colon denoting the end of the def
statement
...

print("Annotations:", f
...
More Control Flow Tools

Python Tutorial, Release 3
...
0

(continued from previous page)


...

return ham + ' and ' + eggs

...
8 Intermezzo: Coding Style
Now that you are about to write longer, more complex pieces of Python, it is a good time to talk about
coding style
...
Making it easy for others to read your code is always a good idea, and adopting a nice
coding style helps tremendously for that
...
Every Python developer should read it at some point; here are the
most important points extracted for you:
• Use 4-space indentation, and no tabs
...
Tabs introduce confusion, and are best left out
...

This helps users with small displays and makes it possible to have several code files side-by-side on
larger displays
...

• When possible, put comments on a line of their own
...

• Use spaces around operators and after commas, but not directly inside bracketing constructs: a =
f(1, 2) + g(3, 4)
...
Always use self as the name for the first
method argument (see A First Look at Classes for more on classes and methods)
...
Python’s
default, UTF-8, or even plain ASCII work best in any case
...


4
...
Intermezzo: Coding Style

29

Python Tutorial, Release 3
...
0

30

Chapter 4
...


5
...
Here are all of the methods of list objects:
list
...
Equivalent to a[len(a):] = [x]
...
extend(iterable)
Extend the list by appending all the items from the iterable
...

list
...
The first argument is the index of the element before which to
insert, so a
...
insert(len(a), x) is equivalent to
a
...

list
...
It raises a ValueError if there is no such
item
...
pop([i ])
Remove the item at the given position in the list, and return it
...
pop() removes
and returns the last item in the list
...
You will see
this notation frequently in the Python Library Reference
...
clear()
Remove all items from the list
...

list
...
Raises a ValueError if
there is no such item
...
The returned index is computed relative to the beginning
of the full sequence rather than the start argument
...
count(x)
Return the number of times x appears in the list
...
sort(key=None, reverse=False)
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for
their explanation)
...
7
...
reverse()
Reverse the elements of the list in place
...
copy()
Return a shallow copy of the list
...

An example that uses most of the list methods:
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits
...
count('tangerine')
0
>>> fruits
...
index('banana', 4) # Find next banana starting a position 4
6
>>> fruits
...
append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits
...
pop()
'pear'

You might have noticed that methods like insert, remove or sort that only modify the list have no return
value printed – they return the default None
...


5
...
1 Using Lists as Stacks
The list methods make it very easy to use a list as a stack, where the last element added is the first element
retrieved (“last-in, first-out”)
...
To retrieve an item
from the top of the stack, use pop() without an explicit index
...
append(6)
stack
...
pop()
stack
4, 5, 6]
stack
...
pop()
stack
4]

1 Other
languages
may
return
d->insert("a")->remove("b")->sort();
...
Data Structures

Python Tutorial, Release 3
...
0

5
...
2 Using Lists as Queues
It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in,
first-out”); however, lists are not efficient for this purpose
...

To implement a queue, use collections
...
For example:
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue
...
append("Graham")
# Graham arrives
>>> queue
...
popleft()
# The second to arrive now leaves
'John'
>>> queue
# Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

5
...
3 List Comprehensions
List comprehensions provide a concise way to create lists
...

For example, assume we want to create a list of squares, like:
>>>
>>>

...

>>>
[0,

squares = []
for x in range(10):
squares
...
We can
calculate the list of squares without any side effects using:
squares = list(map(lambda x: x**2, range(10)))

or, equivalently:
squares = [x**2 for x in range(10)]

which is more concise and readable
...
The result will be a new list resulting from evaluating the expression in the context
of the for and if clauses which follow it
...
1
...
7
...

for y in [3,1,4]:

...

combs
...

>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note how the order of the for and if statements is the same in both these snippets
...
g
...

>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon
...
1', '3
...
142', '3
...
14159']

5
...
4 Nested List Comprehensions
The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension
...

[1, 2, 3, 4],

...
Data Structures

Python Tutorial, Release 3
...
0

(continued from previous page)


...
]

[9, 10, 11, 12],

The following list comprehension will transpose rows and columns:
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it,
so this example is equivalent to:
>>> transposed = []
>>> for i in range(4):

...
append([row[i] for row in matrix])

...

# the following 3 lines implement the nested listcomp

...

for row in matrix:

...
append(row[i])

...
append(transposed_row)

...
The zip() function would
do a great job for this use case:
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

See Unpacking Argument Lists for details on the asterisk in this line
...
2 The del statement
There is a way to remove an item from a list given its index instead of its value: the del statement
...
The del statement can also be used to remove slices
from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice)
...
25, 333, 333, 1234
...
25, 333, 333, 1234
...
25, 1234
...
2
...
7
...
We’ll find other
uses for del later
...
3 Tuples and Sequences
We saw that lists and strings have many common properties, such as indexing and slicing operations
...
Since Python is an evolving language, other sequence
data types may be added
...

A tuple consists of a number of values separated by commas, for instance:
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:

...
t[0] = 88888
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> # but they can contain mutable objects:

...
It is not possible to assign to the individual
items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists
...

Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via
unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples)
...

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to
accommodate these
...

Ugly, but effective
...
Data Structures

Python Tutorial, Release 3
...
0

(continued from previous page)

0
>>> len(singleton)
1
>>> singleton
('hello',)

The statement t = 12345, 54321, 'hello!' is an example of tuple packing: the values 12345, 54321 and
'hello!' are packed together in a tuple
...

Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are
elements in the sequence
...


5
...
A set is an unordered collection with no duplicate elements
...
Set objects also support mathematical
operations like union, intersection, difference, and symmetric difference
...
Note: to create an empty set you have to use
set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section
...

>>> a
>>> b
>>> a
{'a',
>>> a
{'r',
>>> a
{'a',
>>> a
{'a',
>>> a
{'r',

Demonstrate set operations on unique letters from two words
= set('abracadabra')
= set('alacazam')
# unique letters in a
'r',
- b
'd',
| b
'c',
& b
'c'}
^ b
'd',

'b', 'c', 'd'}
# letters in a but not in b
'b'}
# letters in a or b or both
'r', 'd', 'b', 'm', 'z', 'l'}
# letters in both a and b
# letters in a or b but not both
'b', 'm', 'z', 'l'}

Similarly to list comprehensions, set comprehensions are also supported:
>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

5
...
Sets

37

Python Tutorial, Release 3
...
0

5
...
Dictionaries are sometimes
found in other languages as “associative memories” or “associative arrays”
...
Tuples can be used as keys if they contain only strings, numbers, or tuples;
if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key
...

It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique
(within one dictionary)
...
Placing a comma-separated
list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way
dictionaries are written on output
...
It is also possible to delete a key:value pair with del
...
It is an error to extract a value using a non-existent key
...
To check whether a single key is in the dictionary, use
the in keyword
...
Data Structures

Python Tutorial, Release 3
...
0

5
...

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights
...

print(k, v)

...

>>> for i, v in enumerate(['tic', 'tac', 'toe']):

...

0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip() function
...

print('What is your {0}? It is {1}
...

What is your name? It is lancelot
...

What is your favorite color? It is blue
...

>>> for i in reversed(range(1, 10, 2)):

...

9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while
leaving the source unaltered
...

print(f)

...
6
...
7
...

>>> import math
>>> raw_data = [56
...
7, 55
...
5, float('NaN'), 47
...

if not math
...

filtered_data
...

>>> filtered_data
[56
...
7, 55
...
5, 47
...
7 More on Conditions
The conditions used in while and if statements can contain any operators, not just comparisons
...
The
operators is and is not compare whether two objects are really the same object; this only matters for
mutable objects like lists
...

Comparisons can be chained
...

Comparisons may be combined using the Boolean operators and and or, and the outcome of a comparison
(or of any other Boolean expression) may be negated with not
...
As always, parentheses can be used to express the desired composition
...
For example, if A and C are true
but B is false, A and B and C does not evaluate the expression C
...

It is possible to assign the result of a comparison or other Boolean expression to a variable
...
C programmers may grumble
about this, but it avoids a common class of problems encountered in C programs: typing = in an expression
when == was intended
...
8 Comparing Sequences and Other Types
Sequence objects may be compared to other objects with the same sequence type
...
If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively
...
If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser)

40

Chapter 5
...
7
...
Lexicographical ordering for strings uses the Unicode code point number to order individual characters
...
0, 2
...
0)
< (1, 2, ('abc', 'a'), 4)
(1, 2, ('aa', 'ab'))

Note that comparing objects of different types with < or > is legal provided that the objects have appropriate
comparison methods
...
0, etc
...


5
...
Comparing Sequences and Other Types

41

Python Tutorial, Release 3
...
0

42

Chapter 5
...
Therefore, if you want to write a somewhat longer program, you are better off using a
text editor to prepare the input for the interpreter and running it with that file as input instead
...
As your program gets longer, you may want to split it into several files for easier
maintenance
...

To support this, Python has a way to put definitions in a file and use them in a script or in an interactive
instance of the interpreter
...

A module is a file containing Python definitions and statements
...
py appended
...
For instance, use your favorite text editor to create a file called fibo
...
append(a)
a, b = b, a+b
return result

Now enter the Python interpreter and import this module with the following command:
>>> import fibo

This does not enter the names of the functions defined in fibo directly in the current symbol table; it only
enters the module name fibo there
...
fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo
...
7
...
__name__
'fibo'

If you intend to use a function often you can assign it to a local name:
>>> fib = fibo
...
1 More on Modules
A module can contain executable statements as well as function definitions
...
They are executed only the first time the module name is encountered in an import
statement
...
)
Each module has its own private symbol table, which is used as the global symbol table by all functions
defined in the module
...
On the other hand, if you know what you
are doing you can touch a module’s global variables with the same notation used to refer to its functions,
modname
...

Modules can import other modules
...
The imported module names are placed in the importing
module’s global symbol table
...
For example:
>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol table (so in
the example, fibo is not defined)
...
In most cases Python programmers
do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some
things you have already defined
...
However, it is okay to use it to save typing in interactive sessions
...

>>> import fibo as fib
>>> fib
...


44

Chapter 6
...
7
...

It can also be used when utilising from with similar effects:
>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Note: For efficiency reasons, each module is only imported once per interpreter session
...
reload(), e
...
import importlib; importlib
...


6
...
1 Executing modules as scripts
When you run a Python module with
python fibo
...

That means that by adding this code at the end of your module:
if __name__ == "__main__":
import sys
fib(int(sys
...
py 50
0 1 1 2 3 5 8 13 21 34

If the module is imported, the code is not run:
>>> import fibo
>>>

This is often used either to provide a convenient user interface to a module, or for testing purposes (running
the module as a script executes a test suite)
...
1
...

If not found, it then searches for a file named spam
...
path
...
path is initialized from these locations:
• The directory containing the input script (or the current directory when no file is specified)
...

• The installation-dependent default
...
In other words the directory containing the symlink is not added to the module

6
...
More on Modules

45

Python Tutorial, Release 3
...
0

search path
...
path
...
This means that scripts in
that directory will be loaded instead of modules of the same name in the library directory
...
See section Standard Modules for more information
...
1
...
version
...
For example, in CPython release 3
...
py would be cached as __pycache__/spam
...
pyc
...

Python checks the modification date of the source against the compiled version to see if it’s out of date
and needs to be recompiled
...
Also, the compiled modules are
platform-independent, so the same library can be shared among systems with different architectures
...
First, it always recompiles and does not store the
result for the module that’s loaded directly from the command line
...
To support a non-source (compiled only) distribution, the compiled module must
be in the source directory, and there must not be a source module
...

The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__
strings
...
“Optimized” modules have an opt- tag and are usually smaller
...

• A program doesn’t run any faster when it is read from a
...
py file;
the only thing that’s faster about
...

• The module compileall can create
...

• There is more detail on this process, including a flow chart of the decisions, in PEP 3147
...
2 Standard Modules
Python comes with a library of standard modules, described in a separate document, the Python Library
Reference (“Library Reference” hereafter)
...
The set of such modules is a
configuration option which also depends on the underlying platform
...
One particular module deserves some attention: sys, which is built
into every Python interpreter
...
ps1 and sys
...
ps1
'>>> '
>>> sys
...
'
(continues on next page)

46

Chapter 6
...
7
...
ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>

These two variables are only defined if the interpreter is in interactive mode
...
path is a list of strings that determines the interpreter’s search path for modules
...
You can modify it using standard list operations:
>>> import sys
>>> sys
...
append('/ufs/guido/lib/python')

6
...
It returns a sorted list of
strings:
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
'__package__', '__stderr__', '__stdin__', '__stdout__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
'_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
'call_tracing', 'callstats', 'copyright', 'displayhook',
'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
'thread_info', 'version', 'version_info', 'warnoptions']

Without arguments, dir() lists the names you have defined currently:
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo
...

dir() does not list the names of built-in functions and variables
...
3
...
7
...
4 Packages
Packages are a way of structuring Python’s module namespace by using “dotted module names”
...
B designates a submodule named B in a package named A
...

Suppose you want to design a collection of modules (a “package”) for the uniform handling of sound files and
sound data
...
wav,
...
au), so you may need to create and maintain a growing collection of modules for the conversion
between the various file formats
...
Here’s a
possible structure for your package (expressed in terms of a hierarchical filesystem):
sound/
__init__
...
py
wavread
...
py

Top-level package
Initialize the sound package
Subpackage for file format conversions

(continues on next page)

48

Chapter 6
...
7
...
py
aiffwrite
...
py
auwrite
...

effects/

Subpackage for sound effects
__init__
...
py
surround
...
py

...
py
equalizer
...
py
karaoke
...


When importing the package, Python searches through the directories on sys
...

The __init__
...
In the simplest case, __init__
...

Users of the package can import individual modules from the package, for example:
import sound
...
echo

This loads the submodule sound
...
echo
...

sound
...
echo
...
7, atten=4)

An alternative way of importing the submodule is:
from sound
...
echofilter(input, output, delay=0
...
effects
...
7, atten=4)

Note that when using from package import item, the item can be either a submodule (or subpackage)
of the package, or some other name defined in the package, like a function, class or variable
...
If it fails to find it, an ImportError exception is raised
...
subitem
...
4
...
7
...


6
...
1 Importing * From a Package
Now what happens when the user writes from sound
...
This could take a long time and importing sub-modules might have unwanted side-effects that should
only happen when the sub-module is explicitly imported
...
The import statement
uses the following convention: if a package’s __init__
...
It is up
to the package author to keep this list up-to-date when a new version of the package is released
...
For
example, the file sound/effects/__init__
...
effects import * would import the three named submodules of the
sound package
...
effects import * does not import all submodules from
the package sound
...
effects
has been imported (possibly running any initialization code in __init__
...
This includes any names defined (and submodules explicitly loaded) by
__init__
...
It also includes any submodules of the package that were explicitly loaded by previous import
statements
...
effects
...
effects
...
effects import *

In this example, the echo and surround modules are imported in the current namespace because they are
defined in the sound
...
import statement is executed
...
)
Although certain modules are designed to export only names that follow certain patterns when you use
import *, it is still considered bad practice in production code
...


6
...
2 Intra-package References
When packages are structured into subpackages (as with the sound package in the example), you can use
absolute imports to refer to submodules of siblings packages
...
filters
...
effects package, it can use from sound
...

You can also write relative imports, with the from module import name form of import statement
...
From
the surround module for example, you might use:

50

Chapter 6
...
7
...
import echo
from
...
filters import equalizer

Note that relative imports are based on the name of the current module
...


6
...
3 Packages in Multiple Directories
Packages support one more special attribute, __path__
...
py before the code in that file is executed
...

While this feature is not often needed, it can be used to extend the set of modules found in a package
...
4
...
7
...
Modules

CHAPTER

SEVEN

INPUT AND OUTPUT

There are several ways to present the output of a program; data can be printed in a human-readable form,
or written to a file for future use
...


7
...

(A third way is using the write() method of file objects; the standard output file can be referenced as
sys
...
See the Library Reference for more information on this
...
There are several ways to format output
...
Inside this string, you can write a Python expression between { and } characters that
can refer to variables or literal values
...
format() method of strings requires more manual effort
...

>>> yes_votes = 42_572_654 ; no_votes = 43_132_495
>>> percentage = yes_votes/(yes_votes+no_votes)
>>> '{:-9} YES votes {:2
...
format(yes_votes, percentage)
' 42572654 YES votes 49
...
The string type has some methods that perform useful operations
for padding strings to a given column width
...

The str() function is meant to return representations of values which are fairly human-readable, while
repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError
if there is no equivalent syntax)
...
Many values, such as numbers or structures like lists
and dictionaries, have the same representation using either function
...

Some examples:
53

Python Tutorial, Release 3
...
0

>>> s = 'Hello, world
...
'
>>> repr(s)
"'Hello, world
...
14285714285714285'
>>> x = 10 * 3
...
'
>>> print(s)
The value of x is 32
...

>>> # The repr() of a string adds string quotes and backslashes:

...
repr((x, y, ('spam', 'eggs')))
"(32
...


7
...
1 Formatted String Literals
Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside
a string by prefixing the string with f or F and writing expressions as {expression}
...
This allows greater control over how the value is
formatted
...
pi:
...
')

Passing an integer after the ':' will cause that field to be a minimum number of characters wide
...

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table
...

print(f'{name:10} ==> {phone:10d}')

...
'!a' applies ascii(), '!s' applies
str(), and '!r' applies repr():
>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}
...

>>> print('My hovercraft is full of {animals !r}
...


For a reference on these format specifications, see the reference guide for the formatspec
...
Input and Output

Python Tutorial, Release 3
...
0

7
...
2 The String format() Method
Basic usage of the str
...
format('knights', 'Ni'))
We are the knights who say "Ni!"

The brackets and characters within them (called format fields) are replaced with the objects passed into the
str
...
A number in the brackets can be used to refer to the position of the object passed
into the str
...

>>> print('{0} and {1}'
...
format('spam', 'eggs'))
eggs and spam

If keyword arguments are used in the str
...

>>> print('This {food} is {adjective}
...

food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible
...
format('Bill', 'Manfred',
other='Georg'))
The story of Bill, Manfred, and Georg
...
This can be done by simply passing the dict
and using square brackets '[]' to access the keys
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '

...
format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This could also be done by passing the table as keyword arguments with the ‘**’ notation
...
format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This is particularly useful in combination with the built-in function vars(), which returns a dictionary
containing all local variables
...

print('{0:2d} {1:3d} {2:4d}'
...

1
1
1
2
4
8
3
9
27
4 16
64
5 25 125
(continues on next page)

7
...
Fancier Output Formatting

55

Python Tutorial, Release 3
...
0

(continued from previous page)

6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

For a complete overview of string formatting with str
...


7
...
3 Manual String Formatting
Here’s the same table of squares and cubes, formatted manually:
>>> for x in range(1, 11):

...
rjust(2), repr(x*x)
...

# Note use of 'end' on previous line

...
rjust(4))

...
)
The str
...
There are similar methods str
...
center()
...
If the input string is too long, they don’t truncate it, but
return it unchanged; this will mess up your column lay-out but that’s usually better than the alternative,
which would be lying about a value
...
ljust(n)[:n]
...
zfill(), which pads a numeric string on the left with zeros
...
zfill(5)
'00012'
>>> '-3
...
zfill(7)
'-003
...
14159265359'
...
14159265359'

7
...
4 Old string formatting
The % operator can also be used for string formatting
...
For example:

56

Chapter 7
...
7
...
3f
...
pi)
The value of pi is approximately 3
...


More information can be found in the old-string-formatting section
...
2 Reading and Writing Files
open() returns a file object, and is most commonly used with two arguments: open(filename, mode)
...
The second argument is another string containing a
few characters describing the way in which the file will be used
...
'r+' opens the file for both
reading and writing
...

Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are
encoded in a specific encoding
...

'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of
bytes objects
...

In text mode, the default when reading is to convert platform-specific line endings (\n on Unix, \r\n on
Windows) to just \n
...
This behind-the-scenes modification to file data is fine for text files, but will
corrupt binary data like that in JPEG or EXE files
...

It is good practice to use the with keyword when dealing with file objects
...
Using with is also much
shorter than writing equivalent try-finally blocks:
>>> with open('workfile') as f:

...
read()
>>> f
...
close() to close the file and immediately
free up any system resources used by it
...
Another
risk is that different Python implementations will do this clean-up at different times
...
close(), attempts to use the file
object will automatically fail
...
close()
>>> f
...


7
...
1 Methods of File Objects
The rest of the examples in this section will assume that a file object called f has already been created
...
2
...
7
...
read(size), which reads some quantity of data and returns it as a string (in
text mode) or bytes object (in binary mode)
...
When size is omitted
or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as
large as your machine’s memory
...
If the end of the file
has been reached, f
...

>>> f
...
\n'
>>> f
...
readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and
is only omitted on the last line of the file if the file doesn’t end in a newline
...
readline() returns an empty string, the end of the file has been reached, while a blank
line is represented by '\n', a string containing only a single newline
...
readline()
'This is the first line of the file
...
readline()
'Second line of the file\n'
>>> f
...
This is memory efficient, fast, and leads to
simple code:
>>> for line in f:

...

This is the first line of the file
...
readlines()
...
write(string) writes the contents of string to the file, returning the number of characters written
...
write('This is a test\n')
15

Other types of objects need to be converted – either to a string (in text mode) or a bytes object (in binary
mode) – before writing them:
>>> value = ('the answer', 42)
>>> s = str(value) # convert the tuple to string
>>> f
...
tell() returns an integer giving the file object’s current position in the file represented as number of bytes
from the beginning of the file when in binary mode and an opaque number when in text mode
...
seek(offset, from_what)
...
A from_what
value of 0 measures from the beginning of the file, 1 uses the current file position, and 2 uses the end of the
file as the reference point
...

>>> f = open('workfile', 'rb+')
>>> f
...
Input and Output

Python Tutorial, Release 3
...
0

(continued from previous page)

16
>>> f
...
read(1)
b'5'
>>> f
...
read(1)
b'd'

# Go to the 6th byte in the file

# Go to the 3rd byte before the end

In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are
allowed (the exception being seeking to the very file end with seek(0, 2)) and the only valid offset values
are those returned from the f
...
Any other offset value produces undefined behaviour
...


7
...
2 Saving structured data with json
Strings can easily be written to and read from a file
...
When you want to save more complex data types like nested lists
and dictionaries, parsing and serializing by hand becomes complicated
...

The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing
...
Between serializing and deserializing, the string representing the object may have been stored
in a file or data, or sent over a network connection to some distant machine
...
Many
programmers are already familiar with it, which makes it a good choice for interoperability
...
dumps([1, 'simple', 'list'])
'[1, "simple", "list"]'

Another variant of the dumps() function, called dump(), simply serializes the object to a text file
...
dump(x, f)

To decode the object again, if f is a text file object which has been opened for reading:
x = json
...
The reference for the json module contains an explanation of this
...
2
...
7
...

As such, it is specific to Python and cannot be used to communicate with applications written in other
languages
...


60

Chapter 7
...
There are (at least) two distinguishable kinds of errors: syntax errors and exceptions
...
1 Syntax Errors
Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while
you are still learning Python:
>>> while True print('Hello world')
File "", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax

The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line
where the error was detected
...
File
name and line number are printed so you know where to look in case the input came from a script
...
2 Exceptions
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made
to execute it
...
Most exceptions are not handled by programs,
however, and result in error messages as shown here:
>>> 10 * (1/0)
Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "", line 1, in
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "", line 1, in
TypeError: Can't convert 'int' object to str implicitly

61

Python Tutorial, Release 3
...
0

The last line of the error message indicates what happened
...
The string printed as the exception type is the name of the built-in exception that occurred
...
Standard exception names are built-in identifiers (not reserved keywords)
...

The preceding part of the error message shows the context where the exception happened, in the form of
a stack traceback
...

bltin-exceptions lists the built-in exceptions and their meanings
...
3 Handling Exceptions
It is possible to write programs that handle selected exceptions
...

>>> while True:

...

x = int(input("Please enter a number: "))

...

except ValueError:

...
Try again
...


The try statement works as follows
...

• If no exception occurs, the except clause is skipped and execution of the try statement is finished
...
Then if its
type matches the exception named after the except keyword, the except clause is executed, and then
execution continues after the try statement
...

A try statement may have more than one except clause, to specify handlers for different exceptions
...
Handlers only handle exceptions that occur in the corresponding try
clause, not in other handlers of the same try statement
...
except (RuntimeError, TypeError, NameError):

...

For example, the following code will print B, C, D in that order:
class B(Exception):
pass
(continues on next page)

62

Chapter 8
...
7
...

The last except clause may omit the exception name(s), to serve as a wildcard
...
txt')
s = f
...
strip())
except OSError as err:
print("OS error: {0}"
...
")
except:
print("Unexpected error:", sys
...

It is useful for code that must be executed if the try clause does not raise an exception
...
argv[1:]:
try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f
...
close()

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement
...
The
presence and type of the argument depend on the exception type
...
The variable is bound to an exception
instance with the arguments stored in instance
...
For convenience, the exception instance defines
__str__() so the arguments can be printed directly without having to reference
...
One may also
8
...
Handling Exceptions

63

Python Tutorial, Release 3
...
0

instantiate an exception first before raising it and add any attributes to it as desired
...

raise Exception('spam', 'eggs')

...

print(type(inst))
# the exception instance

...
args)
# arguments stored in
...

print(inst)
# __str__ allows args to be printed directly,

...

x, y = inst
...

print('x =', x)

...


('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled
exceptions
...
For example:
>>> def this_fails():

...

>>> try:

...
except ZeroDivisionError as err:

...

Handling run-time error: division by zero

8
...
For example:
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "", line 1, in
NameError: HiThere

The sole argument to raise indicates the exception to be raised
...
If an exception class is passed, it will be implicitly
instantiated by calling its constructor with no arguments:
raise ValueError

# shorthand for 'raise ValueError()'

If you need to determine whether an exception was raised but don’t intend to handle it, a simpler form of
the raise statement allows you to re-raise the exception:
>>> try:

...
except NameError:
(continues on next page)

64

Chapter 8
...
7
...

print('An exception flew by!')

...

An exception flew by!
Traceback (most recent call last):
File "", line 2, in
NameError: HiThere

8
...
Exceptions should typically be derived from the Exception class, either directly or indirectly
...
When creating a module that can raise several distinct errors, a common practice is to create
a base class for exceptions defined by that module, and subclass that to create specific exception classes for
different error conditions:
class Error(Exception):
"""Base class for exceptions in this module
...

Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self
...
message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed
...
previous = previous
self
...
message = message

Most exceptions are defined with names that end in “Error,” similar to the naming of the standard exceptions
...

More information on classes is presented in chapter Classes
...
5
...
7
...
6 Defining Clean-up Actions
The try statement has another optional clause which is intended to define clean-up actions that must be
executed under all circumstances
...

raise KeyboardInterrupt

...

print('Goodbye, world!')

...
When an exception has occurred in the try clause and has not been handled by an except clause (or it
has occurred in an except or else clause), it is re-raised after the finally clause has been executed
...
A more complicated example:
>>> def divide(x, y):

...

result = x / y

...

print("division by zero!")

...

print("result is", result)

...

print("executing finally clause")

...
0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "", line 1, in
File "", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

As you can see, the finally clause is executed in any event
...

In real world applications, the finally clause is useful for releasing external resources (such as files or
network connections), regardless of whether the use of the resource was successful
...
7 Predefined Clean-up Actions
Some objects define standard clean-up actions to be undertaken when the object is no longer needed, regardless of whether or not the operation using the object succeeded or failed
...


66

Chapter 8
...
7
...
txt"):
print(line, end="")

The problem with this code is that it leaves the file open for an indeterminate amount of time after this part
of the code has finished executing
...
The with statement allows objects like files to be used in a way that ensures they are always
cleaned up promptly and correctly
...
txt") as f:
for line in f:
print(line, end="")

After the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines
...


8
...
Predefined Clean-up Actions

67

Python Tutorial, Release 3
...
0

68

Chapter 8
...
Creating a new class creates a new type
of object, allowing new instances of that type to be made
...
Class instances can also have methods (defined by its class) for modifying its
state
...
It is a mixture of the class mechanisms found in C++ and Modula-3
...
Objects can contain arbitrary amounts and
kinds of data
...

In C++ terminology, normally class members (including the data members) are public (except see below
Private Variables), and all member functions are virtual
...
As in Smalltalk, classes themselves
are objects
...
Unlike C++ and Modula-3, built-in types
can be used as base classes for extension by the user
...
) can be redefined for class instances
...
I would use Modula-3 terms, since its object-oriented semantics are closer to those of Python
than C++, but I expect that few readers have heard of it
...
1 A Word About Names and Objects
Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object
...
This is usually not appreciated on a first glance at Python, and
can be safely ignored when dealing with immutable basic types (numbers, strings, tuples)
...
This is usually used to the benefit of the program, since aliases behave
like pointers in some respects
...


9
...
Class definitions
play some neat tricks with namespaces, and you need to know how scopes and namespaces work to fully

69

Python Tutorial, Release 3
...
0

understand what’s going on
...

Let’s begin with some definitions
...
Most namespaces are currently implemented as Python
dictionaries, but that’s normally not noticeable in any way (except for performance), and it may change
in the future
...

In a sense the set of attributes of an object also form a namespace
...

By the way, I use the word attribute for any name following a dot — for example, in the expression z
...
Strictly speaking, references to names in modules are attribute
references: in the expression modname
...
In this case there happens to be a straightforward mapping between the module’s attributes and the
global names defined in the module: they share the same namespace!1
Attributes may be read-only or writable
...
Module
attributes are writable: you can write modname
...
Writable attributes may also be deleted
with the del statement
...
the_answer will remove the attribute the_answer from
the object named by modname
...
The namespace containing the
built-in names is created when the Python interpreter starts up, and is never deleted
...
The statements executed by the top-level invocation of the interpreter, either read
from a script file or interactively, are considered part of a module called __main__, so they have their own
global namespace
...
)
The local namespace for a function is created when the function is called, and deleted when the function
returns or raises an exception that is not handled within the function
...
) Of course, recursive invocations each have their own local
namespace
...
“Directly accessible”
here means that an unqualified reference to a name attempts to find the name in the namespace
...
At any time during execution, there
are at least three nested scopes whose namespaces are directly accessible:
• the innermost scope, which is searched first, contains the local names
• the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope,
contains non-local, but also non-global names
• the next-to-last scope contains the current module’s global names
• the outermost scope (searched last) is the namespace containing built-in names
If a name is declared global, then all references and assignments go directly to the middle scope containing the
module’s global names
...

1 Except for one thing
...
Obviously, using this violates
the abstraction of namespace implementation, and should be restricted to things like post-mortem debuggers
...
Classes

Python Tutorial, Release 3
...
0

Usually, the local scope references the local names of the (textually) current function
...
Class definitions
place yet another namespace in the local scope
...
On the
other hand, the actual search for names is done dynamically, at run time — however, the language definition
is evolving towards static name resolution, at “compile” time, so don’t rely on dynamic name resolution! (In
fact, local variables are already determined statically
...
Assignments do not copy data — they just bind names to objects
...

In fact, all operations that introduce new names use the local scope: in particular, import statements and
function definitions bind the module or function name in the local scope
...


9
...
1 Scopes and Namespaces Example
This is an example demonstrating how to reference the different scopes and namespaces, and how global
and nonlocal affect variable binding:
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)

The output of the example code is:
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

Note how the local assignment (which is default) didn’t change scope_test’s binding of spam
...

9
...
Python Scopes and Namespaces

71

Python Tutorial, Release 3
...
0

You can also see that there was no previous binding for spam before the global assignment
...
3 A First Look at Classes
Classes introduce a little bit of new syntax, three new object types, and some new semantics
...
3
...


...



Class definitions, like function definitions (def statements) must be executed before they have any effect
...
)
In practice, the statements inside a class definition will usually be function definitions, but other statements
are allowed, and sometimes useful — we’ll come back to this later
...

When a class definition is entered, a new namespace is created, and used as the local scope — thus, all
assignments to local variables go into this new namespace
...

When a class definition is left normally (via the end), a class object is created
...
The original local scope (the one in effect just before the class definition was entered)
is reinstated, and the class object is bound here to the class name given in the class definition header
(ClassName in the example)
...
3
...

Attribute references use the standard syntax used for all attribute references in Python: obj
...
Valid
attribute names are all the names that were in the class’s namespace when the class object was created
...
i and MyClass
...
Class attributes can also be assigned to, so you can change the value of MyClass
...
__doc__ is also a valid attribute, returning the docstring belonging to the class: "A simple example
class"
...
Classes

Python Tutorial, Release 3
...
0

Class instantiation uses function notation
...
For example (assuming the above class):
x = MyClass()

creates a new instance of the class and assigns this object to the local variable x
...
Many classes like to create
objects with instances customized to a specific initial state
...
data = []

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the
newly-created class instance
...
In that case, arguments given
to the class instantiation operator are passed on to __init__()
...

def __init__(self, realpart, imagpart):

...
r = realpart

...
i = imagpart

...
0, -4
...
r, x
...
0, -4
...
3
...
There are two kinds of valid attribute names, data attributes and methods
...
Data
attributes need not be declared; like local variables, they spring into existence when they are first assigned
to
...
counter = 1
while x
...
counter = x
...
counter)
del x
...
A method is a function that “belongs to” an
object
...
For example, list objects have methods called append, insert, remove, sort, and so on
...
)
Valid method names of an instance object depend on its class
...
So in our example, x
...
f is a function, but x
...
i is not
...
f is not the same
thing as MyClass
...


9
...
A First Look at Classes

73

Python Tutorial, Release 3
...
0

9
...
4 Method Objects
Usually, a method is called right after it is bound:
x
...
However, it is not necessary to call a
method right away: x
...
For example:
xf = x
...

What exactly happens when a method is called? You may have noticed that x
...
What happened to the
argument? Surely Python raises an exception when a function that requires an argument is called without
any — even if the argument isn’t actually used…
Actually, you may have guessed the answer: the special thing about methods is that the instance object is
passed as the first argument of the function
...
f() is exactly equivalent to MyClass
...
In general, calling a method with a list of n arguments is equivalent to calling the corresponding
function with an argument list that is created by inserting the method’s instance object before the first
argument
...

When a non-data attribute of an instance is referenced, the instance’s class is searched
...

When the method object is called with an argument list, a new argument list is constructed from the instance
object and the argument list, and the function object is called with this new argument list
...
3
...
name = name
# instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d
...
kind
'canine'
>>> d
...
name
'Buddy'

74

# shared by all dogs
# shared by all dogs
# unique to d
# unique to e

Chapter 9
...
7
...
For example, the tricks list in the following code
should not be used as a class variable because just a single list would be shared by all Dog instances:
class Dog:
tricks = []

# mistaken use of a class variable

def __init__(self, name):
self
...
tricks
...
add_trick('roll over')
>>> e
...
tricks
# unexpectedly shared by all dogs
['roll over', 'play dead']

Correct design of the class should use an instance variable instead:
class Dog:
def __init__(self, name):
self
...
tricks = []
# creates a new empty list for each dog
def add_trick(self, trick):
self
...
append(trick)
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d
...
add_trick('play dead')
>>> d
...
tricks
['play dead']

9
...
Possible conventions include capitalizing method names, prefixing data attribute names
with a small unique string (perhaps just an underscore), or using verbs for methods and nouns for data
attributes
...
In
other words, classes are not usable to implement pure abstract data types
...
(On the other hand, the Python
implementation, written in C, can completely hide implementation details and control access to an object if
necessary; this can be used by extensions to Python written in C
...
4
...
7
...
Note that clients may add data attributes of their own to an instance
object without affecting the validity of the methods, as long as name conflicts are avoided — again, a naming
convention can save a lot of headaches here
...
I find that
this actually increases the readability of methods: there is no chance of confusing local variables and instance
variables when glancing through a method
...
This is nothing more than a convention: the name
self has absolutely no special meaning to Python
...

Any function object that is a class attribute defines a method for instances of that class
...
For example:
# Function defined outside the class
def f1(self, x, y):
return min(x, x+y)
class C:
f = f1
def g(self):
return 'hello world'
h = g

Now f, g and h are all attributes of class C that refer to function objects, and consequently they are all
methods of instances of C — h being exactly equivalent to g
...

Methods may call other methods by using method attributes of the self argument:
class Bag:
def __init__(self):
self
...
data
...
add(x)
self
...
The global scope associated
with a method is the module containing its definition
...
) While one
rarely encounters a good reason for using global data in a method, there are many legitimate uses of the
global scope: for one thing, functions and modules imported into the global scope can be used by methods,
as well as functions and classes defined in it
...

Each value is an object, and therefore has a class (also called its type)
...
__class__
...
Classes

Python Tutorial, Release 3
...
0

9
...
The
syntax for a derived class definition looks like this:
class DerivedClassName(BaseClassName):


...


...
In place of
a base class name, other arbitrary expressions are also allowed
...
BaseClassName):

Execution of a derived class definition proceeds the same as for a base class
...
This is used for resolving attribute references: if a requested
attribute is not found in the class, the search proceeds to look in the base class
...

There’s nothing special about instantiation of derived classes: DerivedClassName() creates a new instance of
the class
...

Derived classes may override methods of their base classes
...
(For C++ programmers:
all methods in Python are effectively virtual
...
There is a simple way to call the base class method directly: just call
BaseClassName
...
This is occasionally useful to clients as well
...
)
Python has two built-in functions that work with inheritance:
• Use isinstance() to check an instance’s type: isinstance(obj, int) will be True only if obj
...

• Use issubclass() to check class inheritance: issubclass(bool, int) is True since bool is a subclass
of int
...


9
...
1 Multiple Inheritance
Python supports a form of multiple inheritance as well
...


...



9
...
Inheritance

77

Python Tutorial, Release 3
...
0

For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent
class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy
...

In fact, it is slightly more complex than that; the method resolution order changes dynamically to support
cooperative calls to super()
...

Dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more diamond relationships (where at least one of the parent classes can be accessed through multiple paths from the
bottommost class)
...
To keep the base classes from being accessed more than
once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once, and that is monotonic (meaning that a class
can be subclassed without affecting the precedence order of its parents)
...
For more detail, see
https://www
...
org/download/releases/2
...


9
...

However, there is a convention that is followed by most Python code: a name prefixed with an underscore
(e
...
_spam) should be treated as a non-public part of the API (whether it is a function, a method or a data
member)
...

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names
defined by subclasses), there is limited support for such a mechanism, called name mangling
...

This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within
the definition of a class
...

For example:
class Mapping:
def __init__(self, iterable):
self
...
__update(iterable)
def update(self, iterable):
for item in iterable:
self
...
append(item)
__update = update

# private copy of original update() method

class MappingSubclass(Mapping):
def update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self
...
append(item)

Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a
variable that is considered private
...

78

Chapter 9
...
7
...
The same restriction applies to getattr(), setattr() and delattr(),
as well as when referencing __dict__ directly
...
7 Odds and Ends
Sometimes it is useful to have a data type similar to the Pascal “record” or C “struct”, bundling together a
few named data items
...
name = 'John Doe'
john
...
salary = 1000

A piece of Python code that expects a particular abstract data type can often be passed a class that emulates
the methods of that data type instead
...

Instance method objects have attributes, too: m
...
__func__ is the function object corresponding to the method
...
8 Iterators
By now you have probably noticed that most container objects can be looped over using a for statement:
for element in [1, 2, 3]:
print(element)
for element in (1, 2, 3):
print(element)
for key in {'one':1, 'two':2}:
print(key)
for char in "123":
print(char)
for line in open("myfile
...
The use of iterators pervades and unifies Python
...
The function returns an iterator
object that defines the method __next__() which accesses elements in the container one at a time
...
You can call the __next__() method using the next() built-in function; this example shows how
it all works:
>>> s = 'abc'
>>> it = iter(s)
>>> it
(continues on next page)

9
...
Odds and Ends

79

Python Tutorial, Release 3
...
0

(continued from previous page)


>>> next(it)
'a'
>>> next(it)
'b'
>>> next(it)
'c'
>>> next(it)
Traceback (most recent call last):
File "", line 1, in
next(it)
StopIteration

Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes
...
If the class defines
__next__(), then __iter__() can just return self:
class Reverse:
"""Iterator for looping over a sequence backwards
...
data = data
self
...
index == 0:
raise StopIteration
self
...
index - 1
return self
...
index]
>>> rev = Reverse('spam')
>>> iter(rev)
<__main__
...

print(char)

...
9 Generators
Generators are a simple and powerful tool for creating iterators
...
Each time next() is called on it, the generator
resumes where it left off (it remembers all the data values and which statement was last executed)
...
Classes

Python Tutorial, Release 3
...
0

>>> for char in reverse('golf'):

...

f
l
o
g

Anything that can be done with generators can also be done with class-based iterators as described in the
previous section
...

Another key feature is that the local variables and execution state are automatically saved between calls
...
index and self
...

In addition to automatic method creation and saving program state, when generators terminate, they automatically raise StopIteration
...


9
...
These expressions are designed for situations where the generator is used right away by an enclosing function
...

Examples:
>>> sum(i*i for i in range(10))
285
>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))
260

# sum of squares

# dot product

>>> from math import pi, sin
>>> sine_table = {x: sin(x*pi/180) for x in range(0, 91)}
>>> unique_words = set(word

for line in page

for word in line
...
gpa, student
...
10
...
7
...
Classes

CHAPTER

TEN

BRIEF TOUR OF THE STANDARD LIBRARY

10
...
getcwd()
# Return the current working directory
'C:\\Python37'
>>> os
...
system('mkdir today')
# Run the command mkdir in the system shell
0

Be sure to use the import os style instead of from os import *
...
open() from shadowing
the built-in open() function which operates much differently
...
copyfile('data
...
db')
'archive
...
move('/build/executables', 'installdir')
'installdir'

10
...
glob('*
...
py', 'random
...
py']

83

Python Tutorial, Release 3
...
0

10
...
These arguments are stored in the
sys module’s argv attribute as a list
...
py
one two three at the command line:
>>> import sys
>>> print(sys
...
py', 'one', 'two', 'three']

The getopt module processes sys
...
More powerful
and flexible command line processing is provided by the argparse module
...
4 Error Output Redirection and Program Termination
The sys module also has attributes for stdin, stdout, and stderr
...
stderr
...
exit()
...
5 String Pattern Matching
The re module provides regular expression tools for advanced string processing
...
findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re
...
replace('too', 'two')
'tea for two'

10
...
cos(math
...
70710678118654757
>>> math
...
0

The random module provides tools for making random selections:
84

Chapter 10
...
7
...
choice(['apple', 'pear', 'banana'])
'apple'
>>> random
...
random()
# random float
0
...
randrange(6)
# random integer chosen from range(6)
4

The statistics module calculates basic statistical properties (the mean, median, variance, etc
...
75, 1
...
25, 0
...
5, 1
...
5]
>>> statistics
...
6071428571428572
>>> statistics
...
25
>>> statistics
...
3720238095238095

The SciPy project ...


10
...
Two of the
simplest are urllib
...
request import urlopen
>>> with urlopen('http://tycho
...
navy
...
pl') as response:

...

line = line
...


...

print(line)

Nov
...


...


...

>>>

import smtplib
server = smtplib
...
sendmail('soothsayer@example
...
org',
"""To: jcaesar@example
...
org
Beware the Ides of March
...
quit()

(Note that the second example needs a mailserver running on localhost
...
8 Dates and Times
The datetime module supplies classes for manipulating dates and times in both simple and complex ways
...
7
...
7
...
The module also supports objects that are timezone aware
...
today()
>>> now
datetime
...
strftime("%m-%d-%y
...
")
'12-02-03
...
'
>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age
...
9 Data Compression
Common data archiving and compression formats are directly supported by modules including: zlib, gzip,
bz2, lzma, zipfile and tarfile
...
compress(s)
>>> len(t)
37
>>> zlib
...
crc32(s)
226805979

10
...
Python provides a measurement tool that answers those questions immediately
...
The timeit module quickly demonstrates a modest performance
advantage:
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2')
...
57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2')
...
54962537085770791

In contrast to timeit’s fine level of granularity, the profile and pstats modules provide tools for identifying
time critical sections in larger blocks of code
...
Brief Tour of the Standard Library

Python Tutorial, Release 3
...
0

10
...

The doctest module provides a tool for scanning a module and validating tests embedded in a program’s
docstrings
...
This improves the documentation by providing the user with an example and it allows the
doctest module to make sure the code remains true to the documentation:
def average(values):
"""Computes the arithmetic mean of a list of numbers
...
0
"""
return sum(values) / len(values)
import doctest
doctest
...
TestCase):
def test_average(self):
self
...
0)
self
...
3)
with self
...
assertRaises(TypeError):
average(20, 30, 70)
unittest
...
12 Batteries Included
Python has a “batteries included” philosophy
...
For example:
• The xmlrpc
...
server modules make implementing remote procedure calls into an
almost trivial task
...

• The email package is a library for managing email messages, including MIME and other RFC 2822based message documents
...

• The json package provides robust support for parsing this popular data interchange format
...
XML processing is supported by the xml
...
ElementTree,
xml
...
sax packages
...


10
...
Quality Control

87

Python Tutorial, Release 3
...
0

• The sqlite3 module is a wrapper for the SQLite database library, providing a persistent database
that can be updated and accessed using slightly nonstandard SQL syntax
...


88

Chapter 10
...
These modules rarely occur in small scripts
...
1 Output Formatting
The reprlib module provides a version of repr() customized for abbreviated displays of large or deeply
nested containers:
>>> import reprlib
>>> reprlib
...
}"

The pprint module offers more sophisticated control over printing both built-in and user defined objects in
a way that is readable by the interpreter
...

'yellow'], 'blue']]]

...
pprint(t, width=30)
[[[['black', 'cyan'],
'white',
['green', 'red']],
[['magenta', 'yellow'],
'blue']]]

The textwrap module formats paragraphs of text to fit a given screen width:
>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns

...
the wrapped lines
...

>>> print(textwrap
...


The locale module accesses a database of culture specific data formats
...
7
...
setlocale(locale
...
1252')
'English_United States
...
localeconv()
# get a mapping of conventions
>>> x = 1234567
...
format("%d", x, grouping=True)
'1,234,567'
>>> locale
...
*f", (conv['currency_symbol'],

...
80'

11
...
This allows users to customize their applications without having to alter the application
...
Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters
with no intervening spaces
...
')
>>> t
...
'

The substitute() method raises a KeyError when a placeholder is not supplied in a dictionary or a
keyword argument
...
')
>>> d = dict(item='unladen swallow')
>>> t
...

KeyError: 'owner'
>>> t
...
'

Template subclasses can specify a custom delimiter
...
path
>>> photofiles = ['img_1074
...
jpg', 'img_1077
...

delimiter = '%'
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format):
Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f

')

>>> t = BatchRename(fmt)
>>> date = time
...

base, ext = os
...
splitext(filename)

...
substitute(d=date, n=i, f=ext)
(continues on next page)

90

Chapter 11
...
7
...


print('{0} --> {1}'
...
jpg --> Ashley_0
...
jpg --> Ashley_1
...
jpg --> Ashley_2
...

This makes it possible to substitute custom templates for XML files, plain text reports, and HTML web
reports
...
3 Working with Binary Data Record Layouts
The struct module provides pack() and unpack() functions for working with variable length binary record
formats
...
Pack codes "H" and "I" represent two and four byte unsigned numbers respectively
...
zip', 'rb') as f:
data = f
...
unpack('crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
start += 16
filename = data[start:start+filenamesize]
start += filenamesize
extra = data[start:start+extra_size]
print(filename, hex(crc32), comp_size, uncomp_size)
start += extra_size + comp_size

# skip to the next header

11
...
Threads can be used to
improve the responsiveness of applications that accept user input while other tasks run in the background
...

The following code shows how the high level threading module can run tasks in background while the main
program continues to run:
import threading, zipfile
class AsyncZip(threading
...
Thread
...
infile = infile
self
...
3
...
7
...
ZipFile(self
...
ZIP_DEFLATED)
f
...
infile)
f
...
infile)
background = AsyncZip('mydata
...
zip')
background
...
')
background
...
')

The principal challenge of multi-threaded applications is coordinating threads that share data or other
resources
...

While those tools are powerful, minor design errors can result in problems that are difficult to reproduce
...
Applications using
Queue objects for inter-thread communication and coordination are easier to design, more readable, and
more reliable
...
5 Logging
The logging module offers a full featured and flexible logging system
...
stderr:
import logging
logging
...
info('Informational message')
logging
...
conf')
logging
...
critical('Critical error -- shutting down')

This produces the following output:
WARNING:root:Warning:config file server
...
Other output options include routing messages through email, datagrams, sockets, or to an HTTP
Server
...

The logging system can be configured directly from Python or can be loaded from a user editable configuration
file for customized logging without altering the application
...
Brief Tour of the Standard Library — Part II

Python Tutorial, Release 3
...
0

11
...
The memory is freed shortly after the last reference to it has been eliminated
...
Unfortunately, just tracking them creates a reference that makes
them permanent
...

When the object is no longer needed, it is automatically removed from a weakref table and a callback is
triggered for weakref objects
...

def __init__(self, value):

...
value = value

...

return str(self
...

>>> a = A(10)
# create a reference
>>> d = weakref
...
collect()
# run garbage collection right away
0
>>> d['primary']
# entry was automatically removed
Traceback (most recent call last):
File "", line 1, in
d['primary']
# entry was automatically removed
File "C:/python37/lib/weakref
...
data[key]()
KeyError: 'primary'

11
...
However, sometimes there is a need for
alternative implementations with different performance trade-offs
...
The following example shows an array of numbers stored as two byte unsigned binary
numbers (typecode "H") rather than the usual 16 bytes per entry for regular lists of Python int objects:
>>> from array import array
>>> a = array('H', [4000, 10, 700, 22222])
>>> sum(a)
26932
>>> a[1:3]
array('H', [10, 700])

The collections module provides a deque() object that is like a list with faster appends and pops from
the left side but slower lookups in the middle
...
6
...
7
...
append("task4")
>>> print("Handling", d
...
popleft()
for m in gen_moves(node):
if is_goal(m):
return m
unsearched
...
insort(scores, (300, 'ruby'))
>>> scores
[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

The heapq module provides functions for implementing heaps based on regular lists
...
This is useful for applications which repeatedly access the smallest element
but do not want to run a full list sort:
>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data)
# rearrange the list into heap order
>>> heappush(data, -5)
# add a new entry
>>> [heappop(data) for i in range(3)] # fetch the three smallest entries
[-5, 0, 1]

11
...
Compared to the
built-in float implementation of binary floating point, the class is especially helpful for
• financial applications and other uses which require exact decimal representation,
• control over precision,
• control over rounding to meet legal or regulatory requirements,
• tracking of significant decimal places, or
• applications where the user expects the results to match calculations done by hand
...
The difference becomes significant if the results are rounded to the nearest cent:
>>> from decimal import *
>>> round(Decimal('0
...
05'), 2)
Decimal('0
...
70 * 1
...
73

94

Chapter 11
...
7
...
Decimal reproduces mathematics as done by hand and avoids issues that can
arise when binary floating point cannot exactly represent decimal quantities
...
00') % Decimal('
...
00')
>>> 1
...
10
0
...
1')]*10) == Decimal('1
...
1]*10) == 1
...
prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0
...
8
...
7
...
Brief Tour of the Standard Library — Part II

CHAPTER

TWELVE

VIRTUAL ENVIRONMENTS AND PACKAGES

12
...

Applications will sometimes need a specific version of a library, because the application may require that a
particular bug has been fixed or the application may be written using an obsolete version of the library’s
interface
...

If application A needs version 1
...
0, then the
requirements are in conflict and installing either version 1
...
0 will leave one application unable to run
...

Different applications can then use different virtual environments
...
0 installed while application
B has another virtual environment with version 2
...
If application B requires a library be upgraded to version
3
...


12
...
venv will usually install the
most recent version of Python that you have available
...

To create a virtual environment, decide upon a directory where you want to place it, and run the venv
module as a script with the directory path:
python3 -m venv tutorial-env

This will create the tutorial-env directory if it doesn’t exist, and also create directories inside it containing
a copy of the Python interpreter, the standard library, and various supporting files
...

On Windows, run:
tutorial-env\Scripts\activate
...
7
...
If you use the csh or fish shells, there are alternate activate
...
fish scripts you should use instead
...
For example:
$ source ~/envs/tutorial-env/bin/activate
(tutorial-env) $ python
Python 3
...
1 (default, May 6 2016, 10:59:36)

...
path
['', '/usr/local/lib/python35
...
,
'~/envs/tutorial-env/lib/python3
...
3 Managing Packages with pip
You can install, upgrade, and remove packages using a program called pip
...
org>
...

novas
- The United States Naval Observatory NOVAS astronomy library
astroobs
- Provides astronomy ephemeris to plan telescope observations
PyAstronomy
- A collection of astronomy related tools for Python
...


pip has a number of subcommands: “search”, “install”, “uninstall”, “freeze”, etc
...
)
You can install the latest version of a package by specifying a package’s name:
(tutorial-env) $ pip install novas
Collecting novas
Downloading novas-3
...
1
...
tar
...
py install for novas
Successfully installed novas-3
...
1
...
6
...
6
...
6
...
py3-none-any
...
6
...

You can supply a different version number to get that version, or you can run pip install --upgrade to
upgrade the package to the latest version:

98

Chapter 12
...
7
...
6
...
6
...
6
...
7
...

pip show will display information about a particular package:
(tutorial-env) $ pip show requests
--Metadata-Version: 2
...
7
...

Home-page: http://python-requests
...
com
License: Apache 2
...
4/site-packages
Requires:

pip list will display all of the packages installed in the virtual environment:
(tutorial-env) $ pip list
novas (3
...
1
...
9
...
0
...
7
...
0)

pip freeze will produce a similar list of the installed packages, but the output uses the format that pip
install expects
...
txt file:
(tutorial-env) $ pip freeze > requirements
...
txt
novas==3
...
1
...
9
...
7
...
txt can then be committed to version control and shipped as part of an application
...
txt
Collecting novas==3
...
1
...
txt (line 1))

...
9
...
txt (line 2))

...
7
...
txt (line 3))

...
py install for novas
Successfully installed novas-3
...
1
...
9
...
7
...
3
...
7
...
Consult the installing-index guide for complete documentation for pip
...


100

Chapter 12
...
Where should you go to learn more?
This tutorial is part of Python’s documentation set
...
The standard Python distribution includes
a lot of additional code
...
Skimming through the Library Reference will give you an idea of what’s available
...

• reference-index: A detailed explanation of Python’s syntax and semantics
...

More Python resources:
• https://www
...
org: The major Python Web site
...
This Web site is mirrored in various places around the world,
such as Europe, Japan, and Australia; a mirror may be faster than the main site, depending on your
geographical location
...
python
...

• https://pypi
...
Once you begin releasing code, you
can register it here so that others can find it
...
activestate
...
Particularly notable contributions are collected in
a book also titled Python Cookbook (O’Reilly & Associates, ISBN 0-596-00797-3
...
pyvideo
...

• https://scipy
...

For Python-related questions and problem reports, you can post to the newsgroup comp
...
python, or
send them to the mailing list at python-list@python
...
The newsgroup and mailing list are gatewayed,
so messages posted to one will automatically be forwarded to the other
...
Mailing list
archives are available at https://mail
...
org/pipermail/
...
7
...
The FAQ
answers many of the questions that come up again and again, and may already contain the solution for your
problem
...
What Now?

CHAPTER

FOURTEEN

INTERACTIVE INPUT EDITING AND HISTORY SUBSTITUTION

Some versions of the Python interpreter support editing of the current input line and history substitution,
similar to facilities found in the Korn shell and the GNU Bash shell
...
This library has its own documentation which we
won’t duplicate here
...
1 Tab Completion and History Editing
Completion of variable and module names is automatically enabled at interpreter startup so that the Tab
key invokes the completion function; it looks at Python statement names, the current local variables, and
the available module names
...
a, it will evaluate the expression up to
the final '
...
Note that this may
execute application-defined code if an object with a __getattr__() method is part of the expression
...
python_history in your user directory
...


14
...
The completion mechanism might use the interpreter’s symbol
table
...
, would also be useful
...
It can also be thoroughly
customized and embedded into other applications
...


103

Python Tutorial, Release 3
...
0

104

Chapter 14
...
For example,
the decimal fraction
0
...
001

has value 0/2 + 0/4 + 1/8
...

Unfortunately, most decimal fractions cannot be represented exactly as binary fractions
...

The problem is easier to understand at first in base 10
...
You can approximate
that as a base 10 fraction:
0
...
33

or, better,
0
...
No matter how many digits you’re willing to write down, the result will never be exactly 1/3,
but will be an increasingly better approximation of 1/3
...
1 cannot be
represented exactly as a base 2 fraction
...
0001100110011001100110011001100110011001100110011
...
On most machines today, floats are
approximated using a binary fraction with the numerator using the first 53 bits starting with the most
significant bit and with the denominator as a power of two
...

Many users are not aware of the approximation because of the way values are displayed
...
On
most machines, if Python were to print the true decimal value of the binary approximation stored for 0
...
7
...
1
0
...
1

Just remember, even though the printed result looks like the exact value of 1/10, the actual stored value is
the nearest representable binary fraction
...

For example, the numbers 0
...
10000000000000001 and
0
...
Since all of these decimal values share the same approximation,
any one of them could be displayed while still preserving the invariant eval(repr(x)) == x
...
10000000000000001
...
1, Python (on most systems) is now able to choose
the shortest of these and simply display 0
...

Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a
bug in your code either
...

For more pleasant output, you may wish to use string formatting to produce a limited number of significant
digits:
>>> format(math
...
12g')
'3
...
pi, '
...
14'

# give 2 digits after the point

>>> repr(math
...
141592653589793'

It’s important to realize that this is, in a real sense, an illusion: you’re simply rounding the display of the
true machine value
...
For example, since 0
...
1 may
not yield exactly 0
...
1 +
...
1 ==
...
1 cannot get any closer to the exact value of 1/10 and 0
...
1, 1) + round(
...
1, 1) == round(
...
1 +
...
1, 10) == round(
...
Floating Point Arithmetic: Issues and Limitations

Python Tutorial, Release 3
...
0

Binary floating-point arithmetic holds many surprises like this
...
1” is explained in
precise detail below, in the “Representation Error” section
...

As that says near the end, “there are no easy answers
...
That’s more than adequate for most tasks, but
you do need to keep in mind that it’s not decimal arithmetic and that every float operation can suffer a new
rounding error
...
str() usually suffices, and for finer control see the str
...

For use cases which require exact decimal representation, try using the decimal module which implements
decimal arithmetic suitable for accounting applications and high-precision applications
...

If you are a heavy user of floating point operations you should take a look at the Numerical Python package
and many other packages for mathematical and statistical operations supplied by the SciPy project
...
org>
...
The float
...
14159
>>> x
...
hex() method expresses a float in hexadecimal (base 16), again giving the exact value stored by
your computer:
>>> x
...
921f9f01b866ep+1'

This precise hexadecimal representation can be used to reconstruct the float value exactly:
>>> x == float
...
921f9f01b866ep+1')
True

Since the representation is exact, it is useful for reliably porting values across different versions of Python
(platform independence) and exchanging data with other languages that support the same format (such as
Java and C99)
...
fsum() function which helps mitigate loss-of-precision during summation
...
That can make a difference in overall accuracy
so that the errors do not accumulate to the point where they affect the final total:
>>> sum([0
...
0
False
>>> math
...
1] * 10) == 1
...
7
...
1 Representation Error
This section explains the “0
...
Basic familiarity with binary floating-point representation is assumed
...
This is the chief reason why Python (or Perl, C, C++, Java, Fortran,
and many others) often won’t display the exact decimal number you expect
...
Almost all machines today (November
2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754
“double precision”
...
1
to the closest fraction it can of the form J/2**N where J is an integer containing exactly 53 bits
...
The best possible value for J is then
that quotient rounded:
>>> q, r = divmod(2**56, 10)
>>> r
6

Since the remainder is more than half of 10, the best approximation is obtained by rounding up:
>>> q+1
7205759403792794

Therefore the best possible approximation to 1/10 in 754 double precision is:
7205759403792794 / 2 ** 56

Dividing both the numerator and denominator by two reduces the fraction to:
3602879701896397 / 2 ** 55

Note that since we rounded up, this is actually a little bit larger than 1/10; if we had not rounded up, the
quotient would have been a little bit smaller than 1/10
...
1 * 2 ** 55
3602879701896397
...
Floating Point Arithmetic: Issues and Limitations

Python Tutorial, Release 3
...
0

meaning that the exact number stored in the computer is equal to the decimal value
0
...
Instead of displaying the full decimal
value, many languages (including older versions of Python), round the result to 17 significant digits:
>>> format(0
...
17f')
'0
...
from_float(0
...
1)
...
from_float(0
...
1000000000000000055511151231257827021181583404541015625')
>>> format(Decimal
...
1), '
...
10000000000000001'

15
...
Representation Error

109

Python Tutorial, Release 3
...
0

110

Chapter 15
...
1 Interactive Mode
16
...
1 Error Handling
When an error occurs, the interpreter prints an error message and a stack trace
...
(Exceptions handled by an except clause in a try statement are not errors in this
context
...
All error messages are written to the standard
error stream; normal output from executed commands is written to standard output
...
1 Typing an interrupt while a command is executing raises
the KeyboardInterrupt exception, which may be handled by a try statement
...
1
...
5

(assuming that the interpreter is on the user’s PATH) at the beginning of the script and giving the file an
executable mode
...
On some platforms, this first line
must end with a Unix-style line ending ('\n'), not a Windows ('\r\n') line ending
...

The script can be given an executable mode, or permission, using the chmod command
...
py

On Windows systems, there is no notion of an “executable mode”
...
py files with python
...
The
extension can also be
...


16
...
3 The Interactive Startup File
When you use Python interactively, it is frequently handy to have some standard commands executed every
time the interpreter is started
...


111

Python Tutorial, Release 3
...
0

to the name of a file containing your start-up commands
...
profile feature of the Unix
shells
...
It
is executed in the same namespace where interactive commands are executed, so that objects that it defines
or imports can be used without qualification in the interactive session
...
ps1 and sys
...

If you want to read an additional start-up file from the current directory, you can program this in the
global start-up file using code like if os
...
isfile('
...
py'): exec(open('
...
py')
...
If you want to use the startup file in a script, you must do this explicitly in the script:
import os
filename = os
...
get('PYTHONSTARTUP')
if filename and os
...
isfile(filename):
with open(filename) as fobj:
startup_file = fobj
...
1
...
To see how it
works, you need first to find the location of your user site-packages directory
...
getusersitepackages()
'/home/user/
...
5/site-packages'

Now you can create a file named usercustomize
...
It
will affect every invocation of Python, unless it is started with the -s option to disable the automatic import
...
See the documentation of the site
module for more details
...
Appendix

APPENDIX

A

GLOSSARY

>>> The default Python prompt of the interactive shell
...


...

2to3 A tool that tries to convert Python 2
...
x code by handling most of the incompatibilities which can be detected by parsing the source and traversing the parse tree
...
See 2to3-reference
...
ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but
are still recognized by isinstance() and issubclass(); see the abc module documentation
...
abc module), numbers (in
the numbers module), streams (in the io module), import finders and loaders (in the importlib
...
You can create your own ABCs with the abc module
...

Annotations of local variables cannot be accessed at runtime, but annotations of global variables, class
attributes, and functions are stored in the __annotations__ special attribute of modules, classes, and
functions, respectively
...

argument A value passed to a function (or method) when calling the function
...
g
...
For example, 3 and 5 are both keyword arguments in
the following calls to complex():
complex(real=3, imag=5)
complex(**{'real': 3, 'imag': 5})

• positional argument: an argument that is not a keyword argument
...
For example, 3 and 5 are both positional arguments in the following calls:
complex(3, 5)
complex(*(3, 5))

113

Python Tutorial, Release 3
...
0

Arguments are assigned to the named local variables in a function body
...
Syntactically, any expression can be used to represent an argument;
the evaluated value is assigned to the local variable
...

asynchronous context manager An object which controls the environment seen in an async with statement by defining __aenter__() and __aexit__() methods
...

asynchronous generator A function which returns an asynchronous generator iterator
...

Usually refers to a asynchronous generator function, but may refer to an asynchronous generator
iterator in some contexts
...

An asynchronous generator function may contain await expressions as well as async for, and async
with statements
...

This is an asynchronous iterator which when called using the __anext__() method returns an awaitable
object which will execute that the body of the asynchronous generator function until the next yield
expression
...
When the asynchronous generator iterator effectively resumes
with another awaitable returned by __anext__(), it picks up where it left off
...

asynchronous iterable An object, that can be used in an async for statement
...
Introduced by PEP 492
...

__anext__ must return an awaitable object
...
Introduced
by PEP 492
...
For
example, if an object o has an attribute a it would be referenced as o
...

awaitable An object that can be used in an await expression
...
See also PEP 492
...
k
...
Guido van Rossum, Python’s creator
...
Examples of binary files are files opened
in binary mode ('rb', 'wb' or 'rb+'), sys
...
buffer, sys
...
buffer, and instances of
io
...
GzipFile
...

bytes-like object An object that supports the bufferobjects and can export a C-contiguous buffer
...
array objects, as well as many common memoryview objects
...

Some operations need the binary data to be mutable
...
Example mutable buffer objects include bytearray and a memoryview of a
bytearray
...


114

Appendix A
...
7
...
The bytecode is also cached in
...
This “intermediate
language” is said to run on a virtual machine that executes the machine code corresponding to each
bytecode
...

A list of bytecode instructions can be found in the documentation for the dis module
...
Class definitions normally contain method definitions
which operate on instances of the class
...
e
...

coercion The implicit conversion of an instance of one type to another during an operation which involves
two arguments of the same type
...
15) converts the floating point number to the
integer 3, but in 3+4
...
Without coercion, all
arguments of even compatible types would have to be normalized to the same value by the programmer,
e
...
, float(3)+4
...
5
...
Imaginary numbers are real multiples of the imaginary
unit (the square root of -1), often written i in mathematics or j in engineering
...
g
...
To get access to complex equivalents of the math module, use cmath
...
If you’re not aware of a need for them,
it’s almost certain you can safely ignore them
...
See PEP 343
...

Zero-dimensional buffers are C and Fortran contiguous
...
In
multidimensional C-contiguous arrays, the last index varies the fastest when visiting items in order of
memory address
...

coroutine Coroutines is a more generalized form of subroutines
...
Coroutines can be entered, exited, and resumed at many different points
...
See also PEP 492
...
A coroutine function may be defined
with the async def statement, and may contain await, async for, and async with keywords
...

CPython The canonical implementation of the Python programming language, as distributed on
python
...
The term “CPython” is used when necessary to distinguish this implementation from
others such as Jython or IronPython
...
Common examples for decorators are classmethod() and staticmethod()
...
):

...
7
...
):

...
See the documentation for
function definitions and class definitions for more about decorators
...
When a class
attribute is a descriptor, its special binding behavior is triggered upon attribute lookup
...
b to get, set or delete an attribute looks up the object named b in the class dictionary for a, but
if b is a descriptor, the respective descriptor method gets called
...

For more information about descriptors’ methods, see descriptors
...
The keys can be any object
with __hash__() and __eq__() methods
...

dictionary view The objects returned from dict
...
values(), and dict
...
They provide a dynamic view on the dictionary’s entries, which means that when
the dictionary changes, the view reflects these changes
...
See dict-views
...
While ignored
when the suite is executed, it is recognized by the compiler and put into the __doc__ attribute of the
enclosing class, function or module
...

duck-typing A programming style which does not look at an object’s type to determine if it has the right
interface; instead, the method or attribute is simply called or used (“If it looks like a duck and quacks
like a duck, it must be a duck
...
Duck-typing avoids tests using
type() or isinstance()
...
) Instead, it typically employs hasattr() tests or EAFP programming
...
This common Python coding style assumes the
existence of valid keys or attributes and catches exceptions if the assumption proves false
...
The technique
contrasts with the LBYL style common to many other languages such as C
...
In other words, an expression is
an accumulation of expression elements like literals, names, attribute access, operators or function
calls which all return a value
...
There are also statements which cannot be used as expressions, such as if
...

extension module A module written in C or C++, using Python’s C API to interact with the core and
with user code
...
See also PEP 498
...
Depending on the way it was created, a file object can mediate access to a real on-disk file
or to another type of storage or communication device (for example standard input/output, in-memory
buffers, sockets, pipes, etc
...

There are actually three categories of file objects: raw binary files, buffered binary files and text files
...
The canonical way to create a file object is by using the
116

Appendix A
...
7
...

file-like object A synonym for file object
...

Since Python 3
...
meta_path, and
path entry finders for use with sys
...

See PEP 302, PEP 420 and PEP 451 for much more detail
...
The floor division operator is
//
...
75 returned by float true
division
...
75 rounded downward
...

function A series of statements which returns some value to a caller
...
See also parameter, method, and the
function section
...

Function annotations are usually used for type hints: for example this function is expected to take two
int arguments and is also expected to have an int return value:
def sum_two_numbers(a: int, b: int) -> int:
return a + b

Function annotation syntax is explained in section function
...

__future__ A pseudo-module which programmers can use to enable new language features which are
not compatible with the current interpreter
...
division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

garbage collection The process of freeing memory when it is not used anymore
...
The garbage collector can be controlled using the gc module
...
It looks like a normal function except that it
contains yield expressions for producing a series of values usable in a for-loop or that can be retrieved
one at a time with the next() function
...
In cases
where the intended meaning isn’t clear, using the full terms avoids ambiguity
...

Each yield temporarily suspends processing, remembering the location execution state (including local
variables and pending try-statements)
...

generator expression An expression that returns an iterator
...
The combined
expression generates values for an enclosing function:
>>> sum(i*i for i in range(10))
285

# sum of squares 0, 1, 4,
...
7
...
Which implementation should be used during a call is determined by the dispatch algorithm
...
singledispatch() decorator, and PEP
443
...

global interpreter lock The mechanism used by the CPython interpreter to assure that only one thread
executes Python bytecode at a time
...
Locking
the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much
of the parallelism afforded by multi-processor machines
...
Also, the GIL is always
released when doing I/O
...
It is believed that overcoming this performance issue would make the implementation much more
complicated and therefore costlier to maintain
...
See pyc-invalidation
...
Hashable
objects which compare equal must have the same hash value
...

All of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not
...
They all
compare unequal (except with themselves), and their hash value is derived from their id()
...
IDLE is a basic editor and interpreter environment which ships with the standard distribution of Python
...
Immutable objects include numbers, strings and tuples
...
A new object has to be created if a different value has to be stored
...

import path A list of locations (or path entries) that are searched by the path based finder for modules to
import
...
path, but for subpackages it may
also come from the parent package’s __path__ attribute
...

importer An object that both finds and loads a module; both a finder and loader object
...
Just launch python with
no arguments (possibly by selecting it from your computer’s main menu)
...

interpreted Python is an interpreted language, as opposed to a compiled one, though the distinction can
be blurry because of the presence of the bytecode compiler
...
Interpreted languages typically

118

Appendix A
...
7
...
See also interactive
...
It
also makes several calls to the garbage collector
...
Code executed during the shutdown phase can encounter various
exceptions as the resources it relies on may not function anymore (common examples are library
modules or the warnings machinery)
...

iterable An object capable of returning its members one at a time
...

Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(),
…)
...
This iterator is good for one pass over the set of values
...
The for statement
does that automatically for you, creating a temporary unnamed variable to hold the iterator for the
duration of the loop
...

iterator An object representing a stream of data
...
When no more
data are available a StopIteration exception is raised instead
...
Iterators
are required to have an __iter__() method that returns the iterator object itself so every iterator is
also iterable and may be used in most places where other iterables are accepted
...
A container object (such as a list) produces a fresh
new iterator each time you pass it to the iter() function or use it in a for loop
...

More information can be found in typeiter
...
For example, locale
...

A number of tools in Python accept key functions to control how elements are ordered or grouped
...
sort(), heapq
...
nsmallest(), heapq
...
groupby()
...
For example
...
lower() method can serve
as a key function for case insensitive sorts
...
Also, the operator module provides three key function
constructors: attrgetter(), itemgetter(), and methodcaller()
...

keyword argument See argument
...
The syntax to create a lambda function is lambda [parameters]: expression
LBYL Look before you leap
...
This style contrasts with the EAFP approach and is characterized by the presence of many
if statements
...
7
...
For example, the code, if key in mapping: return mapping[key]
can fail if another thread removes key from mapping after the test, but before the lookup
...

list A built-in Python sequence
...

list comprehension A compact way to process all or part of the elements in a sequence and return a list
with the results
...
format(x) for x in range(256) if x % 2 == 0] generates
a list of strings containing even hex numbers (0x
...
The if clause is
optional
...

loader An object that loads a module
...
A loader is typically
returned by a finder
...
abc
...

mapping A container object that supports arbitrary key lookups and implements the methods specified
in the Mapping or MutableMapping abstract base classes
...

defaultdict, collections
...
Counter
...
meta_path
...

See importlib
...
MetaPathFinder for the methods that meta path finders implement
...
Class definitions create a class name, a class dictionary, and a list of base
classes
...
Most
object oriented programming languages provide a default implementation
...
Most users never need this tool, but when the need
arises, metaclasses can provide powerful, elegant solutions
...

More information can be found in metaclasses
...
If called as an attribute of an instance of that
class, the method will get the instance object as its first argument (which is usually called self)
...

method resolution order Method Resolution Order is the order in which base classes are searched for
a member during lookup
...
3 Method Resolution Order for details of the algorithm
used by the Python interpreter since the 2
...

module An object that serves as an organizational unit of Python code
...
Modules are loaded into Python by the process of importing
...

module spec A namespace containing the import-related information used to load a module
...
machinery
...

MRO See method resolution order
...
See also immutable
...
localtime() returns a tuple-like object where the year is accessible either with an
index such as t[0] or with a named attribute like t
...

A named tuple can be a built-in type such as time
...
A full featured named tuple can also be created with the factory function collections
...
The latter approach automatically provides extra features such as a self-documenting
representation like Employee(name='jones', title='programmer')
...
Glossary

Python Tutorial, Release 3
...
0

namespace The place where a variable is stored
...
There
are the local, global and built-in namespaces as well as nested namespaces in objects (in methods)
...
For instance, the functions builtins
...
open() are distinguished by their namespaces
...
For instance, writing random
...
islice() makes it clear that those functions are implemented by the random
and itertools modules, respectively
...
Namespace
packages may have no physical representation, and specifically are not like a regular package because
they have no __init__
...

See also module
...
For instance, a function defined
inside another function can refer to variables in the outer function
...
Local variables both read and write in the innermost
scope
...
The nonlocal allows writing
to outer scopes
...
In earlier Python versions, only new-style classes could use Python’s newer, versatile features like __slots__, descriptors,
properties, __getattribute__(), class methods, and static methods
...
Also the ultimate base
class of any new-style class
...
Technically, a package is a Python module with an __path__ attribute
...

parameter A named entity in a function (or method) definition that specifies an argument (or in some
cases, arguments) that the function can accept
...
This is the default kind of parameter, for example foo and bar in the following:
def func(foo, bar=None):
...
Python has no
syntax for defining positional-only parameters
...
g
...

• keyword-only: specifies an argument that can be supplied only by keyword
...


• var-positional: specifies that an arbitrary sequence of positional arguments can be provided (in
addition to any positional arguments already accepted by other parameters)
...


• var-keyword: specifies that arbitrarily many keyword arguments can be provided (in addition to
any keyword arguments already accepted by other parameters)
...

Parameters can specify both optional and required arguments, as well as default values for some
optional arguments
...
7
...
Parameter class, the function section, and PEP 362
...

path entry finder A finder returned by a callable on sys
...
e
...

See importlib
...
PathEntryFinder for the methods that path entry finders implement
...
path_hook list which returns a path entry finder if it knows how
to find modules on a specific path entry
...

path-like object An object representing a file system path
...
PathLike protocol
...
PathLike protocol can be converted to a str or bytes file system path by calling the
os
...
fsdecode() and os
...
Introduced by PEP 519
...
A PEP is a design document providing information to the Python
community, or describing a new feature for Python or its processes or environment
...

PEPs are intended to be the primary mechanisms for proposing major new features, for collecting community input on an issue, and for documenting the design decisions that have gone into Python
...

See PEP 1
...

positional argument See argument
...
While major changes to such interfaces are not expected, as long
as they are marked provisional, backwards incompatible changes (up to and including removal of
the interface) may occur if deemed necessary by core developers
...

Even for provisional APIs, backwards incompatible changes are seen as a “solution of last resort” every attempt will still be made to find a backwards compatible resolution to any identified problems
...
See PEP 411 for more details
...

Python 3000 Nickname for the Python 3
...
) This is also abbreviated “Py3k”
...
For example, a common
idiom in Python is to loop over all elements of an iterable using a for statement
...
Glossary

Python Tutorial, Release 3
...
0

As opposed to the cleaner, Pythonic method:
for piece in food:
print(piece)

qualified name A dotted name showing the “path” from a module’s global scope to a class, function or
method defined in that module, as defined in PEP 3155
...

class D:

...

pass

...
__qualname__
'C'
>>> C
...
__qualname__
'C
...
D
...
__qualname__
'C
...
meth'

When used to refer to modules, the fully qualified name means the entire dotted path to the module,
including any parent packages, e
...
email
...
text:
>>> import email
...
text
>>> email
...
text
...
mime
...
When the reference count of an object drops to
zero, it is deallocated
...
The sys module defines a getrefcount() function that programmers
can call to return the reference count for a particular object
...
py file
...

__slots__ A declaration inside a class that saves memory by pre-declaring space for instance attributes
and eliminating instance dictionaries
...

sequence An iterable which supports efficient element access using integer indices via the __getitem__()
special method and defines a __len__() method that returns the length of the sequence
...
Note that dict also supports __getitem__() and
__len__(), but is considered a mapping rather than a sequence because the lookups use arbitrary
immutable keys rather than integers
...
abc
...
Types that implement this expanded interface can be registered explicitly using
register()
...

slice An object usually containing a portion of a sequence
...
The bracket
(subscript) notation uses slice objects internally
...
7
...
Such methods have names starting and ending with double underscores
...

statement A statement is part of a suite (a “block” of code)
...

struct sequence A tuple with named elements
...
However, they do
not have any of the named tuple methods like _make() or _asdict()
...
float_info and the return value of os
...

text encoding A codec which encodes Unicode strings to bytes
...
Often, a text file actually accesses a byte-oriented
datastream and handles the text encoding automatically
...
stdin, sys
...
StringIO
...

triple-quoted string A string which is bound by three instances of either a quotation mark (“) or an
apostrophe (‘)
...
They allow you to include unescaped single and double quotes
within a string and they can span multiple lines without the use of the continuation character, making
them especially useful when writing docstrings
...
An object’s
type is accessible as its __class__ attribute or can be retrieved with type(obj)
...

Type aliases are useful for simplifying type hints
...

type hint An annotation that specifies the expected type for a variable, a class attribute, or a function
parameter or return value
...

Type hints of global variables, class attributes, and functions, but not local variables, can be accessed
using typing
...

See typing and PEP 484, which describe this functionality
...
Glossary

Python Tutorial, Release 3
...
0

Macintosh convention '\r'
...
splitlines() for an
additional use
...

When annotating a variable or a class attribute, assignment is optional:
class C:
field: 'annotation'

Variable annotations are usually used for type hints: for example this variable is expected to take int
values:
count: int = 0

Variable annotation syntax is explained in section annassign
...

virtual environment A cooperatively isolated runtime environment that allows Python users and applications to install and upgrade Python distribution packages without interfering with the behaviour of
other Python applications running on the same system
...

virtual machine A computer defined entirely in software
...

Zen of Python Listing of Python design principles and philosophies that are helpful in understanding and
using the language
...


125

Python Tutorial, Release 3
...
0

126

Appendix A
...

Development of the documentation and its toolchain is an entirely volunteer effort, just like Python itself
...
New
volunteers are always welcome!
Many thanks go to:
• Fred L
...
, the creator of the original Python documentation toolset and writer of much of the
content;
• the Docutils project for creating reStructuredText and the Docutils suite;
• Fredrik Lundh for his Alternative Python Reference project from which Sphinx got many good ideas
...
1 Contributors to the Python Documentation
Many people have contributed to the Python language, the Python standard library, and the Python documentation
...

It is only with the input and contributions of the Python community that Python has such wonderful
documentation – Thank You!

127

Python Tutorial, Release 3
...
0

128

Appendix B
...
1 History of the software
Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see
https://www
...
nl/) in the Netherlands as a successor of a language called ABC
...

In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI,
see https://www
...
reston
...
us/) in Reston, Virginia where he released several versions of the software
...
com to form the BeOpen
PythonLabs team
...
zope
...
In 2001, the Python Software Foundation (PSF, see https:
//www
...
org/psf/) was formed, a non-profit organization created specifically to own Python-related
Intellectual Property
...

All Python releases are Open Source (see https://opensource
...
Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the
various releases
...
9
...
2
1
...
5
...
6
2
...
6
...
1
2
...
1
2
...
1
2
...
2
2
...
3
2
...
2
1
...
2
1
...
6
2
...
6
...
0+1
...
1
2
...
0
...
1
...
1
...
1
...
com
CNRI
PSF
PSF
PSF
PSF
PSF
PSF

GPL compatible?
yes
yes
no
no
no
no
yes
yes
yes
yes
yes

Note: GPL-compatible doesn’t mean that we’re distributing Python under the GPL
...
The GPLcompatible licenses make it possible to combine Python with other software that is released under the GPL;
the others don’t
...


129

Python Tutorial, Release 3
...
0

C
...
2
...
7
...
This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
the Individual or Organization ("Licensee") accessing and otherwise using Python
3
...
0 software in source or binary form and its associated documentation
...
Subject to the terms and conditions of this License Agreement, PSF hereby
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
analyze, test, perform and/or display publicly, prepare derivative works,
distribute, and otherwise use Python 3
...
0 alone or in any derivative
version, provided, however, that PSF's License Agreement and PSF's notice of
copyright, i
...
, "Copyright © 2001-2018 Python Software Foundation; All Rights
Reserved" are retained in Python 3
...
0 alone or in any derivative version
prepared by Licensee
...
In the event Licensee prepares a derivative work that is based on or
incorporates Python 3
...
0 or any part thereof, and wants to make the
derivative work available to others as provided herein, then Licensee hereby
agrees to include in any such work a brief summary of the changes made to Python
3
...
0
...
PSF is making Python 3
...
0 available to Licensee on an "AS IS" basis
...
BY WAY OF
EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
USE OF PYTHON 3
...
0 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS
...
PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 3
...
0
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 3
...
0, OR ANY DERIVATIVE
THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF
...
This License Agreement will automatically terminate upon a material breach of
its terms and conditions
...
Nothing in this License Agreement shall be deemed to create any relationship
of agency, partnership, or joint venture between PSF and Licensee
...

8
...
7
...


C
...
2 BEOPEN
...
0
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
1
...
com ("BeOpen"), having an office at
160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
(continues on next page)

130

Appendix C
...
7
...

2
...

3
...

BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED
...

4
...

5
...

6
...

Nothing in this License Agreement shall be deemed to create any relationship of
agency, partnership, or joint venture between BeOpen and Licensee
...
As an exception, the "BeOpen Python" logos available at
http://www
...
com/logos
...

7
...


C
...
3 CNRI LICENSE AGREEMENT FOR PYTHON 1
...
1
1
...
6
...

2
...
6
...
e
...
6
...
Alternately, in lieu of CNRI's License Agreement,
Licensee may substitute the following text (omitting the quotes): "Python 1
...
1
is made available subject to the terms and conditions in CNRI's License
(continues on next page)

C
...
Terms and conditions for accessing or otherwise using Python

131

Python Tutorial, Release 3
...
0

(continued from previous page)

Agreement
...
6
...
22/1013
...
handle
...
22/1013
...
In the event Licensee prepares a derivative work that is based on or
incorporates Python 1
...
1 or any part thereof, and wants to make the derivative
work available to others as provided herein, then Licensee hereby agrees to
include in any such work a brief summary of the changes made to Python 1
...
1
...
CNRI is making Python 1
...
1 available to Licensee on an "AS IS" basis
...
BY WAY OF EXAMPLE,
BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
PYTHON 1
...
1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS
...
CNRI SHALL NOT BE LIABLE
ANY INCIDENTAL, SPECIAL,
MODIFYING, DISTRIBUTING,
THEREOF, EVEN IF ADVISED

TO
OR
OR
OF

LICENSEE OR ANY OTHER USERS OF PYTHON 1
...
1 FOR
CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
OTHERWISE USING PYTHON 1
...
1, OR ANY DERIVATIVE
THE POSSIBILITY THEREOF
...
This License Agreement will automatically terminate upon a material breach of
its terms and conditions
...
This License Agreement shall be governed by the federal intellectual property
law of the United States, including without limitation the federal copyright
law, and, to the extent such U
...
federal law does not apply, by the law of the
Commonwealth of Virginia, excluding Virginia's conflict of law provisions
...
6
...
Nothing in
this License Agreement shall be deemed to create any relationship of agency,
partnership, or joint venture between CNRI and Licensee
...

8
...
6
...


C
...
4 CWI LICENSE AGREEMENT FOR PYTHON 0
...
0 THROUGH 1
...
All rights reserved
...

(continues on next page)

132

Appendix C
...
7
...


C
...


C
...
1 Mersenne Twister
The _random module includes code based on a download from http://www
...
sci
...
ac
...
html
...

Coded by Takuji Nishimura and Makoto Matsumoto
...

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved
...
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer
...
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution
...
The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission
...
IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
(continues on next page)

C
...
Licenses and Acknowledgements for Incorporated Software

133

Python Tutorial, Release 3
...
0

(continued from previous page)

SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
...

http://www
...
sci
...
ac
...
html
email: m-mat @ math
...
hiroshima-u
...
jp (remove space)

C
...
2 Sockets
The socket module uses the functions, getaddrinfo(), and getnameinfo(), which are coded in separate
source files from the WIDE Project, http://www
...
ad
...

Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project
...

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1
...

2
...

3
...

THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED
...


C
...
3 Asynchronous socket services
The asynchat and asyncore modules contain the following notice:
Copyright 1996 by Sam Rushing
All Rights Reserved
Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of Sam
Rushing not be used in advertising or publicity pertaining to
(continues on next page)

134

Appendix C
...
7
...

SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE
...
3
...
cookies module contains the following notice:
Copyright 2000 by Timothy O'Malley ...
edu>
All Rights Reserved
Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Timothy O'Malley not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission
...


C
...
5 Execution tracing
The trace module contains the following notice:
portions copyright 2001, Autonomous Zones Industries, Inc
...

err
...
2 license
...
com/
mailto:zooko@zooko
...
, all rights reserved
...
, all rights reserved
...
3
...
7
...
, all rights reserved
...


Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission
...
3
...

All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission
...

Modified by Jack Jansen, CWI, July 1995:
- Use binascii module to do the actual line-by-line conversion
between ascii and binary
...
The C
version is still 5 times faster, though
...
3
...
client module contains the following notice:
The XML-RPC client interface is
Copyright (c) 1999-2002 by Secret Labs AB
Copyright (c) 1999-2002 by Fredrik Lundh
By obtaining, using, and/or copying this software and/or its
(continues on next page)

136

Appendix C
...
7
...

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
...


C
...
8 test_epoll
The test_epoll module contains the following notice:
Copyright (c) 2001-2006 Twisted Matrix Laboratories
...

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT
...


C
...
9 Select kqueue
The select module contains the following notice for the kqueue interface:
Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved
...
3
...
7
...
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer
...
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution
...
IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE
...
3
...
c contains Marek Majkowski’ implementation of Dan Bernstein’s SipHash24 algorithm
...
org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software
...
com/majek/csiphash/
Solution inspired by code from:
Samuel Neves (supercop/crypto_auth/siphash24/little)
djb (supercop/crypto_auth/siphash24/little2)
Jean-Philippe Aumasson (https://131002
...
c)

C
...
11 strtod and dtoa
The file Python/dtoa
...
Gay, currently available from http:
//www
...
org/fp/
...
History and License

Python Tutorial, Release 3
...
0

/****************************************************************
*
* The author of this software is David M
...

*
* Copyright (c) 1991, 2000, 2001 by Lucent Technologies
...

*
* THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTY
...

*
***************************************************************/

C
...
12 OpenSSL
The modules hashlib, posix, ssl, crypt use the OpenSSL library for added performance if made available
by the operating system
...
e
...

See below for the actual license texts
...
In case of any license issues related to OpenSSL
please contact openssl-core@openssl
...

OpenSSL License
--------------/*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*

====================================================================
Copyright (c) 1998-2008 The OpenSSL Project
...

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1
...

2
...

3
...
(http://www
...
org/)"
(continues on next page)

C
...
Licenses and Acknowledgements for Incorporated Software

139

Python Tutorial, Release 3
...
0

(continued from previous page)

*
* 4
...
For written permission, please contact
*
openssl-core@openssl
...

*
* 5
...

*
* 6
...
openssl
...
IN NO EVENT SHALL THE OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE
...
com)
...
com)
...
com)
All rights reserved
...
com)
...

This library is free for commercial and non-commercial use as long as
the following conditions are aheared to
...
, code; not just the SSL code
...
com)
...

If this package is used in a product, Eric Young should be given attribution
as the author of the parts of the library used
...
History and License

Python Tutorial, Release 3
...
0

(continued from previous page)

* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package
...
Redistributions of source code must retain the copyright
*
notice, this list of conditions and the following disclaimer
...
Redistributions in binary form must reproduce the above copyright
*
notice, this list of conditions and the following disclaimer in the
*
documentation and/or other materials provided with the distribution
...
All advertising materials mentioning features or use of this software
*
must display the following acknowledgement:
*
"This product includes cryptographic software written by
*
Eric Young (eay@cryptsoft
...

* 4
...
com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED
...

*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed
...
e
...
]
*/

C
...
13 expat
The pyexpat extension is built using an included copy of the expat sources unless the build is configured
--with-system-expat:
Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
and Clark Cooper
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
(continues on next page)

C
...
Licenses and Acknowledgements for Incorporated Software

141

Python Tutorial, Release 3
...
0

(continued from previous page)

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software
...

IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
...
3
...


Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software''), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software
...
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE
...
3
...
In no event will the authors be held liable for any damages
arising from the use of this software
...
History and License

Python Tutorial, Release 3
...
0

(continued from previous page)

1
...
If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required
...
Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software
...
This notice may not be removed or altered from any source distribution
...
org

Mark Adler
madler@alumni
...
edu

C
...
16 cfuhash
The implementation of the hash table used by the tracemalloc is based on the cfuhash project:
Copyright (c) 2005 Don Owens
All rights reserved
...

* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution
...

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED
...


C
...
Licenses and Acknowledgements for Incorporated Software

143

Python Tutorial, Release 3
...
0

C
...
17 libmpdec
The _decimal module is built using an included copy of the libmpdec library unless the build is configured
--with-system-libmpdec:
Copyright (c) 2008-2016 Stefan Krah
...

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1
...

2
...

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED
...


144

Appendix C
...
All rights reserved
...
com
...

Copyright © 1995-2000 Corporation for National Research Initiatives
...

Copyright © 1991-1995 Stichting Mathematisch Centrum
...


See History and License for complete license and permissions information
...
7
...
Copyright

INDEX

Symbols
*
statement, 26
**
statement, 27
-> (return annotation assignment), 28

...
7
...
7
Title: Python Programming full Tutorial with Exercises
Description: Here you can find the full python course and there is also exercises, examples that make your study more easier and enjoyable.