Python Crash Course A Hands On Project Based Introduction to Programming 2nd Edition Eric Matthes instant download
Python Crash Course A Hands On Project Based Introduction to Programming 2nd Edition Eric Matthes instant download
https://ebookmeta.com/product/python-crash-course-a-hands-on-
project-based-introduction-to-programming-2nd-edition-eric-
matthes-2/
https://ebookmeta.com/product/python-crash-course-a-hands-on-
project-based-introduction-to-programming-2nd-edition-eric-
matthes/
https://ebookmeta.com/product/python-crash-course-a-hands-on-
project-based-introduction-to-programming-2nd-edition-eric-
matthes-3/
https://ebookmeta.com/product/python-crash-course-3rd-edition-
eric-matthes-6/
https://ebookmeta.com/product/everyday-mathematics-made-easy-a-
quick-review-of-what-you-forgot-you-knew-tom-begnal/
Bred by the Billionaire Breeding Season 1 1st Edition
Sam Crescent Stacey Espino
https://ebookmeta.com/product/bred-by-the-billionaire-breeding-
season-1-1st-edition-sam-crescent-stacey-espino/
https://ebookmeta.com/product/uncanny-magazine-issue-49-lynne-m-
thomas-et-el/
https://ebookmeta.com/product/critical-thinking-mit-press-
essential-knowledge-series-jonathan-haber/
https://ebookmeta.com/product/towers-of-acalia-the-reincarnated-
core-volume-v-1st-edition-atlas-kane-2/
https://ebookmeta.com/product/the-idea-of-suicide-contagion-
imitation-and-cultural-diffusion-researching-social-
psychology-1st-edition-michael-j-kral/
Shakespearean Star Laurence Olivier and National Cinema
Jennifer Barnes
https://ebookmeta.com/product/shakespearean-star-laurence-
olivier-and-national-cinema-jennifer-barnes/
PRAISE FOR PYTHON CRASH COURSE
“It has been interesting to see No Starch Press producing future
classics that should be alongside the more traditional programming
books. Python Crash Course is one of those books.”
—GREG LADEN, SCIENCEBLOGS
“Deals with some rather complex projects and lays them out in a
consistent, logical, and pleasant manner that draws the reader into
the subject.”
—FULL CIRCLE MAGAZINE
“Does what it says on the tin, and does it really well. . . . Presents a
large number of useful exercises as well as three challenging and
entertaining projects.”
—REALPYTHON.COM
by Eric Matthes
San Francisco
PYTHON CRASH COURSE, 2ND EDITION. Copyright © 2019 by Eric
Matthes.
All rights reserved. No part of this work may be reproduced or transmitted in any
form or by any means, electronic or mechanical, including photocopying, recording, or
by any information storage or retrieval system, without the prior written permission of
the copyright owner and the publisher.
ISBN-10: 1-59327-928-0
ISBN-13: 978-1-59327-928-8
No Starch Press and the No Starch Press logo are registered trademarks of No Starch
Press, Inc. Other product and company names mentioned herein may be the
trademarks of their respective owners. Rather than use a trademark symbol with every
occurrence of a trademarked name, we are using the names only in an editorial fashion
and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The information in this book is distributed on an “As Is” basis, without warranty.
While every precaution has been taken in the preparation of this work, neither the
author nor No Starch Press, Inc. shall have any liability to any person or entity with
respect to any loss or damage caused or alleged to be caused directly or indirectly by
the information contained in it.
About the Author
Eric Matthes is a high school science and math teacher living in Alaska,
where he teaches an introductory Python course. He has been writing
programs since he was five years old. Eric currently focuses on writing
software that addresses inefficiencies in education and brings the
benefits of open source software to the field of education. In his spare
time he enjoys climbing mountains and spending time with his family.
About the Technical Reviewer
Kenneth Love has been a Python programmer, teacher, and conference
organizer for many years. He has spoken and taught at many
conferences, been a Python and Django freelancer, and is currently a
software engineer for O’Reilly Media. Kenneth is co-creator of the
django-braces package, which provides several handy mixins for
Django’s class-based views. You can keep up with him on Twitter at
@kennethlove.
For my father, who always made time to answer my
questions about programming, and for Ever, who is just
beginning to ask me his questions
BRIEF CONTENTS
Preface to the Second Edition
Acknowledgments
Introduction
PART I: BASICS
Chapter 1: Getting Started
Chapter 2: Variables and Simple Data Types
Chapter 3: Introducing Lists
Chapter 4: Working with Lists
Chapter 5: if Statements
Chapter 6: Dictionaries
Chapter 7: User Input and while Loops
Chapter 8: Functions
Chapter 9: Classes
Chapter 10: Files and Exceptions
Chapter 11: Testing Your Code
Afterword
Index
CONTENTS IN DETAIL
PREFACE TO THE SECOND EDITION
ACKNOWLEDGMENTS
INTRODUCTION
Who Is This Book For?
What Can You Expect to Learn?
Online Resources
Why Python?
PART I: BASICS
1
GETTING STARTED
Setting Up Your Programming Environment
Python Versions
Running Snippets of Python Code
About the Sublime Text Editor
Python on Different Operating Systems
Python on Windows
Python on macOS
Python on Linux
Running a Hello World Program
Configuring Sublime Text to Use the Correct Python Version
Running hello_world.py
Troubleshooting
Running Python Programs from a Terminal
On Windows
On macOS and Linux
Exercise 1-1: python.org
Exercise 1-2: Hello World Typos
Exercise 1-3: Infinite Skills
Summary
2
VARIABLES AND SIMPLE DATA TYPES
What Really Happens When You Run hello_world.py
Variables
Naming and Using Variables
Avoiding Name Errors When Using Variables
Variables Are Labels
Exercise 2-1: Simple Message
Exercise 2-2: Simple Messages
Strings
Changing Case in a String with Methods
Using Variables in Strings
Adding Whitespace to Strings with Tabs or Newlines
Stripping Whitespace
Avoiding Syntax Errors with Strings
Exercise 2-3: Personal Message
Exercise 2-4: Name Cases
Exercise 2-5: Famous Quote
Exercise 2-6: Famous Quote 2
Exercise 2-7: Stripping Names
Numbers
Integers
Floats
Integers and Floats
Underscores in Numbers
Multiple Assignment
Constants
Exercise 2-8: Number Eight
Exercise 2-9: Favorite Number
Comments
How Do You Write Comments?
What Kind of Comments Should You Write?
Exercise 2-10: Adding Comments
The Zen of Python
Exercise 2-11: Zen of Python
Summary
3
INTRODUCING LISTS
What Is a List?
Accessing Elements in a List
Index Positions Start at 0, Not 1
Using Individual Values from a List
Exercise 3-1: Names
Exercise 3-2: Greetings
Exercise 3-3: Your Own List
Changing, Adding, and Removing Elements
Modifying Elements in a List
Adding Elements to a List
Removing Elements from a List
Exercise 3-4: Guest List
Exercise 3-5: Changing Guest List
Exercise 3-6: More Guests
Exercise 3-7: Shrinking Guest List
Organizing a List
Sorting a List Permanently with the sort() Method
Sorting a List Temporarily with the sorted() Function
Printing a List in Reverse Order
Finding the Length of a List
Exercise 3-8: Seeing the World
Exercise 3-9: Dinner Guests
Exercise 3-10: Every Function
Avoiding Index Errors When Working with Lists
Exercise 3-11: Intentional Error
Summary
4
WORKING WITH LISTS
Looping Through an Entire List
A Closer Look at Looping
Doing More Work Within a for Loop
Doing Something After a for Loop
Avoiding Indentation Errors
Forgetting to Indent
Forgetting to Indent Additional Lines
Indenting Unnecessarily
Indenting Unnecessarily After the Loop
Forgetting the Colon
Exercise 4-1: Pizzas
Exercise 4-2: Animals
Making Numerical Lists
Using the range() Function
Using range() to Make a List of Numbers
Simple Statistics with a List of Numbers
List Comprehensions
Exercise 4-3: Counting to Twenty
Exercise 4-4: One Million
Exercise 4-5: Summing a Million
Exercise 4-6: Odd Numbers
Exercise 4-7: Threes
Exercise 4-8: Cubes
Exercise 4-9: Cube Comprehension
Working with Part of a List
Slicing a List
Looping Through a Slice
Copying a List
Exercise 4-10: Slices
Exercise 4-11: My Pizzas, Your Pizzas
Exercise 4-12: More Loops
Tuples
Defining a Tuple
Looping Through All Values in a Tuple
Writing over a Tuple
Exercise 4-13: Buffet
Styling Your Code
The Style Guide
Indentation
Line Length
Blank Lines
Other Style Guidelines
Exercise 4-14: PEP 8
Exercise 4-15: Code Review
Summary
5
IF STATEMENTS
A Simple Example
Conditional Tests
Checking for Equality
Ignoring Case When Checking for Equality
Checking for Inequality
Numerical Comparisons
Checking Multiple Conditions
Checking Whether a Value Is in a List
Checking Whether a Value Is Not in a List
Boolean Expressions
Exercise 5-1: Conditional Tests
Exercise 5-2: More Conditional Tests
if Statements
Simple if Statements
if-else Statements
The if-elif-else Chain
Using Multiple elif Blocks
Omitting the else Block
Testing Multiple Conditions
Exercise 5-3: Alien Colors #1
Exercise 5-4: Alien Colors #2
Exercise 5-5: Alien Colors #3
Exercise 5-6: Stages of Life
Exercise 5-7: Favorite Fruit
Using if Statements with Lists
Checking for Special Items
Checking That a List Is Not Empty
Using Multiple Lists
Exercise 5-8: Hello Admin
Exercise 5-9: No Users
Exercise 5-10: Checking Usernames
Exercise 5-11: Ordinal Numbers
Styling Your if Statements
Exercise 5-12: Styling if statements
Exercise 5-13: Your Ideas
Summary
6
DICTIONARIES
A Simple Dictionary
Working with Dictionaries
Accessing Values in a Dictionary
Adding New Key-Value Pairs
Starting with an Empty Dictionary
Modifying Values in a Dictionary
Removing Key-Value Pairs
A Dictionary of Similar Objects
Using get() to Access Values
Exercise 6-1: Person
Exercise 6-2: Favorite Numbers
Exercise 6-3: Glossary
Looping Through a Dictionary
Looping Through All Key-Value Pairs
Looping Through All the Keys in a Dictionary
Looping Through a Dictionary’s Keys in a Particular Order
Looping Through All Values in a Dictionary
Exercise 6-4: Glossary 2
Exercise 6-5: Rivers
Exercise 6-6: Polling
Nesting
A List of Dictionaries
A List in a Dictionary
A Dictionary in a Dictionary
Exercise 6-7: People
Exercise 6-8: Pets
Exercise 6-9: Favorite Places
Exercise 6-10: Favorite Numbers
Exercise 6-11: Cities
Exercise 6-12: Extensions
Summary
7
USER INPUT AND WHILE LOOPS
How the input() Function Works
Writing Clear Prompts
Using int() to Accept Numerical Input
The Modulo Operator
Exercise 7-1: Rental Car
Exercise 7-2: Restaurant Seating
Exercise 7-3: Multiples of Ten
Introducing while Loops
The while Loop in Action
Letting the User Choose When to Quit
Using a Flag
Using break to Exit a Loop
Using continue in a Loop
Avoiding Infinite Loops
Exercise 7-4: Pizza Toppings
Exercise 7-5: Movie Tickets
Exercise 7-6: Three Exits
Exercise 7-7: Infinity
Using a while Loop with Lists and Dictionaries
Moving Items from One List to Another
Removing All Instances of Specific Values from a List
Filling a Dictionary with User Input
Exercise 7-8: Deli
Exercise 7-9: No Pastrami
Exercise 7-10: Dream Vacation
Summary
8
FUNCTIONS
Defining a Function
Passing Information to a Function
Arguments and Parameters
Exercise 8-1: Message
Exercise 8-2: Favorite Book
Passing Arguments
Positional Arguments
Keyword Arguments
Default Values
Equivalent Function Calls
Avoiding Argument Errors
Exercise 8-3: T-Shirt
Exercise 8-4: Large Shirts
Exercise 8-5: Cities
Return Values
Returning a Simple Value
Making an Argument Optional
Returning a Dictionary
Using a Function with a while Loop
Exercise 8-6: City Names
Exercise 8-7: Album
Exercise 8-8: User Albums
Passing a List
Modifying a List in a Function
Preventing a Function from Modifying a List
Exercise 8-9: Messages
Exercise 8-10: Sending Messages
Exercise 8-11: Archived Messages
Passing an Arbitrary Number of Arguments
Mixing Positional and Arbitrary Arguments
Using Arbitrary Keyword Arguments
Exercise 8-12: Sandwiches
Exercise 8-13: User Profile
Exercise 8-14: Cars
Storing Your Functions in Modules
Importing an Entire Module
Importing Specific Functions
Using as to Give a Function an Alias
Using as to Give a Module an Alias
Importing All Functions in a Module
Styling Functions
Exercise 8-15: Printing Models
Exercise 8-16: Imports
Exercise 8-17: Styling Functions
Summary
9
CLASSES
Creating and Using a Class
Creating the Dog Class
Making an Instance from a Class
Exercise 9-1: Restaurant
Exercise 9-2: Three Restaurants
Exercise 9-3: Users
Working with Classes and Instances
The Car Class
Setting a Default Value for an Attribute
Modifying Attribute Values
Exercise 9-4: Number Served
Exercise 9-5: Login Attempts
Inheritance
The __init__() Method for a Child Class
Defining Attributes and Methods for the Child Class
Overriding Methods from the Parent Class
Instances as Attributes
Modeling Real-World Objects
Exercise 9-6: Ice Cream Stand
Exercise 9-7: Admin
Exercise 9-8: Privileges
Exercise 9-9: Battery Upgrade
Importing Classes
Importing a Single Class
Storing Multiple Classes in a Module
Importing Multiple Classes from a Module
Importing an Entire Module
Importing All Classes from a Module
Importing a Module into a Module
Using Aliases
Finding Your Own Workflow
Exercise 9-10: Imported Restaurant
Exercise 9-11: Imported Admin
Exercise 9-12: Multiple Modules
The Python Standard Library
Exercise 9-13: Dice
Exercise 9-14: Lottery
Exercise 9-15: Lottery Analysis
Exercise 9-16: Python Module of the Week
Styling Classes
Summary
10
FILES AND EXCEPTIONS
Reading from a File
Reading an Entire File
File Paths
Reading Line by Line
Making a List of Lines from a File
Working with a File’s Contents
Large Files: One Million Digits
Is Your Birthday Contained in Pi?
Exercise 10-1: Learning Python
Exercise 10-2: Learning C
Writing to a File
Writing to an Empty File
Writing Multiple Lines
Appending to a File
Exercise 10-3: Guest
Exercise 10-4: Guest Book
Exercise 10-5: Programming Poll
Exceptions
Handling the ZeroDivisionError Exception
Using try-except Blocks
Using Exceptions to Prevent Crashes
The else Block
Handling the FileNotFoundError Exception
Analyzing Text
Working with Multiple Files
Failing Silently
Deciding Which Errors to Report
Exercise 10-6: Addition
Exercise 10-7: Addition Calculator
Exercise 10-8: Cats and Dogs
Exercise 10-9: Silent Cats and Dogs
Exercise 10-10: Common Words
Storing Data
Using json.dump() and json.load()
Saving and Reading User-Generated Data
Refactoring
Exercise 10-11: Favorite Number
Exercise 10-12: Favorite Number Remembered
Exercise 10-13: Verify User
Summary
11
TESTING YOUR CODE
Testing a Function
Unit Tests and Test Cases
A Passing Test
A Failing Test
Responding to a Failed Test
Adding New Tests
Exercise 11-1: City, Country
Exercise 11-2: Population
Testing a Class
A Variety of Assert Methods
A Class to Test
Testing the AnonymousSurvey Class
The setUp() Method
Exercise 11-3: Employee
Summary
PART II: PROJECTS
12
A SHIP THAT FIRES BULLETS
Planning Your Project
Installing Pygame
Starting the Game Project
Creating a Pygame Window and Responding to User Input
Setting the Background Color
Creating a Settings Class
Adding the Ship Image
Creating the Ship Class
Drawing the Ship to the Screen
Refactoring: The _check_events() and _update_screen() Methods
The _check_events() Method
The _update_screen() Method
Exercise 12-1: Blue Sky
Exercise 12-2: Game Character
Piloting the Ship
Responding to a Keypress
Allowing Continuous Movement
Moving Both Left and Right
Adjusting the Ship’s Speed
Limiting the Ship’s Range
Refactoring _check_events()
Pressing Q to Quit
Running the Game in Fullscreen Mode
A Quick Recap
alien_invasion.py
settings.py
ship.py
Exercise 12-3: Pygame Documentation
Exercise 12-4: Rocket
Exercise 12-5: Keys
Shooting Bullets
Adding the Bullet Settings
Creating the Bullet Class
Storing Bullets in a Group
Firing Bullets
Deleting Old Bullets
Limiting the Number of Bullets
Creating the _update_bullets() Method
Exercise 12-6: Sideways Shooter
Summary
13
ALIENS!
Reviewing the Project
Creating the First Alien
Creating the Alien Class
Creating an Instance of the Alien
Building the Alien Fleet
Determining How Many Aliens Fit in a Row
Creating a Row of Aliens
Refactoring _create_fleet()
Adding Rows
Exercise 13-1: Stars
Exercise 13-2: Better Stars
Making the Fleet Move
Moving the Aliens Right
Creating Settings for Fleet Direction
Checking Whether an Alien Has Hit the Edge
Dropping the Fleet and Changing Direction
Exercise 13-3: Raindrops
Exercise 13-4: Steady Rain
Shooting Aliens
Detecting Bullet Collisions
Making Larger Bullets for Testing
Repopulating the Fleet
Speeding Up the Bullets
Refactoring _update_bullets()
Exercise 13-5: Sideways Shooter Part 2
Ending the Game
Detecting Alien and Ship Collisions
Responding to Alien and Ship Collisions
Aliens that Reach the Bottom of the Screen
Game Over!
Identifying When Parts of the Game Should Run
Exercise 13-6: Game Over
Summary
14
SCORING
Adding the Play Button
Creating a Button Class
Drawing the Button to the Screen
Starting the Game
Resetting the Game
Deactivating the Play Button
Hiding the Mouse Cursor
Exercise 14-1: Press P to Play
Exercise 14-2: Target Practice
Leveling Up
Modifying the Speed Settings
Resetting the Speed
Exercise 14-3: Challenging Target Practice
Exercise 14-4: Difficulty Levels
Scoring
Displaying the Score
Making a Scoreboard
Updating the Score as Aliens Are Shot Down
Resetting the Score
Making Sure to Score All Hits
Increasing Point Values
Rounding the Score
High Scores
Displaying the Level
Displaying the Number of Ships
Exercise 14-5: All-Time High Score
Exercise 14-6: Refactoring
Exercise 14-7: Expanding the Game
Exercise 14-8: Sideways Shooter, Final Version
Summary
15
GENERATING DATA
Installing Matplotlib
Plotting a Simple Line Graph
Changing the Label Type and Line Thickness
Correcting the Plot
Using Built-in Styles
Plotting and Styling Individual Points with scatter()
Plotting a Series of Points with scatter()
Calculating Data Automatically
Defining Custom Colors
Using a Colormap
Saving Your Plots Automatically
Exercise 15-1: Cubes
Exercise 15-2: Colored Cubes
Random Walks
Creating the RandomWalk() Class
Choosing Directions
Plotting the Random Walk
Generating Multiple Random Walks
Styling the Walk
Exercise 15-3: Molecular Motion
Exercise 15-4: Modified Random Walks
Exercise 15-5: Refactoring
Rolling Dice with Plotly
Installing Plotly
Creating the Die Class
Rolling the Die
Analyzing the Results
Making a Histogram
Rolling Two Dice
Rolling Dice of Different Sizes
Exercise 15-6: Two D8s
Exercise 15-7: Three Dice
Exercise 15-8: Multiplication
Exercise 15-9: Die Comprehensions
Exercise 15-10: Practicing with Both Libraries
Summary
16
DOWNLOADING DATA
The CSV File Format
Parsing the CSV File Headers
Printing the Headers and Their Positions
Extracting and Reading Data
Plotting Data in a Temperature Chart
The datetime Module
Plotting Dates
Plotting a Longer Timeframe
Plotting a Second Data Series
Shading an Area in the Chart
Error Checking
Downloading Your Own Data
Exercise 16-1: Sitka Rainfall
Exercise 16-2: Sitka–Death Valley Comparison
Exercise 16-3: San Francisco
Exercise 16-4: Automatic Indexes
Exercise 16-5: Explore
Mapping Global Data Sets: JSON Format
Downloading Earthquake Data
Examining JSON Data
Making a List of All Earthquakes
Extracting Magnitudes
Extracting Location Data
Building a World Map
A Different Way of Specifying Chart Data
Customizing Marker Size
Customizing Marker Colors
Other Colorscales
Adding Hover Text
Exercise 16-6: Refactoring
Exercise 16-7: Automated Title
Exercise 16-8: Recent Earthquakes
Exercise 16-9: World Fires
Summary
17
WORKING WITH APIS
Using a Web API
Git and GitHub
Requesting Data Using an API Call
Installing Requests
Processing an API Response
Working with the Response Dictionary
Summarizing the Top Repositories
Monitoring API Rate Limits
Visualizing Repositories Using Plotly
Refining Plotly Charts
Adding Custom Tooltips
Adding Clickable Links to Our Graph
More About Plotly and the GitHub API
The Hacker News API
Exercise 17-1: Other Languages
Exercise 17-2: Active Discussions
Exercise 17-3: Testing python_repos.py
Exercise 17-4: Further Exploration
Summary
18
GETTING STARTED WITH DJANGO
Setting Up a Project
Writing a Spec
Creating a Virtual Environment
Activating the Virtual Environment
Installing Django
Creating a Project in Django
Creating the Database
Viewing the Project
Exercise 18-1: New Projects
Starting an App
Defining Models
Activating Models
The Django Admin Site
Defining the Entry Model
Migrating the Entry Model
Registering Entry with the Admin Site
The Django Shell
Exercise 18-2: Short Entries
Exercise 18-3: The Django API
Exercise 18-4: Pizzeria
Making Pages: The Learning Log Home Page
Mapping a URL
Writing a View
Writing a Template
Exercise 18-5: Meal Planner
Exercise 18-6: Pizzeria Home Page
Building Additional Pages
Template Inheritance
The Topics Page
Individual Topic Pages
Exercise 18-7: Template Documentation
Exercise 18-8: Pizzeria Pages
Summary
19
USER ACCOUNTS
Allowing Users to Enter Data
Adding New Topics
Adding New Entries
Editing Entries
Exercise 19-1: Blog
Setting Up User Accounts
The users App
The Login Page
Logging Out
The Registration Page
Exercise 19-2: Blog Accounts
Allowing Users to Own Their Data
Restricting Access with @login_required
Connecting Data to Certain Users
Restricting Topics Access to Appropriate Users
Protecting a User’s Topics
Protecting the edit_entry Page
Associating New Topics with the Current User
Exercise 19-3: Refactoring
Exercise 19-4: Protecting new_entry
Exercise 19-5: Protected Blog
Summary
20
STYLING AND DEPLOYING AN APP
Styling Learning Log
The django-bootstrap4 App
Using Bootstrap to Style Learning Log
Modifying base.html
Styling the Home Page Using a Jumbotron
Styling the Login Page
Styling the Topics Page
Styling the Entries on the Topic Page
Exercise 20-1: Other Forms
Exercise 20-2: Stylish Blog
Deploying Learning Log
Making a Heroku Account
Installing the Heroku CLI
Installing Required Packages
Creating a requirements.txt File
Specifying the Python Runtime
Modifying settings.py for Heroku
Making a Procfile to Start Processes
Using Git to Track the Project’s Files
Pushing to Heroku
Setting Up the Database on Heroku
Refining the Heroku Deployment
Securing the Live Project
Committing and Pushing Changes
Setting Environment Variables on Heroku
Creating Custom Error Pages
Ongoing Development
The SECRET_KEY Setting
Deleting a Project on Heroku
Exercise 20-3: Live Blog
Exercise 20-4: More 404s
Exercise 20-5: Extended Learning Log
Summary
AFTERWORD
A
INSTALLATION AND TROUBLESHOOTING
Python on Windows
Finding the Python Interpreter
Adding Python to Your Path Variable
Reinstalling Python
Python on macOS
Installing Homebrew
Installing Python
Python on Linux
Python Keywords and Built-in Functions
Python Keywords
Python Built-in Functions
B
TEXT EDITORS AND IDES
Customizing Sublime Text Settings
Converting Tabs to Spaces
Setting the Line Length Indicator
Indenting and Unindenting Code Blocks
Commenting Out Blocks of Code
Saving Your Configuration
Further Customizations
Other Text Editors and IDEs
IDLE
Geany
Emacs and Vim
Atom
Visual Studio Code
PyCharm
Jupyter Notebooks
C
GETTING HELP
First Steps
Try It Again
Take a Break
Refer to This Book’s Resources
Searching Online
Stack Overflow
The Official Python Documentation
Official Library Documentation
r/learnpython
Blog Posts
Internet Relay Chat
Making an IRC Account
Channels to Join
IRC Culture
Slack
Discord
D
USING GIT FOR VERSION CONTROL
Installing Git
Installing Git on Windows
Installing Git on macOS
Installing Git on Linux
Configuring Git
Making a Project
Ignoring Files
Initializing a Repository
Checking the Status
Adding Files to the Repository
Making a Commit
Checking the Log
The Second Commit
Reverting a Change
Checking Out Previous Commits
Deleting the Repository
INDEX
PREFACE TO THE SECOND EDITION
The response to the first edition of Python Crash Course has been
overwhelmingly positive. More than 500,000 copies are in print,
including translations in eight languages. I’ve received letters and emails
from readers as young as 10, as well as from retirees who want to learn
to program in their free time. Python Crash Course is being used in
middle schools and high schools, and also in college classes. Students
who are assigned more advanced textbooks are using Python Crash
Course as a companion text for their classes and finding it a worthwhile
supplement. People are using it to enhance their skills on the job and to
start working on their own side projects. In short, people are using the
book for the full range of purposes I had hoped they would.
The opportunity to write a second edition of Python Crash Course has
been thoroughly enjoyable. Although Python is a mature language, it
continues to evolve as every language does. My goal in revising the book
was to make it leaner and simpler. There is no longer any reason to
learn Python 2, so this edition focuses on Python 3 only. Many Python
packages have become easier to install, so setup and installation
instructions are easier. I’ve added a few topics that I’ve realized readers
would benefit from, and I’ve updated some sections to reflect new,
simpler ways of doing things in Python. I’ve also clarified some sections
where certain details of the language were not presented as accurately as
they could have been. All the projects have been completely updated
using popular, well-maintained libraries that you can confidently use to
build your own projects.
The following is a summary of specific changes that have been made
in the second edition:
In Chapter 1, the instructions for installing Python have been
simplified for users of all major operating systems. I now
recommend the text editor Sublime Text, which is popular among
beginner and professional programmers and works well on all
operating systems.
Chapter 2 includes a more accurate description of how variables
are implemented in Python. Variables are described as labels for
values, which leads to a better understanding of how variables
behave in Python. The book now uses f-strings, introduced in
Python 3.6. This is a much simpler way to use variable values in
strings. The use of underscores to represent large numbers, such as
1_000_000, was also introduced in Python 3.6 and is included in this
edition. Multiple assignment of variables was previously introduced
in one of the projects, and that description has been generalized
and moved to Chapter 2 for the benefit of all readers. Finally, a
clear convention for representing constant values in Python is
included in this chapter.
In Chapter 6, I introduce the get() method for retrieving values
from a dictionary, which can return a default value if a key does not
exist.
The Alien Invasion project (Chapters 12–14) is now entirely class-
based. The game itself is a class, rather than a series of functions.
This greatly simplifies the overall structure of the game, vastly
reducing the number of function calls and parameters required.
Readers familiar with the first edition will appreciate the simplicity
this new class-based approach provides. Pygame can now be
installed in one line on all systems, and readers are given the option
of running the game in fullscreen mode or in a windowed mode.
In the data visualization projects, the installation instructions for
Matplotlib are simpler for all operating systems. The visualizations
featuring Matplotlib use the subplots() function, which will be
easier to build upon as you learn to create more complex
visualizations. The Rolling Dice project in Chapter 15 uses Plotly, a
well-maintained visualization library that features a clean syntax
and beautiful, fully customizable output.
In Chapter 16, the weather project is based on data from NOAA,
which should be more stable over the next few years than the site
used in the first edition. The mapping project focuses on global
earthquake activity; by the end of this project you’ll have a
stunning visualization showing Earth’s tectonic plate boundaries
through a focus on the locations of all earthquakes over a given
time period. You’ll learn to plot any data set involving geographic
points.
Chapter 17 uses Plotly to visualize Python-related activity in open
source projects on GitHub.
The Learning Log project (Chapters 18–20) is built using the latest
version of Django and styled using the latest version of Bootstrap.
The process of deploying the project to Heroku has been
simplified using the django-heroku package, and uses environment
variables rather than modifying the settings.py files. This is a simpler
approach and is more consistent with how professional
programmers deploy modern Django projects.
Appendix A has been fully updated to recommend current best
practices in installing Python. Appendix B includes detailed
instructions for setting up Sublime Text and brief descriptions of
most of the major text editors and IDEs in current use. Appendix C
directs readers to newer, more popular online resources for getting
help, and Appendix D continues to offer a mini crash course in
using Git for version control.
The index has been thoroughly updated to allow you to use Python
Crash Course as a reference for all of your future Python projects.
Thank you for reading Python Crash Course! If you have any feedback
or questions, please feel free to get in touch.
ACKNOWLEDGMENTS
This book would not have been possible without the wonderful and
extremely professional staff at No Starch Press. Bill Pollock invited me
to write an introductory book, and I deeply appreciate that original
offer. Tyler Ortman helped shape my thinking in the early stages of
drafting. Liz Chadwick’s and Leslie Shen’s initial feedback on each
chapter was invaluable, and Anne Marie Walker helped to clarify many
parts of the book. Riley Hoffman answered every question I had about
the process of assembling a complete book and patiently turned my
work into a beautiful finished product.
I’d like to thank Kenneth Love, the technical reviewer for Python
Crash Course. I met Kenneth at PyCon one year, and his enthusiasm for
the language and the Python community has been a constant source of
professional inspiration ever since. Kenneth went beyond simple fact-
checking and reviewed the book with the goal of helping beginning
programmers develop a solid understanding of the Python language and
programming in general. That said, any inaccuracies that remain are
completely my own.
I’d like to thank my father for introducing me to programming at a
young age and for not being afraid that I’d break his equipment. I’d like
to thank my wife, Erin, for supporting and encouraging me through the
writing of this book, and I’d like to thank my son, Ever, whose curiosity
inspires me every single day.
INTRODUCTION
Every programmer has a story about how they learned to write their
first program. I started programming as a child when my father was
working for Digital Equipment Corporation, one of the pioneering
companies of the modern computing era. I wrote my first program on a
kit computer that my dad had assembled in our basement. The
computer consisted of nothing more than a bare motherboard
connected to a keyboard without a case, and its monitor was a bare
cathode ray tube. My initial program was a simple number guessing
game, which looked something like this:
I'm thinking of a number! Try to guess the number I'm thinking of: 25
Too low! Guess again: 50
Too high! Guess again: 42
That's it! Would you like to play again? (yes/no) no
Thanks for playing!
Online Resources
You can find all the supplementary resources for the book online at
https://nostarch.com/pythoncrashcourse2e/ or
http://ehmatthes.github.io/pcc_2e/. These resources include:
Setup instructions These instructions are identical to what’s in the
book but include active links you can click for all the different
pieces. If you’re having any setup issues, refer to this resource.
Updates Python, like all languages, is constantly evolving. I
maintain a thorough set of updates, so if anything isn’t working,
check here to see whether instructions have changed.
Solutions to exercises You should spend significant time on your
own attempting the exercises in the “Try It Yourself” sections. But if
you’re stuck and can’t make any progress, solutions to most of the
exercises are online.
Cheat sheets A full set of downloadable cheat sheets for a quick
reference to major concepts is also online.
Why Python?
Every year I consider whether to continue using Python or whether to
move on to a different language—perhaps one that’s newer to the
programming world. But I continue to focus on Python for many
reasons. Python is an incredibly efficient language: your programs will
do more in fewer lines of code than many other languages would
require. Python’s syntax will also help you write “clean” code. Your code
will be easy to read, easy to debug, and easy to extend and build upon
compared to other languages.
Other documents randomly have
different content
umili casolari dei contadini. Dal che ne nacque più forza alla potenza
popolare; perciocchè credessi là esser la buona causa dov'era la
virtù, e la cattiva dov'era il vizio.
A questo si aggiungeva che a gran pezza l'entrata non pareggiava
l'uscita dello Stato, deplorabile frutto dei concetti smisurati di Luigi
XIV, del voluttuoso vivere di Luigi XV, e del profuso spendere della
corte di Luigi XVI, ancorchè questo principe se ne vivesse per sè
molto parcamente. Questo difetto nell'entrata era giunto a tale sul
finire del 1786, ch'era per nascere una gran rovina, se presto non vi
si rimediava.
In cotal modo scomposte le cose, passata la forza dell'opinione
dai nobili ai popolari, dai ricchi ai poveri, dai prelati ai curati, e
mancato il denaro, principal nervo dello Stato, si vedeva, che ove
nascesse un primo incitamento, un grande sovvertimento sarebbe
accaduto. Nè la natura del re, dolce e buona, era tale che potesse
dare speranza di potere o allontanare o indirizzare con norma certa
ed a posta sua gli accidenti che si temevano.
Qui nacque un caso degno veramente di eterne lagrime, e pur
non raro nelle memorie tramandate dagli storici. Tanto è la natura
umana sempre più consentanea a sè stessa nel male che nel bene, e
tanto sono cupe le ambizioni degli uomini. Volevasi da tutti, come
opinione portata dai tempi, e come cosa utile e giusta, un'equalità
civile, un'equalità d'imposte, una sicurezza delle persone, una
riforma negli ordini giudiziali, una maggior larghezza nello scrivere.
Era il re inclinato ad accomodar le cose ai tempi, per quanto la
prudenza e le prerogative della corona, tanto salutari in un reame
vasto ed in una nazione vivace e mobile, il comportassero. Ma una
setta composta principalmente dai parlamenti, dai pari del regno, dai
prelati più ragguardevoli, dai nobili più principali, e secondata da un
principe del sangue, del quale se fu biasimevole la vita, fu ancor più
lagrimevole il fine, preoccuparono il passo, e vollero farsi capi e
guidatori, dell'impresa. In questo il pensier loro era di cattivarsi con
allettattive parole la benevolenza del popolo, e diminuire, con
l'aumento della propria, l'autorità della corona. Forse i primi e i
principali autori di questo disegno miravano più oltre, velando con
parole denotanti amore di popolo pensieri colpevoli di mutazioni
nella famiglia regnante.
Quale di questo sia la verità, i capi di questa setta si prevalsero
molto opportunamente per arrivare ai fini loro, di un errore
commesso dal governo, il quale diede occasione alla resistenza loro
e fu primo principio di quel fatale incendio che arse prima il reame di
Francia, poi propagatosi per tutta Europa, vi trasse tutto a
scompiglio ed a rovina. Il re, in vece di cominciar l'opera dalle
riforme tanto desiderate del popolo, poi ordinar le tasse, volle
principiare a por le tasse, poi le riforme. Quindi l'amore cominciò a
convertirsi in odio; la setta nemica alla corona se ne prevalse.
Adunque, avendo egli pubblicato due editti, uno perchè si ponesse
un'imposta sopra le terre, l'altro perchè si ponesse una tassa sulla
carta bollata, il parlamento di Parigi, non solo fortemente protestò,
ma, ancora più oltre procedendo, ordinò che chiunque recasse ad
effetto i due editti fosse riputato reo di tradimento e nemico della
patria. Questo era il momento d'insorgere da parte del governo, e di
dar forza alla legge, e di aggiungere al tempo stesso qualche editto
contenente riforme e giuste per sè e desiderate dal popolo: ciò
avrebbe preoccupato il passo. Ma egli, rimettendo dall'opera sua,
lasciò andar non eseguiti i suoi editti. Quindi crebbe l'ardire del
parlamento, che, volendo usar l'occasione di guadagnarsi la grazia
del popolo a diminuzione dell'autorità regia, passò ad abbominare
con pubbliche scritture e con parole infiammative le incarcerazioni
arbitrarie; poi statuì, annuendo ad una convocazione degli Stati
generali, non essere in facoltà sua, nè della corona, nè di tutti due
uniti insieme trar denaro dal popolo per via di tasse; la sola volontà
del re non bastare a far la legge, nè la semplice espressione di
questa volontà poter costituire l'atto formale della nazione; essere
necessario, a volere che la volontà del re debba trarsi ad effetto,
ch'essa sia pubblicata secondo le forme prestabilite dalla legge; tali
essere i principii, tali i fondamenti della costituzione franzese; sapere
il parlamento che si volevano sovvertire i diritti pubblicati, per
istabilire il dispotismo; la libertà comune essere in pericolo; ma non
volere nè poter a tali rei disegni dar la mano, anzi volere opporsi, nè
mai permettere che gli essenziali diritti dei sudditi fossero conculcati
e messi al fondo; poi, rivoltosi al re, gl'intimò non isperasse di poter
annullare la costituzione, concentrando il parlamento nella sola sua
persona.
Rispose risentitamente il re, che quello che s'era fatto, s'era fatto
secondo gli ordini fondamentali dello Stato; non s'intromettessero in
affari di governo, perchè di ciò non avevano autorità di sorte alcuna;
ch'erano i parlamenti del regno di Francia corti di giustizia abili solo a
giudicare in materie civili e criminali, ma non avere autorità nè
legislativa nè amministrativa; la volontà del re non potersi senza
pericolo nè senza un nuovo e funesto cambiamento nella
constituzione del regno soggettare a quella dei magistrati; se ciò
fosse, cambierebbesi la monarchia in aristocrazia di magistrati;
badassero a far il debito loro come giudici, e lasciassero il governo
delle cose pubbliche a chi per antica consuetudine e per costituzione
l'aveva in mano; considerassero quante leggi erano state fatte in
ogni tempo dai re di Francia, non solo senza il consenso, ma ancora
contro la volontà dei parlamenti; la registrazione non essere
approvazione, ma solo autenticazione, nè altro in questo fare i
parlamenti, che le veci di notai del regno; che quest'erano le forme,
questi i precetti, ai quali e' si dovevano conformare, e se nol
facessero, si li costringerebbe.
Tal era la contesa nata in Francia fra il re ed i parlamenti circa le
prerogative e l'autorità della corona. Intanto ogni pubblico affare era
soprattenuto, perchè i parlamenti di provincia, come quello di Parigi,
o avevano cessato di per sè stessi l'ufficio, o erano dall'autorità regia
sospesi. Volle il re rimediare colla creazione della corte plenaria, ma
proruppe il parlamento in un'asprissima protesta; protestarono i pari
del regno; il clero stesso titubava.
Intanto uomini faziosi d'ogni genere, o stimolati espressamente
dei capi della parte dei parlamenti, o valendosi acconciamente
dell'occasione offerta dalla resistenza loro per macchinar novità,
andavano spargendo in ogni luogo semi di discordia e di anarchia.
Tumultuavasi a Grenoble, a Rennes, a Tolosa e in altre sedi di
parlamenti; orribili scritture uscite in Parigi chiamavano tiranno il re,
distruttore dei diritti del popolo, oppressore crudelissimo, esortavansi
le genti a levarsi, a disvelare e punir gli oppressori.
Avendo il re trovato, invece d'appoggio, opposizione e resistenza
nei parlamenti, nella nobiltà e in una parte del clero, dovette
necessariamente voltarsi verso il popolo, e fondar l'autorità sua sulla
potenza dei più, giacchè i pochi lo abbandonavano. Così era fatale
che le prime occasioni delle enormità che seguirono siano state date
da coloro ai quali più importava di evitarle, e che ne furono alla fine
le miserabili vittime. Adunque fu chiamato ministro il Ginevrino
Necker, e con lui altri personaggi consentanei al tempo. Si sperava
bene, il popolo esultava. Convocaronsi i notabili del regno,
convocaronsi gli stati generali. Prevalse in sul bel principio la parte
popolare, siccome quella, in favor della quale operavano i tempi.
Decretossi da prima, del qual consiglio fu autore Necker, fosse
doppio il numero dei deputati del terzo stato; poi sedessero i tre
ordini, non separatamente, ma in comune, poi si deliberasse, non
per ordini, ma per capi, il che diede del tutto la causa vinta ai
popolari. Gli ordini uniti presero il titolo di assemblea nazionale.
Erano portati al cielo: non si parlò più dei parlamenti, quantunque
eglino con opportune scritture si fossero sforzati di riguadagnarsi
quel favore che per un nuovo empito popolare s'era voltato
all'assemblea.
L'assemblea nazionale, ottenuta la superiorità del terzo stato,
abolì l'inequalità delle imposte, poi i privilegii della nobiltà, poi quelli
del clero, poi la nobiltà ed il clero; ed aboliti la nobiltà ed il clero,
s'incamminava ad indebolire talmente l'autorità regia, ch'ella non
fosse più che un'ombra vana. Il benefizio della equalità era
solamente apprezzato dai buoni; i tristi usavano l'occasione dello
indebolimento del governo. I faziosi dominavano: l'autorità regia non
li poteva frenare, perchè scema di potenza e d'opinione; l'autorità
popolare non ardiva perchè parlavano in nome ed in favor del
popolo. In ogni luogo, sedizioni, incendii e rapine, morti funeste e
modi di morte più funesti ancora, uomini mansueti divenuti crudeli;
uomini innocenti cacciati dai colpevoli; uomini benefici uccisi dai
beneficiati. Virtù in parole, malvagità in fatti. Novelle strane si
spargevano ogni giorno, e quanto più strane, tanto più credute, e
tosto si poneva mano nel sangue o ad ardere i palazzi; nè il sesso nè
le età si risparmiavano; ad ogni voce che si spargesse, il popolo
traeva, massime in Parigi. In mezzo a tutto questo, atti sublimi di
virtù patria e di virtù privata, ma insufficienti pel torrente
insuperabile e contrario. Nè si vedeva fine agli scandali, perchè
l'argine era rotto, e fin dove avesse a trascorrere questo fiume senza
freno, nissuno prevedeva.
In fine, dopo molti e varii eventi, l'assemblea con una cotal
costituzione che teneva poco del regio, meno ancora
dell'aristocratico, molto del democratico, rendè il re un nome senza
forza; poi venne l'assemblea legislativa, che il depose; poi il
consesso nazionale che l'uccise. Intanto uccisi o intimoriti i buoni,
impadronitisi della somma delle cose i tristi, la nazione franzese, non
trovando più riposo in sè stessa, minacciava, qual mare ingrossato
dalla tempesta, di uscir da' proprii confini, e di allagare con rovina
universale l'Europa.
Cristo mdccxc. Indizione viii.
Anno di Pio VI papa 16.
Leopoldo II imperadore 1.