Cover image for Introducing Python

Book Description

Easy to understand and fun to read, Introducing Python is ideal for beginning programmers as well as those new to the language. Author Bill Lubanovic takes you from the basics to more involved and varied topics, mixing tutorials with cookbook-style code recipes to explain concepts in Python 3. End-of-chapter exercises help you practice what you’ve learned.

Table of Contents

  1. Dedication
  2. Preface
    1. Audience
    2. Outline
    3. Python Versions
    4. Conventions Used in This Book
    5. Using Code Examples
    6. Safari® Books Online
    7. How to Contact Us
    8. Acknowledgments
  3. 1. A Taste of Py
    1. Python in the Real World
    2. Python versus Language X
    3. So, Why Python?
    4. When Not to Use Python
    5. Python 2 versus Python 3
    6. Installing Python
    7. Running Python
      1. Using the Interactive Interpreter
      2. Use Python Files
      3. What’s Next?
    8. Your Moment of Zen
    9. Things to Do
  4. 2. Py Ingredients: Numbers, Strings, and Variables
    1. Variables, Names, and Objects
    2. Numbers
      1. Integers
      2. Precedence
      3. Bases
      4. Type Conversions
      5. How Big Is an int?
      6. Floats
      7. Math Functions
    3. Strings
      1. Create with Quotes
      2. Convert Data Types by Using str()
      3. Escape with \
      4. Combine with +
      5. Duplicate with *
      6. Extract a Character with []
      7. Slice with [
      8. Get Length with len()
      9. Split with split()
      10. Combine with join()
      11. Playing with Strings
      12. Case and Alignment
      13. Substitute with replace()
      14. More String Things
    4. Things to Do
  5. 3. Py Filling: Lists, Tuples, Dictionaries, and Sets
    1. Lists and Tuples
    2. Lists
      1. Create with [] or list()
      2. Convert Other Data Types to Lists with list()
      3. Get an Item by Using [
      4. Lists of Lists
      5. Change an Item by [
      6. Get a Slice to Extract Items by Offset Range
      7. Add an Item to the End with append()
      8. Combine Lists by Using extend() or +=
      9. Add an Item by Offset with insert()
      10. Delete an Item by Offset with del
      11. Delete an Item by Value with remove()
      12. Get an Item by Offset and Delete It by Using pop()
      13. Find an Item’s Offset by Value with index()
      14. Test for a Value with in
      15. Count Occurrences of a Value by Using count()
      16. Convert to a String with join()
      17. Reorder Items with sort()
      18. Get Length by Using len()
      19. Assign with =, Copy with copy()
    3. Tuples
      1. Create a Tuple by Using ()
      2. Tuples versus Lists
    4. Dictionaries
      1. Create with {}
      2. Convert by Using dict()
      3. Add or Change an Item by [
      4. Combine Dictionaries with update()
      5. Delete an Item by Key with del
      6. Delete All Items by Using clear()
      7. Test for a Key by Using in
      8. Get an Item by [
      9. Get All Keys by Using keys()
      10. Get All Values by Using values()
      11. Get All Key-Value Pairs by Using items()
      12. Assign with =, Copy with copy()
    5. Sets
      1. Create with set()
      2. Convert from Other Data Types with set()
      3. Test for Value by Using in
      4. Combinations and Operators
    6. Compare Data Structures
    7. Make Bigger Data Structures
    8. Things to Do
  6. 4. Py Crust: Code Structures
    1. Comment with #
    2. Continue Lines with \
    3. Compare with if, elif, and else
      1. What Is True?
    4. Repeat with while
      1. Cancel with break
      2. Skip Ahead with continue
      3. Check break Use with else
    5. Iterate with for
      1. Cancel with break
      2. Skip with continue
      3. Check break Use with else
      4. Iterate Multiple Sequences with zip()
      5. Generate Number Sequences with range()
      6. Other Iterators
    6. Comprehensions
      1. List Comprehensions
      2. Dictionary Comprehensions
      3. Set Comprehensions
      4. Generator Comprehensions
    7. Functions
      1. Positional Arguments
      2. Keyword Arguments
      3. Specify Default Parameter Values
      4. Gather Positional Arguments with *
      5. Gather Keyword Arguments with **
      6. Docstrings
      7. Functions Are First-Class Citizens
      8. Inner Functions
      9. Closures
      10. Anonymous Functions: the lambda() Function
    8. Generators
    9. Decorators
    10. Namespaces and Scope
      1. Uses of _ and __ in Names
    11. Handle Errors with try and except
    12. Make Your Own Exceptions
    13. Things to Do
  7. 5. Py Boxes: Modules, Packages, and Programs
    1. Standalone Programs
    2. Command-Line Arguments
    3. Modules and the import Statement
      1. Import a Module
      2. Import a Module with Another Name
      3. Import Only What You Want from a Module
      4. Module Search Path
    4. Packages
    5. The Python Standard Library
      1. Handle Missing Keys with setdefault() and defaultdict()
      2. Count Items with Counter()
      3. Order by Key with OrderedDict()
      4. Stack + Queue == deque
      5. Iterate over Code Structures with itertools
      6. Print Nicely with pprint()
    6. More Batteries: Get Other Python Code
    7. Things to Do
  8. 6. Oh Oh: Objects and Classes
    1. What Are Objects?
    2. Define a Class with class
    3. Inheritance
    4. Override a Method
    5. Add a Method
    6. Get Help from Your Parent with super
    7. In self Defense
    8. Get and Set Attribute Values with Properties
    9. Name Mangling for Privacy
    10. Method Types
    11. Duck Typing
    12. Special Methods
    13. Composition
    14. When to Use Classes and Objects versus Modules
      1. Named Tuples
    15. Things to Do
  9. 7. Mangle Data Like a Pro
    1. Text Strings
      1. Unicode
        1. Python 3 Unicode strings
        2. Encode and decode with UTF-8
        3. Encoding
        4. Decoding
        5. For more information
      2. Format
        1. Old style with %
        2. New style formatting with {} and format
      3. Match with Regular Expressions
        1. Exact match with match()
        2. First match with search()
        3. All matches with findall()
        4. Split at matches with split()
        5. Replace at matches with sub()
        6. Patterns: special characters
        7. Patterns: using specifiers
        8. Patterns: specifying match output
    2. Binary Data
      1. bytes and bytearray
      2. Convert Binary Data with struct
      3. Other Binary Data Tools
      4. Convert Bytes/Strings with binascii()
      5. Bit Operators
    3. Things to Do
  10. 8. Data Has to Go Somewhere
    1. File Input/Output
      1. Write a Text File with write()
      2. Read a Text File with read(), readline(), or readlines()
      3. Write a Binary File with write()
      4. Read a Binary File with read()
      5. Close Files Automatically by Using with
      6. Change Position with seek()
    2. Structured Text Files
      1. CSV
      2. XML
      3. HTML
      4. JSON
      5. YAML
      6. A Security Note
      7. Configuration Files
      8. Other Interchange Formats
      9. Serialize by Using pickle
    3. Structured Binary Files
      1. Spreadsheets
      2. HDF5
    4. Relational Databases
      1. SQL
      2. DB-API
      3. SQLite
      4. MySQL
      5. PostgreSQL
      6. SQLAlchemy
        1. The engine layer
        2. The SQL Expression Language
        3. The Object-Relational Mapper
    5. NoSQL Data Stores
      1. The dbm Family
      2. Memcached
      3. Redis
        1. Strings
        2. Lists
        3. Hashes
        4. Sets
        5. Sorted sets
        6. Bits
        7. Caches and expiration
      4. Other NoSQL
    6. Full-Text Databases
    7. Things to Do
  11. 9. The Web, Untangled
    1. Web Clients
      1. Test with telnet
      2. Python’s Standard Web Libraries
      3. Beyond the Standard Library: Requests
    2. Web Servers
      1. The Simplest Python Web Server
      2. Web Server Gateway Interface
      3. Frameworks
      4. Bottle
      5. Flask
        1. Pass an argument as part of the URL path
      6. Non-Python Web Servers
        1. Apache
        2. The nginx Web Server
      7. Other Frameworks
        1. Other Python Web Servers
    3. Web Services and Automation
      1. The webbrowser Module
      2. Web APIs and Representational State Transfer
      3. JSON
      4. Crawl and Scrape
      5. Scrape HTML with BeautifulSoup
    4. Things to Do
  12. 10. Systems
    1. Files
      1. Create with open()
      2. Check Existence with exists()
      3. Check Type with isfile()
      4. Copy with copy()
      5. Change Name with rename()
      6. Link with link() or symlink()
      7. Change Permissions with chmod()
      8. Change Ownership with chown()
      9. Get a Pathname with abspath()
      10. Get a symlink Pathname with realpath()
      11. Delete a File with remove()
    2. Directories
      1. Create with mkdir()
      2. Delete with rmdir()
      3. List Contents with listdir()
      4. Change Current Directory with chdir()
      5. List Matching Files with glob()
    3. Programs and Processes
      1. Create a Process with subprocess
      2. Create a Process with multiprocessing
      3. Kill a Process with terminate()
    4. Calendars and Clocks
      1. The datetime Module
      2. Using the time Module
      3. Read and Write Dates and Times
      4. Alternative Modules
    5. Things to Do
  13. 11. Concurrency and Networks
    1. Concurrency
      1. Queues
      2. Processes
      3. Threads
      4. Green Threads and gevent
      5. twisted
      6. asyncio
      7. Redis
      8. Beyond Queues
    2. Networks
      1. Patterns
      2. The Publish-Subscribe Model
        1. Redis
        2. ZeroMQ
        3. Other Pub-sub Tools
      3. TCP/IP
      4. Sockets
      5. ZeroMQ
      6. Scapy
      7. Internet Services
        1. Domain Name System
        2. Python Email Modules
        3. Other protocols
      8. Web Services and APIs
      9. Remote Processing
        1. Remote Procedure Calls
        2. fabric
        3. Salt
      10. Big Fat Data and MapReduce
      11. Working in the Clouds
        1. Google
        2. Amazon
        3. OpenStack
    3. Things to Do
  14. 12. Be a Pythonista
    1. About Programming
    2. Find Python Code
    3. Install Packages
      1. Use pip
      2. Use a Package Manager
      3. Install from Source
    4. Integrated Development Environments
      1. IDLE
      2. PyCharm
      3. IPython
    5. Name and Document
    6. Testing Your Code
      1. Check with pylint, pyflakes, and pep8
      2. Test with unittest
      3. Test with doctest
      4. Test with nose
      5. Other Test Frameworks
      6. Continuous Integration
    7. Debugging Python Code
    8. Debug with pdb
    9. Logging Error Messages
    10. Optimize Your Code
      1. Measure Timing
      2. Algorithms and Data Structures
      3. Cython, NumPy, and C Extensions
      4. PyPy
    11. Source Control
      1. Mercurial
      2. Git
    12. Clone This Book
    13. How You Can Learn More
      1. Books
      2. Websites
      3. Groups
      4. Conferences
    14. Coming Attractions
  15. A. Py Art
    1. 2-D Graphics
      1. Standard Library
      2. PIL and Pillow
      3. ImageMagick
    2. Graphical User Interfaces (GUIs)
    3. 3-D Graphics and Animation
    4. Plots, Graphs, and Visualization
      1. matplotlib
      2. bokeh
    5. Games
    6. Audio and Music
  16. B. Py at Work
    1. The Microsoft Office Suite
    2. Carrying Out Business Tasks
    3. Processing Business Data
      1. Extracting, Transforming, and Loading
      2. Additional Sources of Information
    4. Python in Finance
    5. Business Data Security
    6. Maps
      1. Formats
      2. Draw a Map
      3. Applications and Data
  17. C. Py Sci
    1. Math and Statistics in the Standard Library
      1. Math Functions
      2. Working with Complex Numbers
      3. Calculate Accurate Floating Point with decimal
      4. Perform Rational Arithmetic with fractions
      5. Use Packed Sequences with array
      6. Handling Simple Stats by Using statistics
      7. Matrix Multiplication
    2. Scientific Python
    3. NumPy
      1. Make an Array with array()
      2. Make an Array with arange()
      3. Make an Array with zeros(), ones(), or random()
      4. Change an Array’s Shape with reshape()
      5. Get an Element with []
      6. Array Math
      7. Linear Algebra
    4. The SciPy Library
    5. The SciKit Library
    6. The IPython Library
      1. A Better Interpreter
      2. IPython Notebook
    7. Pandas
    8. Python and Scientific Areas
  18. D. Install Python 3
    1. Install Standard Python
      1. Mac OS X
      2. Windows
      3. Linux or Unix
    2. Install Anaconda
    3. Install and Use pip and virtualenv
    4. Install and Use conda
  19. E. Answers to Exercises
    1. Chapter 1,
    2. Chapter 2,
    3. Chapter 3,
    4. Chapter 4,
    5. Chapter 5,
    6. Chapter 6,
    7. Chapter 7,
    8. Chapter 8,
    9. Chapter 9,
    10. Chapter 10,
    11. Chapter 11,
  20. F. Cheat Sheets
    1. Operator Precedence
    2. String Methods
      1. Change Case
      2. Search
      3. Modify
      4. Format
      5. String Type
    3. String Module Attributes
    4. Fin
  21. Index
  22. Colophon
  23. Copyright