Book description
Want to learn the Python language without slogging your way through how-to manuals? With Head First Python, you’ll quickly grasp Python’s fundamentals, working with the built-in data structures and functions. Then you’ll move on to building your very own webapp, exploring database management, exception handling, and data wrangling. If you’re intrigued by what you can do with context managers, decorators, comprehensions, and generators, it’s all here. This second edition is a complete learning experience that will help you become a bonafide Python programmer in no time.
Why does this book look so different? Based on the latest research in cognitive science and learning theory, Head First Pythonuses a visually rich format to engage your mind, rather than a text-heavy approach that puts you to sleep. Why waste your time struggling with new concepts? This multi-sensory learning experience is designed for the way your brain really works.
Publisher resources
Table of contents
- Dedication
- Advance Praise for Head First Python, Second Edition
- Author of Head First Python, 2nd Edition
- How to use this Book: Intro
- O’Reilly Safari
-
1. The Basics: Getting Started Quickly
- Breaking with Tradition
- Jump Right In
- Understanding IDLE’s Windows
- What Happens Next...
- Press F5 to Run Your Code
- Code Runs Immediately
- Executing Code, One Statement at a Time
- Functions + Modules = The Standard Library
- Batteries Included
- Data Structures Come Built-in
- Invoking Methods Obtains Results
- Deciding When to Run Blocks of Code
- What Happened to My Curly Braces?
- What “else” Can You Have with “if”?
- Suites Can Contain Embedded Suites
- What We Already Know
- Extending Our Program to Do More
- What’s the Best Approach to Solving This Problem?
- Returning to the Python Shell
- Experimenting at the Shell
- Iterating Over a Sequence of Objects
- Iterating a Specific Number of Times
- Applying the Outcome of Task #1 to Our Code
- Indent Suites with Format...Indent Region
- Arranging to Pause Execution
- Importation Confusion
- Generating Random Integers with Python
- Asking the Interpreter for Help
- Reviewing Our Experiments
- Updating What We Already Know
- A Few Lines of Code Do a Lot
- Coding a Serious Business Application
- Python Code Is Easy to Read
- Is Indentation Driving You Crazy?
- Asking the Interpreter for Help on a Function
- Experimenting with Ranges
- Don’t Forget to Try the Beer Song Code
- Chapter 1’s Code
-
2. List Data: Working with Ordered Data
- Numbers, Strings...and Objects
- “Everything Is an Object”
- Meet the Four Built-in Data Structures
- Ordered Collections Are Mutable/Immutable
- An Unordered Data Structure: Dictionary
- A Data Structure That Avoids Duplicates: Set
- A List Is an Ordered Collection of Objects
- Creating Lists Literally
- Putting Lists to Work
- Use Your Editor When Working on More Than a Few Lines of Code
- “Growing” a List at Runtime
- Checking for Membership with “in”
- It’s Time to Update Our Code
- Removing Objects from a List
- Popping Objects Off a List
- Extending a List with Objects
- Inserting an Object into a List
- What About Using Square Brackets?
- What Happened to “plist”?
- Lists: What We Know
- What Looks Like a Copy, But Isn’t
- How to Copy a Data Structure
- Square Brackets Are Everywhere
- Lists Extend the Square Bracket Notation
- Lists Understand Start, Stop, and Step
- List Slices in Action
- Starting and Stopping with Lists
- Stepping with Lists
- Putting Slices to Work on Lists
- Putting Slices to Work on Lists, Continued
- Which Is Better? It Depends...
- Slicing a List Is Nondestructive
- Python’s “for” Loop Understands Lists
- Python’s “for” Loop Understands Slices
- Marvin’s Slices in Detail
- Lists: Updating What We Know
- What’s Wrong with Lists?
- When Not to Use Lists
- Chapter 2’s Code, 1 of 2
- Chapter 2’s Code, 2 of 2
-
3. Structured Data: Working with Structured Data
- A Dictionary Stores Key/Value Pairs
- Make Dictionaries Easy to Read
- How to Spot a Dictionary in Code
- Insertion Order Is NOT Maintained
- Value Lookup with Square Brackets
- Working with Dictionaries at Runtime
- Recap: Displaying Found Vowels (Lists)
- How Can a Dictionary Help Here?
- Selecting a Frequency Count Data Structure
- Updating a Frequency Counter
- Updating a Frequency Counter, v2.0
- Iterating Over a Dictionary
- Iterating Over Keys and Values
- Dictionaries: What We Already Know
- Iterating Over a Dictionary with “items”
- Just How Dynamic Are Dictionaries?
- Avoiding KeyErrors at Runtime
- Checking for Membership with “in”
- Ensuring Initialization Before Use
- Substituting “not in” for “in”
- Putting the “setdefault” Method to Work
- Aren’t Dictionaries (and Lists) Enough?
- Sets Don’t Allow Duplicates
- Creating Sets Efficiently
- Taking Advantage of Set Methods
- union Works by Combining Sets
- difference Tells You What’s Not Shared
- intersection Reports on Commonality
- Sets: What You Already Know
- Making the Case for Tuples
- Tuples Are Immutable
- Watch Out for Single-Object Tuples
- Combining the Built-in Data Structures
- Storing a Table of Data
- A Dictionary Containing a Dictionary
- A Dictionary of Dictionaries (a.k.a. a Table)
- Pretty-Printing Complex Data Structures
- Visualizing Complex Data Structures
- Accessing a Complex Data Structure’s Data
- Data Is As Complex As You Make It
- Chapter 3’s Code, 1 of 2
- Chapter 3’s Code, 2 of 2
-
4. Code Reuse: Functions and Modules
- Reusing Code with Functions
- Introducing Functions
- What About Type Information?
- Naming a Chunk of Code with “def”
- Invoking Your Function
- Use IDLE’s Editor to Make Changes
- What’s the Deal with All Those Strings?
- Follow Best Practice As Per the PEPs
- Functions Can Accept Arguments
- Functions Return a Result
- Returning One Value
- Returning More Than One Value
- Recalling the Built-in Data Structures
- Use Annotations to Improve Your Docs
- Why Use Function Annotations?
- Functions: What We Know Already
- Making a Generically Useful Function
- Creating Another Function, 1 of 3
- Creating Another Function, 2 of 3
- Creating Another Function, 3 of 3
- Specifying Default Values for Arguments
- Positional Versus Keyword Assignment
- Updating What We Know About Functions
- Functions Beget Modules
- How Are Modules Found?
- Running Python from the Command Line
- Not Found Modules Produce ImportErrors
- ImportErrors Occur No Matter the Platform
- Getting a Module into Site-packages
- Creating the Required Setup Files
- Creating the Distribution File
- Distribution Files on UNIX-like OSes
- Installing Packages with “pip”
- Modules: What We Know Already
- Demonstrating Call-by-Value Semantics
- Demonstrating Call-by-Reference Semantics
- Can I Test for PEP 8 Compliance?
- Getting Ready to Check PEP 8 Compliance
- Install the Testing Developer Tools
- How PEP 8–Compliant Is Our Code?
- Understanding the Failure Messages
- Confirming PEP 8 Compliance
- Chapter 4’s Code
-
5. Building a Webapp: Getting Real
- Python: What You Already Know
- Let’s Build Something
- What Do We Want Our Webapp to Do?
- What Happens on the Web Server?
- Let’s Install Flask
- How Does Flask Work?
- Running Your Flask Webapp for the First Time
- Here’s What Happened (Line by Line)
- Creating a Flask Webapp Object
- Decorating a Function with a URL
- Running Your Webapp’s Behavior(s)
- Exposing Functionalit y to the Web
- Recall What We’re Trying to Build
- Building the HTML Form
- Templates Relate to Web Pages
- Rendering Templates from Flask
- Displaying the Webapp’s HTML Form
- Preparing to Run the Template Code
- We’re Ready for a Test Run
- Understanding HTTP Status Codes
- Handling Posted Data
- Refining the Edit/Stop/Start/Test Cycle
- Accessing HTML Form Data with Flask
- Using Request Data in Your Webapp
- Producing the Results As HTML
- Calculating the Data We Need
- Adding a Finishing Touch
- Redirect to Avoid Unwanted Errors
- Functions Can Have Multiple URLs
- Updating What We Know
- Preparing Your Webapp for the Cloud
- Exploiting Dunder Name Dunder Main
- Chapter 5’s Code
-
6. Storing and Manipulating Data: Where to Put Your Data
- Doing Something with Your Webapp’s Data
- Python Supports Open, Process, Close
- Reading Data from an Existing File
- A Better Open, Process, Close: “with”
- A Quick Review
- View the Log Through Your Webapp
- Examine the Raw Data with View Source
- It’s Time to Escape (Your Data)
- Viewing the Entire Log in Your Webapp
- Learning More About the Request Object
- Logging Specific Web Request Attributes
- Log a Single Line of Delimited Data
- One Final Change to Our Logging Code
- From Raw Data to Readable Output
- Does This Remind You of Anything?
- Use a Dict of Dicts...or Something Else?
- What’s Joined Together Can Be Split Apart
- When Should the Conversion Occur?
- Processing Data: What We Already Know
- Generate Readable Output With HTML
- Embed Display Logic in Your Template
- Producing Readable Output with Jinja2
- The Current State of Our Webapp Code
- Asking Questions of Your Data
- Chapter 6’s Code
-
7. Using a Database: Putting Python’s DB-API to Use
- Database-Enabling Your Webapp
- Task 1: Install the MySQL Server
- Introducing Python’s DB-API
- Task 2: Install a MySQL Database Driver for Python
- Install MySQL-Connector/Python
- Task 3: Create Our Webapp’s Database and Tables
- Decide on a Structure for Your Log Data
- Confirm Your Table Is Ready for Data
- Task 4: Create Code to Work with Our Webapp’s Database and Tables
- Storing Data Is Only Half the Battle
- How Best to Reuse Your Database Code?
- Consider What You’re Trying to Reuse
- What About That Import?
- Consider What You’re Trying to Do
- You’ve Seen This Pattern Before
- The Bad News Isn’t Really All That Bad
- Chapter 7’s Code
-
8. A Little Bit of Class: Abstracting Behavior and State
- Hooking into the “with” Statement
- An Object-Oriented Primer
- Creating Objects from Classes
- Objects Share Behavior but Not State
- Doing More with CountFromBy
- It’s Worth Repeating Ourselves: Objects Share Behavior but Not State
- Invoking a Method: Understand the Details
- Method Invocation: What Actually Happens
- Adding a Method to a Class
- Are You Serious About “self”?
- The Importance of “self”
- Coping with Scoping
- Prefix Your Attribute Names with “self”
- Initialize (Attribute) Values Before Use
- Dunder “init” Initializes Attributes
- Initializing Attributes with Dunder “init”
- Understanding CountFromBy’s Representation
- Defining CountFromBy’s Representation
- Providing Sensible Defaults for CountFromBy
- Classes: What We Know
- Chapter 8’s Code
-
9. The Context Management Protocol: Hooking into Python’s with Statement
- What’s the Best Way to Share Our Webapp’s Database Code?
- Consider What You’re Trying to Do, Revisited
- Managing Context with Methods
- You’ve Already Seen a Context Manager in Action
- Create a New Context Manager Class
- Initialize the Class with the Database Config
- Perform Setup with Dunder “enter”
- Perform Teardown with Dunder “exit”
- Reconsidering Your Webapp Code, 1 of 2
- Reconsidering Your Webapp Code, 2 of 2
- Recalling the “log_request” Function
- Amending the “log_request” Function
- Recalling the “view_the_log” Function
- It’s Not Just the Code That Changes
- Amending the “view_the_log” Function
- All That Remains...
- Answering the Data Questions
- Which IP addresses are the requests coming from?
- Which browser is being used the most?
- Chapter 9’s Code, 1 of 2
- Chapter 9’s Code, 2 of 2
-
10. Function Decorators: Wrapping Functions
- Your Webapp Is Working Well, But...
- The Web Is Stateless
- Your Web Server (Not Your Computer) Runs Your Code
- It’s Time for a Bit of a Session
- Flask’s Session Technology Adds State
- Dictionary Lookup Retrieves State
- Managing Logins with Sessions
- Let’s Do Login
- Let’s Do Logout and Status Checking
- Why Not Check for False?
- Can We Now Restrict Access to URLs?
- Copy-and-Paste Is Rarely a Good Idea
- Creating a Function Helps, But...
- You’ve Been Using Decorators All Along
- Pass a Function to a Function
- Invoking a Passed Function
- Functions Can Be Nested Inside Functions
- Return a Function from a Function
- Accepting a List of Arguments
- Processing a List of Arguments
- Accepting a Dictionary of Arguments
- Processing a Dictionary of Arguments
- Accepting Any Number and Type of Function Arguments
- A Recipe for Creating a Function Decorator
- Recap: We Need to Restrict Access to Certain URLs
- Creating a Function Decorator
- The Final Step: Handling Arguments
- Your Decorator in All Its Glory
- Putting Your Decorator to Work
- The Beauty of Decorators
- Creating More Decorators
- Back to Restricting Access to /viewlog
- What’s Next?
- Chapter 10’s Code, 1 of 2
- Chapter 10’s Code, 2 of 2
-
11. Exception Handling: What to Do When Things Go Wrong
- Databases Aren’t Always Available
- Web Attacks Are a Real Pain
- Input-Output Is (Sometimes) Slow
- Your Function Calls Can Fail
- Considering the Identified Problems
- Always Try to Execute Error-Prone Code
- Catching an Error Is Not Enough
- try Once, but except Many Times
- A Lot of Things Can Go Wrong
- Haven’t We Just Lost Something?
- Learning About Exceptions from “sys”
- The Catch-All Exception Handler, Revisited
- Getting Back to Our Webapp Code
- Silently Handling Exceptions
- Handling Other Database Errors
- Does “More Errors” Mean “More excepts”?
- Avoid Tightly Coupled Code
- The DBcm Module, Revisited
- Creating Custom Exceptions
- The empty class isn’t quite empty...
- What Else Can Go Wrong with “DBcm”?
- Creating More Custom Exceptions
- Are Your Database Credentials Correct?
- Handling SQLError Is Different
- Be Careful with Code Positioning
- Raising an SQLError
- A Quick Recap: Adding Robustness
- How to Deal with Wait? It Depends...
- Chapter 11’s Code, 1 of 3
- Chapter 11’s Code, 2 of 3
- Chapter 11’s Code, 3 of 3
-
12. 11¾ A Little Bit of Threading: Dealing with Waiting
- Waiting: What to Do?
- How Are You Querying Your Database?
- Database INSERTs and SELECTs Are Different
- Doing More Than One Thing at Once
- Don’t Get Bummed Out: Use Threads
- First Things First: Don’t Panic
- Don’t Get Bummed Out: Flask Can Help
- Is Your Webapp Robust Now?
- Chapter 11¾’s Code, 1 of 2
- Chapter 11¾’s Code, 2 of 2
-
13. Advanced Iteration: Looping Like Crazy
- Bahamas Buzzers Have Places to Go
- Reading CSV Data As Lists
- Reading CSV Data As Dictionaries
- Let’s Back Up a Little Bit
- Stripping, Then Splitting, Your Raw Data
- Be Careful When Chaining Method Calls
- Transforming Data into the Format You Need
- Transforming into a Dictionary Of Lists
- Let’s Do the Basic Conversions
- Did You Spot the Pattern in Your Code?
- Spotting the Pattern with Lists
- Converting Patterns into Comprehensions
- Take a Closer Look at the Comprehension
- What’s the Big Deal?
- Specifying a Dictionary Comprehension
- Extend Comprehensions with Filters
- Recall What You Set Out to Do
- Deal with Complexity the Python Way
- Extract a Single Destination’s Flight Times
- Extract Flight Times for All Destinations
- That Feeling You Get...
- The Set Comprehension in Action
- How to Spot a Comprehension
- What About “Tuple Comprehensions”?
- Parentheses Around Code == Generator
- Using a Listcomp to Process URLs
- Using a Generator to Process URLs
- Using a Generator: What Just Happened?
- Define What Your Function Needs to Do
- Yield to the Power of Generator Functions
- Tracing Your Generator Function, 1 of 2
- Tracing Your Generator Function, 2 of 2
- Concluding Remarks
- One Final Question
- Chapter 12’s Code
- It’s Time to Go…
- A. Installation: Installing Python
- B. Pythonanywhere: Deploying Your Webapp
-
C. Top Ten Things we Didn’t Cover: There’s Always More to Learn
- 1. What About Python 2?
- 2. Virtual Programming Environments
- 3. More on Object Orientation
- 4. Formats for Strings and the Like
- 5. Getting Things Sorted
- 6. More from the Standard Library
- 7. Running Your Code Concurrently
- 8. GUIs w ith Tkinter (and Fun w ith Turtles)
- 9. It’s Not Over ’Til It’s Tested
- 10. Debug, Debug, Debug
- D. Top Ten Projects not Covered: Even More Tools, Libraries, and Modules
- E. Getting Involved: The Python Community
- Index
- About the Author
- Copyright
Product information
- Title: Head First Python, 2nd Edition
- Author(s):
- Release date: November 2016
- Publisher(s): O'Reilly Media, Inc.
- ISBN: 9781491919538
You might also like
book
Head First Python, 3rd Edition
What will you learn from this book? Want to learn the Python language without slogging your …
book
Fluent Python, 2nd Edition
Don't waste time bending Python to fit patterns you've learned in other languages. Python's simplicity lets …
book
Python Crash Course, 3rd Edition
Python Crash Course is the world's best-selling guide to the Python guide programming language, with over …
book
Introducing Python, 2nd Edition
Easy to understand and fun to read, this updated edition of Introducing Python is ideal for …