Log In
Or create an account ->
Imperial Library
Home
About
News
Upload
Forum
Help
Login/SignUp
Index
Head First Python
Dedication
Praise for the first edition
Praise for other Head First books
Author Of Head First Python, 2nd Edition
How to use this Book: Intro
Who Is This Book For?
Who should probably back away from this book?
We Know What You’re Thinking
We know what your brain is thinking
Metacognition: Thinking About Thinking
Here’s What WE Did:
Here’s what YOU can do to bend your brain into submission
Read Me, 1 of 2
Read Me, 2 of 2
The Technical Review Team
Acknowledgments And Thanks
Safari® Books Online
1. The Basics: Getting Started Quickly
Breaking with Tradition
Starting with a meatier example
Jump Right In
Python’s IDLE is all you need to get going
Understanding IDLE’s Windows
What Happens Next...
Press F5 to Run Your Code
Code Runs Immediately
Executing Code, One Statement at a Time
Let’s be the Python interpreter
Functions + Modules = The Standard Library
Batteries Included
Data Structures Come Built-in
Python variables are dynamically assigned
Invoking Methods Obtains Results
Invoking built-in module functionality
Deciding When to Run Blocks of Code
What Happened to My Curly Braces?
A colon introduces an indented suite of code
What “else” Can You Have with “if”?
Suites Can Contain Embedded Suites
What We Already Know
Extending Our Program to Do More
What We Need to do:
What’s the Best Approach to Solving This Problem?
Both approaches work with Python
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
Dealing with all that beer...
Python Code Is Easy to Read
Is Indentation Driving You Crazy?
Getting back to the beer song code
Asking the Interpreter for Help on a Function
Starting, stopping, and stepping
Experimenting with Ranges
Don’t Forget to Try the Beer Song Code
Wrapping up what you already know
With all the beer gone, what’s next?
Chapter 1’s Programs
2. List Data: Working With Ordered Data
Numbers, Strings... and Objects
Numbers
Strings
Objects
“Everything is an Object”
But... what Does all this Actually Mean?
Meet the Four Built-in Data Structures
Ordered Collections are Mutable/Immutable
An Unordered Data Structure: Dictionary
A Data Structure Which Avoids Duplicates: Set
The 80/20 Data Structure Rule-of-Thumb
A List is an Ordered Collection of Objects
How to Spot a List in Code
Creating Lists Literally
Putting Lists to Work
Working with Lists
Is One Object Inside Another? Check with “in”
Use Your Editor When Working on More Than a Few Lines of Code
Don’t Forget: Press F5 to Run Your Program
“Growing” A List At Run-Time
Checking For Membership with “in”
Is the Object “in” or “not 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”?
What Happened to “plist”, Continued?
Lists: What We Know
What Looks Like A Copy, Isn’t
How To Copy A Data Structure
Square Brackets Are Everywhere
Lists: Updating What We Already Know
Lists Extend The Square Bracket Notation
Lists Understand Start, Stop, And Step
You can put start, stop, and step inside square brackets
List Slices In Action
Starting, And Stopping With Lists
Stepping With Lists
Slices are everywhere
Putting Slices To Work On Lists
Converting “Don’t panic!” to “on tap”
Putting Slices To Work On Lists, Continued
Which is better? It depends...
Slicing A List Is Non-destructive
So... which is better?
Python’s “for” Loop Understands Lists
Understanding marvin.py’s code
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 Programs
Chapter 2’s Programs, Continued
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
What happened to the insertion order?
Insertion Order is NOT Maintained
Dictionaries understand square brackets
Value Lookup With Square Brackets
Dictionary lookup is fast!
Working With Dictionaries At Run-Time
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
Specifying the ordering of a dictionary on output
Iterating Over A Dictionary With “items”
Just How Dynamic Are Dictionaries?
Dictionary keys must be initialized
Avoiding KeyErrors At Run-Time
Checking For Membership With “in”
Ensuring Initialization Before Use
Substituting “not in” For “in”
Putting The “setdefault” Method To Work
Dictionaries: updating what we already know
Aren’t Dictionaries (And Lists) Enough?
Sets Don’t Allow Duplicates
Spotting sets in your code
Creating Sets Efficiently
Creating sets from sequences
Taking Advantage Of Set Methods
Union Works By Combining Sets
What happened to the loop code?
Difference Tells You What’s Not Shared
Intersection Reports On Commonality
Sets: What You Already Know
Making The Case For Tuples
How to spot a tuple in code
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 Programs (1 of 2)
Chapter 3’s Programs (2 of 2)
4. Code Reuse: Functions & Modules
Reusing Code With Functions
Introducing Functions
What About Type Information?
Naming A Chunk Of Code With “def”
Invoking Your Function
Edit your function in an editor, not at the prompt
Use IDLE’s Editor To Make Changes
What’s The Deal With All Those Strings?
Understanding the string quote characters
Follow Best Practice As Per The PEPs
Functions Can Accept Arguments
Functions Return A Result
Returning One Value
Returning More Than One Value
What’s the deal with “set()”?
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 vs. Keyword Assignment
Updating What We Know About Functions
Functions Beget Modules
Creating modules couldn’t be easier, however...
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
Using “setuptools” to install into site-packages
Creating The Required Setup Files
Creating The Distribution File
Creating a distribution file on Windows
Distribution Files On UNIX-like OSes
Installing Packages With “pip”
Step 3 on Windows
Step 3 on UNIX-like OSes
Modules: What We Know Already
Giving your code away (a.k.a. sharing)
Demonstrating Call-By-Value Semantics
Demonstrating Call-By-Reference Semantics
Can I Test For PEP 8 Compliance?
Getting Ready To Check PEP 8 Compliance
Recalling our code
Installing pytest and the pep8 plug-in
Install The Testing Developer Tools
How PEP 8 Compliant Is Our Code?
Understanding The Failure Messages
Confirming PEP 8 Compliance
Conformance to PEP 8 is a good thing
Chapter 4’s Programs
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?
What do we need to get going?
Let’s Install Flask
Install Flask from the command-line with pip
How Does Flask Work?
Check that Flask is installed and working
Run Flask from your OS command-line
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 Functionality To The Web
Recall What We’re Trying To Build
Here’s the plan
Building The HTML Form
But... what if you’re new to all this HTML stuff?
Create the HTML, then send it to the browser
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
Automatic Reloads
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
Is that all there is to this chapter?
Preparing Your Webapp For The Cloud
Exploiting Dunder Name Dunder Main
Deploying to PythonAnywhere (well... almost)
Chapter 5’s Programs
6. Storing & 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”
The “with” statement manages context
Invoking the logging function
A Quick Review
Take your webapp for a spin...
Data is logged (behind the scenes)
View The Log Through Your Webapp
Where to start when things go wrong with your output
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
What’s all this, then?
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?
Take a closer look at the logged data
What’s Joined Together Can Be Split Apart
Getting to a list of lists from a list of strings
When Should The Conversion Occur?
Processing Data: What We Already Know
Take a closer look at the output
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 & 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
This new function is a big change
How Best To Reuse Your Database Code?
Consider What You’re Trying To Reuse
What About That Import?
Be careful when positioning your import statements
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
A class bundles behavior and state
Classes have methods and attributes
Creating Objects From Classes
Objects Share Behavior But Not State
Defining what we want CountFromBy to do
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”
Initialise (Attribute) Values Before Use
Dunder Init Initializes Attributes
Initializing Attributes With Dunder Init
Pass any amount of argument data to dunder “init”
What have we learned from this Test Drive?
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
How best to create a context manager?
Managing Context With Methods
Dunder “enter” performs set-up
Dunder “exit” does tear-down
(As you know) dunder “init” initializes
You’ve Already Seen A Context Manager In Action
What’s required from you
Create A New Context Manager Class
Initialise The Class With The Database Config
Your context manager begins to take shape
Perform Set-up With Dunder Enter
Don’t forget to prefix all attributes with “self”
Perform Tear-down With Dunder Exit
Your context manager is ready for testing
There’s not much code here, is there?
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
Here’s the SQL query you’ll need
It’s nearly time for one last Test Drive
All That Remains...
Answering The Data Questions
How many requests have been responded to?
What’s the most common list of letters?
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...
Only Authenticated Users gain Access
The Web is Stateless
HTTP is to blame...
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
Time for a Test Drive?
Managing Logins with Sessions
Let’s do Login
Amend the Webapp’s code to Handle Logins
Let’s do Logout & Status Checking
Amend the webapp’s code once more
Why not Check for False?
Can we now Restrict Access to URLs?
Copy-and-Paste is Rarely a good Idea
Put Shared Code into its Own Function
Creating a function helps, but...
You’ve been Using Decorators all Along
Pass a Function to a Function
Functions can take a Function as an Argument
Invoking a Passed Function
Functions can be Nested inside Functions
When would you ever use this?
Return a Function from a Function
Accepting a list of Arguments
Use * to accept an arbitrary list of arguments
Processing a list of Arguments
* Works on the way in, Too
Accepting a dictionary of Arguments
Use ** to accept arbitrary keyword arguments
Processing a dictionary of Arguments
** Works on the way in, too
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
That’s almost too easy, isn’t it?
Can you see why the nested function is called “wrapper”?
The Final Step: Handling Arguments
We’re done... or are we?
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
1. Your database connection fails
2. Your application is subjected to an attack
3. Your code takes a long time to execute
4. Your function call fails
Always Try To Execute Error-prone Code
Catching An Error Is Not Enough
There can be more than one exception raised...
Try Once, But Except Many Times
A Lot Of Things Can Go Wrong
The Catch-All Exception-Handler
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 SQLError
A Quick Recap: Adding Robustness
What happens if something takes a long time?
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
Concurrent code: you have options
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
Think about the data wrangling that’s needed here...
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?
Comprehensions aren’t just for lists
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
Generators produce data items one-at-a-time...
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...
You’re on your way!
A. Installation: Installing Python
Install Python 3 on Windows
Download, then install
Check Python 3 on Windows
It’s Python 3 on Windows, sort of...
Add to Python 3 on Windows
Install Python 3 on Mac OS X (macOS)
Using a package manager
Check & Configure Python 3 on Mac OS X
The Python 3 folder on Mac OS X
You’re ready to run on Mac OS X
Install Python 3 on Linux
B. Pythonanywhere: Deploying Your Webapp
Step 0: A Little Prep
Step 1: Sign-up For PythonAnywhere
Step 2: Upload Your Files To The Cloud
Step 3: Extract And Install Your Code
Step 4: Create A Starter Webapp, 1 of 2
Step 4: Create A Starter Webapp, 2 of 2
Step 5: Configure Your Webapp
Step 5: Take Your Cloud-based Webapp For A Spin!
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
Collections
Itertools
Functools
7. Running Your Code Concurrently
New keywords: async and await
8. GUIs With Tkinter (And Fun With 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
1. Alternatives To >>>
2. Alternatives To IDLE
What does Paul use?
3. Jupyter Notebook: The Web-Based IDE
4. Doing Data Science
5. Web Development Technologies
But, wait, there’s more
6. Working With Web Data
Scrape that web data!
7. More Data Sources
There’s more to querying data than SQL
8. Programming Tools
More help with testing, too
9. Kivy: Our Pick For “Coolest Project Ever”
10. Alternative Implementations
E. Getting Involved: The Python Community
BDFL: Benevolent Dictator For Life
PSF: The Python Software Foundation
PyCon: The Python Conference
A Tolerant Community: Respect For Diversity
Come for the language, stay for the community
The Python Podcasts
Python Newsletters
The Zen Of Python
Which Book Should I Read Next?
Our Favorite Python Books
F. Back Cover Content: TOC images
What will you learn from this book?
Why does this book look so different?
Chapter 1 TOC Image
Chapter 2 TOC Image
Chapter 3 TOC Image
Chapter 4 TOC Image
Chapter 5 TOC Image
Chapter 6 TOC Image
Chapter 7 TOC Image
Chapter 8 TOC Image
Chapter 9 TOC Image
Chapter 10 TOC Image
Chapter 11 TOC Image
Chapter 11¾ TOC Image
Chapter 12 TOC Image
About the Author
Copyright
← Prev
Back
Next →
← Prev
Back
Next →