Supercharged Python: Take Your Code to the Next Level, First Edition

Book description

“Brian Overland makes programming simple. . . . To my amazement, his books explain complicated code clearly enough for anyone to understand.”
—Art Sedighi, PhD

Tapping into the full power of Python doesn't have to be difficult. Supercharged Python is written for people who've learned the fundamentals of the language but want to take their skills to the next level.

After a quick review of Python, the book covers: advanced list and string techniques; all the ways to handle text and binary files; financial applications; advanced techniques for writing classes; generators and decorators; and how to master packages such as Numpy (Numeric Python) to supercharge your applications!

  • Use profilers and “magic methods” to code like a pro
  • Harness the power of regular expressions to process text quickly with a single statement
  • Take advantage of 22 coding shortcuts, along with performance tips, to save time and optimize your code
  • Create really useful classes and objects, for games, simulations, money, mathematics, and more
  • Use multiple modules to build powerful apps while avoiding the “gotchas”
  • Import packages to dramatically speed up statistical operations–by as much as 100 times!
  • Refer to the five-part language reference to look up fine points of the language

Supercharged Python demonstrates techniques that allow you to write faster and more powerful code, whether you're manipulating large amounts of data or building sophisticated applications.

Register your book for convenient access to downloads, updates, and/or corrections as they become available. See inside book for details.

Table of contents

  1. Cover Page
  2. About This eBook
  3. Half Title
  4. Title Page
  5. Copyright Page
  6. Dedication Page
  7. Contents
  8. Preface
    1. What Makes Python Special?
    2. Paths to Learning: Where Do I Start?
    3. Clarity and Examples Are Everything
    4. Learning Aids: Icons
    5. What You’ll Learn
    6. Have Fun
  9. Acknowledgments
  10. About the Authors
  11. 1. Review of the Fundamentals
    1. 1.1 Python Quick Start
    2. 1.2 Variables and Naming Names
    3. 1.3 Combined Assignment Operators
    4. 1.4 Summary of Python Arithmetic Operators
    5. 1.5 Elementary Data Types: Integer and Floating Point
    6. 1.6 Basic Input and Output
    7. 1.7 Function Definitions
    8. 1.8 The Python “if” Statement
    9. 1.9 The Python “while” Statement
    10. 1.10 A Couple of Cool Little Apps
    11. 1.11 Summary of Python Boolean Operators
    12. 1.12 Function Arguments and Return Values
    13. 1.13 The Forward Reference Problem
    14. 1.14 Python Strings
    15. 1.15 Python Lists (and a Cool Sorting App)
    16. 1.16 The “for” Statement and Ranges
    17. 1.17 Tuples
    18. 1.18 Dictionaries
    19. 1.19 Sets
    20. 1.20 Global and Local Variables
    21. Summary
    22. Review Questions
    23. Suggested Problems
  12. 2. Advanced String Capabilities
    1. 2.1 Strings Are Immutable
    2. 2.2 Numeric Conversions, Including Binary
    3. 2.3 String Operators (+, =, *, >, etc.)
    4. 2.4 Indexing and Slicing
    5. 2.5 Single-Character Functions (Character Codes)
    6. 2.6 Building Strings Using “join”
    7. 2.7 Important String Functions
    8. 2.8 Binary, Hex, and Octal Conversion Functions
    9. 2.9 Simple Boolean (“is”) Methods
    10. 2.10 Case Conversion Methods
    11. 2.11 Search-and-Replace Methods
    12. 2.12 Breaking Up Input Using “split”
    13. 2.13 Stripping
    14. 2.14 Justification Methods
    15. Summary
    16. Review Questions
    17. Suggested Problems
  13. 3. Advanced List Capabilities
    1. 3.1 Creating and Using Python Lists
    2. 3.2 Copying Lists Versus Copying List Variables
    3. 3.3 Indexing
    4. 3.4 Getting Data from Slices
    5. 3.5 Assigning into Slices
    6. 3.6 List Operators
    7. 3.7 Shallow Versus Deep Copying
    8. 3.8 List Functions
    9. 3.9 List Methods: Modifying a List
    10. 3.10 List Methods: Getting Information on Contents
    11. 3.11 List Methods: Reorganizing
    12. 3.12 Lists as Stacks: RPN Application
    13. 3.13 The “reduce” Function
    14. 3.14 Lambda Functions
    15. 3.15 List Comprehension
    16. 3.16 Dictionary and Set Comprehension
    17. 3.17 Passing Arguments Through a List
    18. 3.18 Multidimensional Lists
    19. Summary
    20. Review Questions
    21. Suggested Problems
  14. 4. Shortcuts, Command Line, and Packages
    1. 4.1 Overview
    2. 4.2 Twenty-Two Programming Shortcuts
    3. 4.3 Running Python from the Command Line
    4. 4.4 Writing and Using Doc Strings
    5. 4.5 Importing Packages
    6. 4.6 A Guided Tour of Python Packages
    7. 4.7 Functions as First-Class Objects
    8. 4.8 Variable-Length Argument Lists
    9. 4.9 Decorators and Function Profilers
    10. 4.10 Generators
    11. 4.11 Accessing Command-Line Arguments
    12. Summary
    13. Questions for Review
    14. Suggested Problems
  15. 5. Formatting Text Precisely
    1. 5.1 Formatting with the Percent Sign Operator (%)
    2. 5.2 Percent Sign (%) Format Specifiers
    3. 5.3 Percent Sign (%) Variable-Length Print Fields
    4. 5.4 The Global “format” Function
    5. 5.5 Introduction to the “format” Method
    6. 5.6 Ordering by Position (Name or Number)
    7. 5.7 “Repr” Versus String Conversion
    8. 5.8 The “spec” Field of the “format” Function and Method
    9. 5.9 Variable-Size Fields
    10. Summary
    11. Review Questions
    12. Suggested Problems
  16. 6. Regular Expressions, Part I
    1. 6.1 Introduction to Regular Expressions
    2. 6.2 A Practical Example: Phone Numbers
    3. 6.3 Refining Matches
    4. 6.4 How Regular Expressions Work: Compiling Versus Running
    5. 6.5 Ignoring Case, and Other Function Flags
    6. 6.6 Regular Expressions: Basic Syntax Summary
    7. 6.7 A Practical Regular-Expression Example
    8. 6.8 Using the Match Object
    9. 6.9 Searching a String for Patterns
    10. 6.10 Iterative Searching (“findall”)
    11. 6.11 The “findall” Method and the Grouping Problem
    12. 6.12 Searching for Repeated Patterns
    13. 6.13 Replacing Text
    14. Summary
    15. Review Questions
    16. Suggested Problems
  17. 7. Regular Expressions, Part II
    1. 7.1 Summary of Advanced RegEx Grammar
    2. 7.2 Noncapture Groups
    3. 7.3 Greedy Versus Non-Greedy Matching
    4. 7.4 The Look-Ahead Feature
    5. 7.5 Checking Multiple Patterns (Look-Ahead)
    6. 7.6 Negative Look-Ahead
    7. 7.7 Named Groups
    8. 7.8 The “re.split” Function
    9. 7.9 The Scanner Class and the RPN Project
    10. 7.10 RPN: Doing Even More with Scanner
    11. Summary
    12. Review Questions
    13. Suggested Problems
  18. 8. Text and Binary Files
    1. 8.1 Two Kinds of Files: Text and Binary
    2. 8.2 Approaches to Binary Files: A Summary
    3. 8.3 The File/Directory System
    4. 8.4 Handling File-Opening Exceptions
    5. 8.5 Using the “with” Keyword
    6. 8.6 Summary of Read/Write Operations
    7. 8.7 Text File Operations in Depth
    8. 8.8 Using the File Pointer (“seek”)
    9. 8.9 Reading Text into the RPN Project
    10. 8.10 Direct Binary Read/Write
    11. 8.11 Converting Data to Fixed-Length Fields (“struct”)
    12. 8.12 Using the Pickling Package
    13. 8.13 Using the “shelve” Package
    14. Summary
    15. Review Questions
    16. Suggested Problems
  19. 9. Classes and Magic Methods
    1. 9.1 Classes and Objects: Basic Syntax
    2. 9.2 More About Instance Variables
    3. 9.3 The “_ _init_ _” and “_ _new_ _” Methods
    4. 9.4 Classes and the Forward Reference Problem
    5. 9.5 Methods Generally
    6. 9.6 Public and Private Variables and Methods
    7. 9.7 Inheritance
    8. 9.8 Multiple Inheritance
    9. 9.9 Magic Methods, Summarized
    10. 9.10 Magic Methods in Detail
    11. 9.11 Supporting Multiple Argument Types
    12. 9.12 Setting and Getting Attributes Dynamically
    13. Summary
    14. Review Questions
    15. Suggested Problems
  20. 10. Decimal, Money, and Other Classes
    1. 10.1 Overview of Numeric Classes
    2. 10.2 Limitations of Floating-Point Format
    3. 10.3 Introducing the Decimal Class
    4. 10.4 Special Operations on Decimal Objects
    5. 10.5 A Decimal Class Application
    6. 10.6 Designing a Money Class
    7. 10.7 Writing the Basic Money Class (Containment)
    8. 10.8 Displaying Money Objects (“_ _str_ _”, “_ _repr_ _”)
    9. 10.9 Other Monetary Operations
    10. 10.10 Demo: A Money Calculator
    11. 10.11 Setting the Default Currency
    12. 10.12 Money and Inheritance
    13. 10.13 The Fraction Class
    14. 10.14 The Complex Class
    15. Summary
    16. Review Questions
    17. Suggested Problems
  21. 11. The Random and Math Packages
    1. 11.1 Overview of the Random Package
    2. 11.2 A Tour of Random Functions
    3. 11.3 Testing Random Behavior
    4. 11.4 A Random-Integer Game
    5. 11.5 Creating a Deck Object
    6. 11.6 Adding Pictograms to the Deck
    7. 11.7 Charting a Normal Distribution
    8. 11.8 Writing Your Own Random-Number Generator
    9. 11.9 Overview of the Math Package
    10. 11.10 A Tour of Math Package Functions
    11. 11.11 Using Special Values (pi)
    12. 11.12 Trig Functions: Height of a Tree
    13. 11.13 Logarithms: Number Guessing Revisited
    14. Summary
    15. Review Questions
    16. Suggested Problems
  22. 12. The “numpy” (Numeric Python) Package
    1. 12.1 Overview of the “array,” “numpy,” and “matplotlib” Packages
    2. 12.2 Using the “array” Package
    3. 12.3 Downloading and Importing “numpy”
    4. 12.4 Introduction to “numpy”: Sum 1 to 1 Million
    5. 12.5 Creating “numpy” Arrays
    6. 12.6 Example: Creating a Multiplication Table
    7. 12.7 Batch Operations on “numpy” Arrays
    8. 12.8 Ordering a Slice of “numpy”
    9. 12.9 Multidimensional Slicing
    10. 12.10 Boolean Arrays: Mask Out That “numpy”!
    11. 12.11 “numpy” and the Sieve of Eratosthenes
    12. 12.12 Getting “numpy” Stats (Standard Deviation)
    13. 12.13 Getting Data on “numpy” Rows and Columns
    14. Summary
    15. Review Questions
    16. Suggested Problems
  23. 13. Advanced Uses of “numpy”
    1. 13.1 Advanced Math Operations with “numpy”
    2. 13.2 Downloading “matplotlib”
    3. 13.3 Plotting Lines with “numpy” and “matplotlib”
    4. 13.4 Plotting More Than One Line
    5. 13.5 Plotting Compound Interest
    6. 13.6 Creating Histograms with “matplotlib”
    7. 13.7 Circles and the Aspect Ratio
    8. 13.8 Creating Pie Charts
    9. 13.9 Doing Linear Algebra with “numpy”
    10. 13.10 Three-Dimensional Plotting
    11. 13.11 “numpy” Financial Applications
    12. 13.12 Adjusting Axes with “xticks” and “yticks”
    13. 13.13 “numpy” Mixed-Data Records
    14. 13.14 Reading and Writing “numpy” Data from Files
    15. Summary
    16. Review Questions
    17. Suggested Problems
  24. 14. Multiple Modules and the RPN Example
    1. 14.1 Overview of Modules in Python
    2. 14.2 Simple Two-Module Example
    3. 14.3 Variations on the “import” Statement
    4. 14.4 Using the “_ _all_ _” Symbol
    5. 14.5 Public and Private Module Variables
    6. 14.6 The Main Module and “_ _main_ _”
    7. 14.7 Gotcha! Problems with Mutual Importing
    8. 14.8 RPN Example: Breaking into Two Modules
    9. 14.9 RPN Example: Adding I/O Directives
    10. 14.10 Further Changes to the RPN Example
    11. 14.11 RPN: Putting It All Together
    12. Summary
    13. Review Questions
    14. Suggested Problems
  25. 15. Getting Financial Data off the Internet
    1. 15.1 Plan of This Chapter
    2. 15.2 Introducing the Pandas Package
    3. 15.3 “stock_load”: A Simple Data Reader
    4. 15.4 Producing a Simple Stock Chart
    5. 15.5 Adding a Title and Legend
    6. 15.6 Writing a “makeplot” Function (Refactoring)
    7. 15.7 Graphing Two Stocks Together
    8. 15.8 Variations: Graphing Other Data
    9. 15.9 Limiting the Time Period
    10. 15.10 Split Charts: Subplot the Volume
    11. 15.11 Adding a Moving-Average Line
    12. 15.12 Giving Choices to the User
    13. Summary
    14. Review Questions
    15. Suggested Problems
  26. A. Python Operator Precedence Table
  27. B. Built-In Python Functions
    1. abs(x)
    2. all(iterable)
    3. any(iterable)
    4. ascii(obj)
    5. bin(n)
    6. bool(obj)
    7. bytes(source, encoding)
    8. callable(obj)
    9. chr(n)
    10. compile(cmd_str, filename, mode_str, flags=0, dont_inherit=False, optimize=–1)
    11. complex(real=0, imag=0)
    12. complex(complex_str)
    13. delattr(obj, name_str)
    14. dir([obj])
    15. divmod(a, b)
    16. enumerate(iterable, start=0)
    17. eval(expr_str [, globals [, locals]] )
    18. exec(object [,global [,locals]])
    19. filter(function,iterable)
    20. float([x])
    21. format(obj, [format_spec])
    22. frozenset([iterable])
    23. getattr(obj,name_str [,default])
    24. globals()
    25. hasattr(obj,name_str)
    26. hash(obj)
    27. help([obj])
    28. hex(n)
    29. id(obj)
    30. input([prompt_str])
    31. int(x,base=10)
    32. int()
    33. isinstance(obj,class)
    34. issubclass(class1,class2)
    35. iter(obj)
    36. len(sequence)
    37. list([iterable])
    38. locals()
    39. map(function,iterable1 [,iterable2...])
    40. max(arg1 [, arg2]...)
    41. max(iterable)
    42. min(arg1 [, arg2]...)
    43. min(iterable)
    44. oct(n)
    45. open(file_name_str,mode=‘rt’)
    46. ord(char_str)
    47. pow(x,y [,z])
    48. print(objects,sep=‘‘,end=‘\n‘,file=sys.stdout)
    49. range(n)
    50. range(start,stop [,step])
    51. repr(obj)
    52. reversed(iterable)
    53. round(x [,ndigits])
    54. set([iterable])
    55. setattr(obj,name_str,value)
    56. sorted(iterable [,key] [,reverse])
    57. str(obj=‘‘)
    58. str(obj=b‘‘ [,encoding=‘utf-8‘])
    59. sum(iterable [,start])
    60. super(type)
    61. tuple([iterable])
    62. type(obj)
    63. zip(*iterables)
    64. C. Set Methods
    65. set_obj.add(obj)
    66. set_obj.clear()
    67. set_obj.copy()
    68. set_obj.difference(other_set)
    69. set_obj.difference_update(other_set)
    70. set_obj.discard(obj)
    71. set_obj.intersection(other_set)
    72. set_obj.intersection_update(other_set)
    73. set_obj.isdisjoint(other_set)
    74. set_obj.issubset(other_set)
    75. set_obj.issuperset(other_set)
    76. set_obj.pop()
    77. set_obj.remove(obj)
    78. set_obj.symmetric_difference(other_set)
    79. set_obj.symmetric_difference_update(other_set)
    80. set_obj.union(other_set)
    81. set_obj.union_update(other_set)
  28. D. Dictionary Methods
    1. dict_obj.clear()
    2. dict_obj.copy()
    3. dict_obj.get(key_obj, default_val = None)
    4. dict_obj.items()
    5. dict_obj.keys()
    6. dict_obj.pop(key [,default_value])
    7. dict_obj.popitem()
    8. dict_obj.setdefault(key,default_value=None)
    9. dict_obj.values()
    10. dict_obj.update(sequence)
  29. E. Statement Reference
    1. Variables and Assignments
    2. Spacing Issues in Python
    3. Alphabetical Statement Reference
  30. Index
  31. Code Snippets

Product information

  • Title: Supercharged Python: Take Your Code to the Next Level, First Edition
  • Author(s): John Bennett, Brian Overland
  • Release date: July 2019
  • Publisher(s): Addison-Wesley Professional
  • ISBN: 9780135160275