內容大鋼
本書面向Python零基礎學習者構建了循序漸進的完整知識體系。
全書分為三大核心板塊:第一部分「基礎要塞」從Python環境搭建起步,逐一講解類型變數、數值、字元串、位元組序列、流程式控制制、元組列表、字典集合、函數與面向對象等核心語法,配套隨堂練習鞏固基礎認知。第二部分「工具集」聚焦Python開發全流程實用技能,覆蓋模塊包管理、開發環境配置、類型提示規範、測試與調試方法,幫讀者建立標準化工程思維。第三部分「進階探索」延伸至文本處理、二進位操作、日期處理、文件IO、併發編程、網路開發、數據持久化、Web開發、數據科學、AI應用與性能優化等前沿實用場景,完整覆蓋Python主流應用方向。
全書內容兼顧基礎嚴謹性與技術時效性,配套大量實操案例與練習答案,是適合入門讀者從零掌握Python、銜接工業級應用的全面指南。
目錄
Preface
Part I. Stronghold
1. Introduction
Mysteries
Little Python Programs
Setup
Install Python
Upgrade Python
Run Python Programs
The Python Interactive Interpreter
Python Files
Built-In Python Features
The Python Standard Library
Third-Party Python Packages
A Bigger Example
Review/Preview
2. Types and Variables
A Computer
Bits and Bytes
Multibyte Types
Variables
Assign a Value to a Variable
Change the Value of a Variable
Delete a Variable
Name Variables
Follow Naming Conventions
Python Types
Specify Values
Objects as Plastic Boxes in Memory
Review/Preview
Practice
3. Numbers
Booleans
Integers
Literal Integers
Integer Operations
Integers and Variables
Precedence
Bases
Type Conversions
How Big Is an int?
Floats
Floats Are Not Exact
Fractions
Decimals
Math Functions
Review/Preview
Practice
4. Strings
Create with Quotes
Create with str()
Escape with \
Combine with +
Duplicate with *
Get a Character by [ offset ]
Get a Substring with a Slice
Get Length with len()
Split with split()
Combine with join()
Substitute with replace()
Work with Prefixes and Suffixes
Strip with strip()
Search and Select
Change Case
Set Alignment
Apply Formatting
Old style: %
New style: {} and format()
Newest Style: f-strings
Review/Preview
Practice
5. Bytes and Bytearray
Bytes
Create with Quotes
Create with bytes()
Create from a Hex String
Decode and Encode Bytes and Strings
Convert to a Hex String
Get One Byte by [ offset ]
Get a Slice
Combine with +
Repeat with *
Bytearray
Create with bytearray()
Get One Byte by [ offset ]
Get Multiple Bytes with a Slice
Modify One Byte by [ offset ]
Modify Multiple Bytes with replace()
Modify Multiple Bytes with a Slice
Insert a Byte with insert()
Append One Byte with append()
Append Multiple Bytes with extend()
Combine with +
Repeat with *
Review/Preview
Practice
6. If and Match
Comment with #
Continue Lines with \
Compare with if, elif, and else
TileDB
Relational Databases
SQL
DB-API
SQLite
DuckDB
MySQL
PostgreSQL
SQLAlchemy
Other Database Access Packages
NoSQL Data Stores
The dbm Family
Memcached
Redis
Redis Alternative: Valkey?
Document Databases
Time-Series Databases
Graph Databases
Other NoSQL
Full-Text Databases
Vector Databases
Geospatial Databases
Review/Preview
Practice
24. The Web
Web Basics
HTTP Testing
Telnet
curl
HTTPie
httpbin
Web Clients
The Standard Library
Requests
Other Web Clients
Web Servers
The Simplest Python Web Server
Web Server Gateway Interface
ASGI
Apache
NGINX
Other Python Web Servers
Web Server Frameworks
Bottle
Flask
Django
FastAPI
Litestar
Database Frameworks
Web Services and Automation
webbrowser
webview
Web APIs and REST
WebSockets
Webhooks
Web Frontends
htmx
FastHTML
Crawl and Scrape
Scrapy
Beautiful Soup
Requests-HTML
Let's Watch a Movie
Review/Preview
Practice
25. Data Science
Standard Python
Format Conversions
Math
Complex Numbers
Calculate Accurate Floating Point Values with decimal
Perform Rational Arithmetic with fractions
Use Packed Sequences with array
Statistics
Matrix Multiplication
NumPy
Make an Array with array()
Make an Array with arange()
Make an Array with zeros(), ones(), or random()
Change an Array's Shape with reshape()
Get an Element with []
Array Math
Linear Algebra
SciPy
pandas
Polars
DuckDB
Data Visualization
Review/Preview
Practice
26. AI...
It Turns Out...
Expert Systems
Perceptrons
The Breakthrough
Image Recognition: ImageNet and AlexNet
Large Language Models
The ChatGPT Moment
Retrieval Augmented Generation
Agents
Efficiency
Create Models: Python Frameworks
Current Models
A Million Models: Hugging Face
Working Examples With Ollama
Install Ollama
Choose a Model
Choose Another Model
Ollama References
References
Review/Preview
Practice
27. Performance
Computer Hardware
Measure Timing
Profile
Algorithms and Data Structures
Arrays Versus Lists and Tuples
Cache
Cython
NumPy and SciPy
C or Rust Extensions
Taichi
PyPy
Numba
Standard Python JIT
Mojo
Background
Design
Examples
Limitations
Conclusion
Review/Preview
Practice
Appendix: Practice Answers
Index
What Is True?
Do Multiple Comparisons with in
New: I Am the Walrus
Match
Simple Matches
Structural Matches
Review/Preview
Practice
7. For and While
Repeat with while
Cancel with break
Skip Ahead with continue
Check break Use with else
Iterate with for and in
Cancel with break
Skip with continue
Check break Use with else
Generate Number Sequences with range()
Review/Preview
Practice
8. Tuples and Lists
Tuples
Create with Commas and ()
Create with tuple()
Get an Item by [ offset ]
Combine with +
Duplicate with *
Compare
Iterate with for and in
Modify?
Lists
Create with []
Create or Convert with list()
Create from a String with split()
Get an Item by [ offset ]
Get Items with a Slice
Add an Item to the End with append()
Add an Item by Offset with insert()
Duplicate with *
Combine with extend() or +
Change an Item with [ offset ]
Change Items with a Slice
Delete an Item by Offset with del
Delete an Item by Value with remove()
Get an Item by Offset and Delete It with pop()
Delete All Items with clear()
Find an Item's Offset by Value with index()
Test for a Value with in
Count Occurrences of a Value with count()
Convert a List to a String with join()
Reorder Items with sort() or sorted()
Get Length with len()
Assign with =
Copy with copy(), list(), or a Slice
Copy Everything with deepcopy()
Compare Lists
Iterate with for and in
Iterate Multiple Sequences with zip()
Iterate Multiple Sequences with zip_longest()
Create a List with a Comprehension
Create Lists of Lists
Tuples Versus Lists
There Are No Tuple Comprehensions
Review/Preview
Practice
9. Dictionaries and Sets
Dictionaries
Create with {}
Create with dict()
Convert with dict()
Add or Change an Item by [ key ]
Get an Item by [ key ] or with get()
Iterate with for and in
Get Length with len()
Combine/update dicts
Delete an Item by Key with del
Get an Item by Key and Delete It with pop( key )
Delete All Items with clear()
Test for a Key with in
Assign with =
Copy with copy()
Copy Everything with deepcopy()
Compare Dictionaries
Use Dictionary Comprehensions
Sets
Create with set() or {}
Get Length with len()
Add an Item with add()
Delete an Item with remove()
Combine with |
Iterate with for and in
Test for a Value with in
Use Combinations and Operators
Create Set Comprehensions
Create an Immutable Set with frozenset()
Review/Preview
Practice
10. Functions
Define a Function with def
Call a Function with Parentheses
Arguments and Parameters
None, Truthiness, and Falsiness
Positional Arguments
Keyword Arguments
Default Parameter Values
Pack/Unpack Positional Arguments with *
Pack/Unpack Keyword Arguments with **
Keyword-Only (*) and Position-Only () Arguments
Mutable and Immutable Arguments
Docstrings
Functions Are First-Class Citizens
Function Arguments Are Not a Tuple
Inner Functions
Closures
Anonymous Functions: Lambda
Generators
Generator Functions
Generator Comprehensions
Decorators
Namespaces and Scope
Dunder Names
Recursion
Async Functions, Briefly
Exceptions
Handle Errors with try and except
Use Finally
Make Your Own Exceptions
Review/Preview
Practice
11. Objects
What Are Objects?
Simple Objects
Define a Class with class
Assign Attributes
Methods
Initialization
Inheritance
Inherit from a Parent Class
Override a Method
Add a Method
Get Help from Your Parent with super()
Use Multiple Inheritance
Include Mixins
In self Defense
Attribute Access
Direct Access
Getters and Setters
Properties for Attribute Access
Properties for Computed Values
Name Mangling for Privacy
Class and Object Attributes
Method Types
Instance Methods
Class Methods
Static Methods
Duck Typing
Magic Methods
Aggregation and Composition
When to Use Objects or Something Else
Named Tuples
Dataclasses
Attrs
Review/Preview
Practice
Part II. Tools
12. Modules and Packages
Modules and the import Statement
Import a Module
Import a Module with Another Name
Import Only What You Want from a Module
Packages
The Module Search Path
Relative and Absolute Imports
Namespace Packages
Modules Versus Objects
Goodies in the Python Standard Library
Handle Missing Keys with setdefault() and defaultdict()
Count Items with Counter()
Order by Key with OrderedDict()
Stack + Queue == deque
Iterate over Code Structures with itertols
Get Random
More Batteries: Get Other Python Code
Review/Preview
Practice
13. Development Environment
Find Python Code
Install Packages
Use Pip
Install with a Native Package Manager
Install from Source
Virtual Environments
Virtualenv and Venv
Pipenv
Poetry
Conda
uv
Integrated Development Environments
IPython
Jupyter Notebook
JupyterLab
Source Control
Mercurial
Git
Review/Preview
Practice
14. Type Hints and Documentation
Type Hints
Variable Hints
Function Hints
Mypy
Documentation
Comments
Docstrings
Markup Text Files
Review/Preview
Practice
15. Testing
Pylint
Ruff
Unittest
Doctest
Pytest
Examples
Fixtures
Parametrization
Hypothesis
Nox
Continuous Integration
Review/Preview
Practice
16. Debugging
Assert
Print
F-strings
Pprint()
IceCream
Decorators
Logging
Pdb
Breakpoint()
Review/Preview
Practice
Part III. Quests
17. Text Data
Text Strings: Unicode
Python Unicode Strings
UTF-8
Encode
Decode
HTML Entities
Normalization
Text Strings: Regular Expressions
Find Exact Beginning Match with match()
Find First Match with search()
Find All Matches with findall()
Split at Matches with split()
Replace at Matches with sub()
Patterns
Using Special Characters
Using Specifiers
Specifying match() Output
Review/Preview
Practice
18. Binary Data
Convert Binary Data with struct
Extraction with Binary Data Tools
Convert Bytes/Strings with binascii()
Use Bit Operators
Review/Preview
Practice
19. Dates and Times
Leap Year
The datetime Module
The time Module
Read and Write Dates and Times
All the Conversions
Alternative Modules
Review/Preview
Practice
20. Files
File Input and Output
Create or Open with open()
Write a Text File with print()
Write a Text File with write()
Read a Text File with read(), readline(), or readlines()
Write a Binary File with write()
Read a Binary File with read()
Close Files Automatically by Using with
Change Position with seek()
Memory Mapping
File Operations
Check Existence with exists()
Check Type with isfile()
Copy with copy()
Change Name with rename()
Link with link() or symlink()
Change Permissions with chmod()
Change Ownership with chown()
Delete a File with remove()
Directory Operations
Create with mkdir()
Delete with rmdir()
List Contents with listdir()
Change Current Directory with chdir()
List Matching Files with glob()
Pathnames
Get a Pathname with abspath()
Get a symlink Pathname with realpath()
Build a Pathname with os.path.join()
Use pathlib
BytesIO and StringIO
File Formats: Determination
Review/Preview
Practice
21. Data in Time: Concurrency
Programs and Processes
Create a Process with subprocess
Create a Process with multiprocessing
Kill a Process with terminate()
Get System Info with os
Get Process Info with psutil
Command Automation
Invoke
Other Command Helpers
Concurrency
Queues
Processes
Threads
The GIL
Concurrent.futures
Green Threads and gevent
Twisted
asyncio
Coroutines and Event Loops
Asyncio Alternatives
Async Versus...
Async Frameworks and Servers
Redis
Beyond Queues
Review/Preview
Practice
22. Data in Space: Networks
TCP/IP
Sockets
Scapy
Netcat
Networking Patterns
The Request-Reply Pattern
Request-Reply: ZeroMQ
Request-Reply: Other Messaging Tools
The Publish-Subscribe Pattern
Pub-Sub: Redis
Pub-Sub: ZeroMQ
Pub-Sub: Other Tools
Internet Services
Domain Name System
Python Email Modules
Other Protocols
Web Services and APIs
Data Serialization
Serialize with pickle
Use Other Serialization Formats
Remote Procedure Calls
XML-RPC
JSON RPC
MessagePack RPC
zerorpc
gRPC
Remote Management
Big Fat Data
Hadoop
Spark
Disco
Dask
Clouds
Amazon Web Services
Google Cloud
Microsoft Azure
OpenStack
Docker
Kubernetes
Review/Preview
Practice
23. Data in a Box: Persistent Storage
Text Files
Tabular and Delimited Text Files
CSV
XML
An XML Security Note
HTML
JSON
YAML
TOML
Tablib
Configuration Files
Binary Files
Padded Binary Files and Memory Mapping
Spreadsheets
HDF5