Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Preface
Python Promo
Overview
What is Python?
It's a standard library!
It's a philosophy
The journey of a thousand miles…
Errata and Suggestions
Conventions Used in This Book
Downloading the example code
Downloading the color images of this book
Getting started
Obtaining and installing Python 3
Windows
macOS
Linux
Starting Python command line REPL
Leaving the REPL
Windows
Unix
Code structure and significant indentation
Python culture
Importing standard library modules
Getting help()
Counting fruit with math.factorial()
Different types of numbers
Scalar data types: integers, floats, None and bool
int
float
Special floating point values
Promotion to float
None
bool
Relational operators
Rich comparison operators
Control flow: if-statements and while-loops
Conditional control flow: The if-statement
if...else
if...elif...else
Conditional repetition: the while-loop
Exiting loops with break
Summary
Strings and Collections
str – an immutable sequence of Unicode code points
String quoting styles
Moment of zen
Concatenation of adjacent strings
Multiline strings and newlines
Raw strings
The str constructor
Strings as sequences
String methods
Strings with Unicode
The bytes type – an immutable sequence of bytes
Literal bytes
Converting between bytes and str
list – a sequence of objects
The dict type – associating keys with values
The For-loops – iterating over series of items
Putting it all together
Summary
Modularity
Organizing code in a .py file
Running Python programs from the operating system shell
Importing modules into the REPL
Defining functions
Organizing our module into functions
The __name__ type and executing modules from the command line
The Python execution model
The difference between modules, scripts, and programs
Setting up a main function with command line argument
Accepting command line arguments
Moment of zen
Docstrings
Comments
Shebang
Executable Python programs on Linux and Mac
Executable Python programs on Windows
Summary
Built-in types and the object model
The nature of Python object references
Reassigning a reference
Assigning one reference to another
Exploring value vs. identity with id()
Testing for equality of identity with is
Mutating without mutating
References to mutable objects
Equality of value (equivalence) versus equality of identity
Argument passing semantics – pass by object-reference
Modifying external objects in a function
Binding new objects in a function
Argument passing is reference binding
Python return semantics
Function arguments in detail
Default parameter values
Keyword arguments
When are default arguments evaluated?
The Python type system
Dynamic typing in Python
Strong typing in Python
Variable declaration and scoping
The LEGB rule
Scopes in action
Identical names in global and local scope
The global keyword
Moment of zen
Everything is an object
Inspecting a function
Summary
Exploring Built-in Collection types
tuple – an immutable sequence of objects
Literal tuples
Tuple element access
The length of a tuple
Iterating over a tuple
Concatenating and repetition of tuples
Nested tuples
Single-element tuples
Empty tuples
Optional parentheses
Returning and unpacking tuples
Swapping variables with tuple unpacking
The tuple constructor
Membership tests
Strings in action
The length of a string
Concatenating strings
Joining strings
Splitting strings
Moment of zen
Partitioning strings
String formatting
Other string methods
range – a collection of evenly spaced integers
Starting value
Step argument
Not using range: enumerate()
list in action
Negative indexing for lists (and other sequences)
Slicing lists
Copying lists
Shallow copies
Repeating lists
Finding list elements with index()
Membership testing with count() and in
Removing list elements by index with del
Removing list elements by value with remove()
Inserting into a list
Concatenating lists
Rearranging list elements
Out-of-place rearrangement
Dictionaries
Copying dictionaries
Updating dictionaries
Iterating over dictionary keys
Iterating over dictionary values
Iterating over key-value pairs
Membership testing for dictionary keys
Removing dictionary items
Mutability of dictionaries
Pretty printing
set – an unordered collection of unique elements
The set constructor
Iterating over sets
Membership testing of sets
Adding elements to sets
Removing elements from sets
Copying sets
Set algebra operations
Union
Intersection
Difference
Symmetric difference
Subset relationships
Collection protocols
Container protocol
Sized protocol
Iterable protocol
Sequence protocol
Other protocols
Summary
Exceptions
Exceptions and control flow
Handling exceptions
Handling multiple exceptions
Programmer errors
Empty blocks – the pass statement
Exception objects
Imprudent return codes
Re-raising exceptions
Exceptions are part of your function's API
Exceptions raised by Python
Catching exceptions
Raising exceptions explicitly
Guard clauses
Exceptions, APIs, and protocols
IndexError
ValueError
KeyError
Choosing not to guard against TypeError
Pythonic style – EAFP versus LBYL
Clean-up actions
Moment of zen
Platform-specific code
Summary
Comprehensions, iterables, and generators
Comprehensions
List comprehensions
List comprehension syntax
Elements of a list comprehension
Set comprehensions
Dictionary comprehensions
Comprehension complexity
Filtering comprehensions
Combining filtering and transformation
Moment of zen
Iteration protocols
An example of the iteration protocols
A more practical example of the iteration protocols
Generator functions
The yield keyword
Generators are iterators
When is generator code executed?
Maintaining explicit state in the generator function
The first stateful generator: take()
The second stateful generator: distinct()
Understand these generators!
Lazy generator pipelines
Laziness and the infinite
Generating the Lucas series
Generator expressions
Batteries included iteration tools
Introducing itertools
Sequences of booleans
Merging sequences with zip
More than two sequences with zip()
Lazily concatenating sequences with chain()
Pulling it all together
Summary
Generators
Iteration tools
Defining new types with classes
Defining classes
Instance methods
Instance initializers
A lack of access modifiers
Validation and invariants
Adding a second class
Collaborating classes
Moment of zen
Booking seats
Allocating seats to passengers
Naming methods for implementation details
Implementing relocate_passenger()
Counting available seats
Sometimes the only object you need is a function
Making Flight create boarding cards
Polymorphism and duck-typing
Refactoring Aircraft
Inheritance and implementation sharing
A base class for aircraft
Inheriting from Aircraft
Hoisting common functionality into a base class
Summary
Files and Resource Management
Files
Binary and text modes
The important of encoding
Opening a file for writing
Writing to files
Closing files
The file outside of Python
Reading files
Readline line by line
Reading multiple lines at once
Appending to files
File objects as iterators
Context Managers
Managing resources with finally
The with-blocks
Moment of zen
Binary files
The BMP file format
Bitwise operators
Writing a BMP file
Reading binary files
File-like objects
You've already seen file-like objects!
Using file-like objects
Other resources
Summary
Unit testing with the Python standard library
Test cases
Fixtures
Assertions
Unit testing example: text analysis
Running the initial tests
Making the test pass
Using fixtures to create temporary files
Using the new fixtures
Using assertions to test behavior
Counting lines
Counting characters
Testing for exceptions
Testing for file existence
Moment of zen
Summary
Debugging with PDB
Debugging commands
Palindrome debugging
Bug hunting with PDB
Finding infinite loops with sampling
Setting explicit breaks
Stepping through execution
Fixing the bug
Summary
Afterword – Just the Beginning
Virtual Environments
Creating a virtual environment
Activating a virtual environment
Deactivating a virtual environment
Other tools for working with virtual environments
Packaging and Distribution
Configuring a package with distutils
Installing with distutils
Packaging with distutils
Installing Third-Party Packages
Installing pip
The Python Package Index
Installing with pip
Installing Local Packages with pip
Uninstalling Packages
← Prev
Back
Next →
← Prev
Back
Next →