Docsity

Python Crash Course_ A Hands-On, Project-Based Introduction to Programming, Guide, Progetti e Ricerche di Programmazione e controllo

Toggle sidebar
bg1
A HANDS-ON, PROJECT-BASED
INTRODUCTION TO PROGRAMMING
PY THON
C R ASH COURSE
PY THON
C R ASH COURSE
2ND EDITION
ERIC MATTHES
SHELV E IN:
PROGRAMMING LANGUAGES/
PYTHON
$39.95 ($53.95 CDN)
LEARN PYTHON—
FAST!
COVERS PYTHON 3.X
Python Crash Course is the world’s best-selling guide
to the Python programming language. This fast-paced,
thorough introduction to programming with Python will
have you writing programs, solving problems, and
making things that work in no time.
In the first half of the book, you’ll learn basic program-
ming concepts, such as variables, lists, classes, and
loops, and practice writing clean code with exercises
for each topic. You’ll also learn how to make your
programs interactive and test your code safely before
adding it to a project. In the second half, you’ll put
your new knowledge into practice with three substantial
projects: a Space Invaders–inspired arcade game, a
set of data visualizations with Python’s handy libraries,
and a simple web app you can deploy online.
As you work through the book, you’ll learn how to:
• Use powerful Python libraries and tools, including
Pygame, Matplotlib, Plotly, and Django
• Make 2D games that respond to keypresses and
mouse clicks, and that increase in difficulty
• Use data to generate interactive visualizations
• Create and customize web apps and deploy them
safely online
• Deal with mistakes and errors so you can solve your
own programming problems
This updated second edition has been thoroughly revised
to reflect the latest in Python code and practices. The
first half of the book includes improved coverage of
topics like f-strings, constants, and managing data. In the
second half, the code for the projects has been updated
with better structure, cleaner syntax, and more popular
and up-to-date libraries and tools, like Plotly and the
latest version of Django. (For a full list of updates, see
the Preface.)
If you’ve been thinking about digging into programming,
Python Crash Course will get you writing real programs
fast. Why wait any longer? Start your engines and code!
ABOUT THE AUTHOR
Eric Matthes is a high school science, math, and program-
ming teacher living in Alaska. He has been writing
programs since he was five years old and is the author
of the Python Flash Cards, also from No Starch Press.
ww w.n os ta rc h. co m
TH E FINE S T IN GEEK EN TE RTAI N M E N T ™
“I LIE FLAT.”
This book uses a dura ble binding that w on’t snap shut
FSC F PO
WORLDWIDE
BEST SELLER
OVER 500,000
COPIES SOLD
WORLDWIDE
BEST SELLER
OVER 500,000
COPIES SOLD
WORLDWIDE
BEST SELLER
OVER 500,000
COPIES SOLD
WORLDWIDE
BEST SELLER
OVER 500,000
COPIES SOLD
PYTHON CRASH COURSE
PYTHON CRASH COURSE MATTHES
2ND EDITION
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Anteprima parziale del testo

Scarica Python Crash Course_ A Hands-On, Project-Based Introduction to Programming e più Guide, Progetti e Ricerche in PDF di Programmazione e controllo solo su Docsity!

A H A N D S - O N , P R O J E C T - B A S E D

I N T R O D U C T I O N T O P R O G R A M M I N G

P Y T H O N

C R A S H C O U R S E

P Y T H O N

C R A S H C O U R S E

2 N D E D I T I O N

E R I C M A T T H E S

P y t h o n

C r a s h C o u r s e

2 n d e d i t i o n

a h a n d s - o n , P r o j e c t - B a s e d

i n t r o d u c t i o n t o P r o g r a m m i n g

by Eric Matthes

San Francisco

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 soft-

ware 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.

B r i e f C o n t e n t s

Preface to the Second Edition xxvii

Acknowledgments xxxi

C o n t e n t s i n D e t a i l

Preface to the Second edition xxvii

acknowledgmentS xxxi

introduction xxxiii

Who Is This Book For? xxxiv What Can You Expect to Learn? xxxiv Online Resources xxxv Why Python? xxxvi

Part i: BaSicS 1

getting Started 3

Setting Up Your Programming Environment 3 Python Versions 4 Running Snippets of Python Code 4 About the Sublime Text Editor 4 Python on Different Operating Systems 5 Python on Windows 5 Python on macOS 7 Python on Linux 8 Running a Hello World Program 9 Configuring Sublime Text to Use the Correct Python Version 9 Running hello_world py 10 Troubleshooting 11 Running Python Programs from a Terminal 12 On Windows 12 On macOS and Linux 12 Exercise 1-1: python.org...................................... 13 Exercise 1-2: Hello World Typos................................. 13 Exercise 1-3: Infinite Skills..................................... 13 Summary 13

VariaBleS and SimPle data tyPeS 15

What Really Happens When You Run hello_world py 15 Variables 16 Naming and Using Variables 17 Avoiding Name Errors When Using Variables 17 Variables Are Labels 18 Exercise 2-1: Simple Message.................................. 19 Exercise 2-2: Simple Messages.................................. 19

xii Contents in Detail

xiv Contents in Detail

Contents in Detail xvii

  • Part I: BasIcs Introduction xxxiii
  • 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
  • Part II: Projects
  • Chapter 12: A Ship that Fires Bullets Project 1: Alien Invasion
  • Chapter 13: Aliens!
  • Chapter 14: Scoring
  • Chapter 15: Generating Data Project 2: Data Visualization
  • Chapter 16: Downloading Data
  • Chapter 17: Working with APIs
  • Chapter 18: Getting Started with Django Project 3: Web Applications
  • Chapter 19: User Accounts
  • Chapter 20: Styling and Deploying an App
  • Afterword
  • Appendix A: Installation and Troubleshooting
  • Appendix B: Text Editors and IDEs
  • Appendix C: Getting Help
  • Appendix D: Using Git for Version Control
  • Index
  • 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
  • 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
  • introducing liStS
  • What Is a List?
  • Accessing Elements in a List
  • Index Positions Start at 0, Not
  • 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 Contents in Detail xiii
  • Exercise 3-11: Intentional Error
  • Summary
  • 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
  • Exercise 4-15: Code Review.
  • Summary
  • 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
  • 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 Contents in Detail xv
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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 xviii Contents in Detail
  • 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
  • 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