Python Crash Course : A Hands-on, Project-based Introduction To Programming

Transcription

PYTHONCRASH COURSEAHandA-On, Project-BaAedIntroduction to ProgrammingbyEric Matthes nostarchpressSan Francisco

CONTENTS INDETAILACKNOWLEDGMENTSxxviixxixINTRODUCTIONWho Is This BookWhat Can YouFor?Expectxxxto Learn?xxxWhy Python?xxxi1PART I: BASICSlGETTING STARTEDSetting UpYourPython3ProgrammingEnvironment2 and3PythonofRunning Snippets34PythonCode4Hello World!PythononDifferentPythonon4Operating Systems5Linux58Python on OS XPython on WindowsTroubleshooting Installation IssuesRunning Python Programs from a Terminal101516On Linux and OS X16On Windows16Exercise 1-1:17python.orgExercise 1-2: Hello World17Typos17Exercise 1-3: Infinite Skills17Summary2VARIABLES AND SIMPLE DATA TYPESWhatReally Happenshello world.pyWhen You Run21Naming and Using VariablesName Errors WhenExercise 2-1:Exercise 2-2:Strings1920VariablesAvoiding19UsingSimple MessageSimple MessagesVariablesChanging Case in a String with MethodsCombining or Concatenating StringsAdding Whitespace to Strings with Tabs or NewlinesStripping WhitespaceErrors withAvoiding SyntaxPrinting in PythonStrings221232323242526262829Exercise 2-3: Personal Message29Exercise 2-4: Name Cases29Exercise 2-5: Famous Quote29

Exercise 2-6: Famous Quote 229Exercise iding Type Errors with the str()Integers in Python 2Exercise 2-8: Number EightFunction313233Exercise 2-9: Favorite Number33Comments33How Do You Write Comments?33What Kind of Comments Should You Write?33Exercise 2-10:The Zen ofAddingComments34Python34Exercise 2-11: Zen of Python36Summary363INTRODUCING LISTSWhat37Is a List?37Accessing ElementsinLista38Index Positions Start at 0, Not 1Using Individual Values from a List39Exercise 3-1: Names40Exercise 3-2:4039GreetingsExercise 3-3: Your Own List40Changing, Adding, and Removing ElementsModifying Elements in a ListAdding Elements toRemoving Elementsa4040Listfrom41aList42Exercise 3-4: Guest ListExercise 3-5:Changing46Guest List46Exercise 3-6: More Guests46Exercise 3-7:47Organizing a ListSorting aSorting aPrinting aFindingShrinkingGuest List47ListPermanently with the sort() MethodListTemporarilywith thesortedf)List in Reverse OrdertheLength of aExercise 3-8:4950Exercise 3-9: Dinner GuestsAvoiding IndexEveryErrors When50FunctionWorking with4849ListSeeing the WorldExercise 3-10:Function4750ListsExercise 3-11: Intentional ErrorSummary5052524WORKING WITH LISTS53Looping Through53anEntire ListA Closer LookatLoopingDoing More Work Within a for LoopDoing Something After a for Loop545556

Avoiding oIndent AdditionalIndenting UnnecessarilyIndenting Unnecessarily AfterLines59theLoop60Exercise 4-1: Pizzas6060Exercise 4-2: AnimalsNumerical ListsUsing the range()61Exercise 4-3:61FunctionUsing range() to MakeSimple Statistics with aList ComprehensionsCountingaList of NumbersList of NumbersExercise 4-5:Summing626363to64Twenty64Exercise 4-4: One MillionaMillion64Exercise 4-6: Odd Numbers64Exercise 4-7: Threes64Exercise 4-8: Cubes64Exercise 4-9: CubeWorking with Part of a ListSlicing a ListLooping Through aCopying a List64Comprehension656566Slice6769Exercise 4-10: SlicesMy Pizzas, YourExercise 4-12: More LoopsPizzasExercise 4-11:6969Defining a TupleLooping Through All ValuesWriting over a TupleinaTuple707171Exercise 4-13: Buffet72Your CodeThe6969TuplesStyling59the ngth73Line73Blank LinesOther Style Guidelines73Exercise 4-14: PEP 874Exercise 4-15: Code Review7474Summary575IF STATEMENTSA76Simple Example76Conditional TestsChecking for gforEqualityInequalityComparisons7879Checking Multiple ConditionsCheckingWhetheraValue Is in7778foraList80Contents in DetailXIM

Checking Whether a ValueBoolean ExpressionsIs Not in a List81Exercise 5-1: Conditional Tests82Exercise 5-2: More Conditional Tests82if Statements82Simple ifStatements82if-else StatementsThe if-elif-else Chain83Using Multiple84elif Blocks86Omitting the else BlockTesting Multiple Conditions86Exercise 5-3: Alien Colors #18887Exercise 5-4: Alien Colors #288Exercise 5-5: Alien Colors #389Exercise 5-6:Stages of Life89Exercise 5-7: Favorite Fruit89if Statements with ListsUsing89Checking for Special ItemsChecking That a List Is Not EmptyUsing Multiple Lists90Exercise 5-8: Hello Admin93Exercise 5-9: No Users93Exercise 5-10:Checking9192Usernames93Exercise 5-11: Ordinal NumbersStyling8193Your if StatementsExercise 5-12:94Styling if statements94Exercise 5-13: Your Ideas94Summary946DICTIONARIES95Simple DictionaryWorking with DictionariesA9696Accessing Values in a DictionaryAdding New Key-Value PairsStartingwith979798Empty DictionaryModifying Values in a DictionaryRemoving Key-Value PairsA Dictionary of Similar Objects100Exercise 6-1: Person102Exercise 6-2: Favorite Numbers102an99100Exercise 6-3:102GlossaryDictionaryLooping Through aLooping Through All Key-Value PairsLooping Through All the Keys in a DictionaryLooping ThroughaLooping ThroughAll Values inExercise 6-4:Dictionary's KeysGlossaryExercise 6-5: RiversExercise ng*!lf2ain Order102A List of Dictionaries109A List inIllT ntonUinahotnilDictionary

ADictionaryExercise 6-7:inaDictionary113People7 74Exercise 6-8: Pets7 75Exercise 6-9: Favorite Places7 75Exercise 6-10: Favorite Numbers7 75Exercise 6-7 7: Cities7 75Exercise 6-12:Extensions'75Summary1157USER INPUT AND WHILE LOOPSHow theinput()Writing Clear PromptsUsing int() to Accept Numerical Input118The Modulo120OperatorAccepting Input in Python1192.712172 7Exercise 7-2: Restaurant Seating727IntroducingMultiples of Ten72 7whileLoopsThe while Loop in ActionLetting the User Choose WhenUsing a FlagUsing break to Exit a LoopUsingcontinue ina122122to Quit122124125126LoopInfiniteAvoidingExercise 7-4:a118Exercise 7-1: Rental CarExercise 7-3:Using117Function Works126LoopsPizza Toppings727Exercise 7-5: Movie Tickets727Exercise 7-6: Three Exits728Exercise 7-7:728whileInfinitywith Lists and Dictionaries128Moving Items from One List to AnotherRemoving All Instances of Specific Values fromFilling a Dictionary with User Input128LoopaList129130Exercise 7-8: Deli73 7Exercise 7-9: No Pastrami73 7Exercise 7-10: Dream Vacation73 g Information to a FunctionArguments and Parameters134Exercise 8-1:7 35MessageExercise 8-2: Favorite BookPassing Arguments1357 35135Positional Arguments136Keyword Arguments137Default Values138

Equivalent Function CallsAvoiding Argument Errors139140Exercise 8-3: T-ShirtExercise 8-4: Large Shirts141141Exercise 8-5: Cities141Return Values141Returning a Simple ValueMaking an Argument OptionalReturning a DictionaryUsing a Function with a while Loop142142144145Exercise 8-6: City NamesExercise 8-7: Album146146Exercise 8-8: User AlbumsPassing146Lista147ModifyingPreventingaList inaFunction fromaFunction147ModifyingaListExercise 8-9: MagiciansExercise 8-10: Great MagiciansExercise 8-11:PassingUnchanged MagiciansArbitrary Number of ArgumentsMixing Positional and Arbitrary ArgumentsUsing Arbitrary Keyword ArgumentsanExercise 8-12: SandwichesExercise 8-13: User Profilean152154156AliasUsing as to Give a Module an AliasImporting All Functions in a ModuleFunctionsExercise 8-15: Printing ModelsExercise 8-16: ImportsStyling152154Entire ModuleExercise 8-17:150151154Importing Specific FunctionsUsing as to Give a Function anStyling150154Your Functions in ModulesImporting150154Exercise 8-14: 91599CLASSES161Creating and Using a ClassCreating the Dog ClassMakinganInstance from162162aClassExercise 9-1: RestaurantExercise 9-2: Three RestaurantsExercise 9-3: UsersWorkingwith Classes and InstancesThe Car ClassSetting a Default Value for an AttributeModifying Attribute ValuesExercise 9-4: Number ServedExercise 9-5: Login AttemptsXViContents inDetail164166166166167167168168171171

Inheritance172The() Method forinitInheritancePythoninChild Classa173Defining Attributes and Methods for the ChildOverriding Methods from the Parent ClassInstancesasAttributes174175175177Exercise 9-6: Ice Cream StandExercise 9-7: Admin178Exercise 9-8:Privileges178Exercise 9-9:Battery Upgrade178178179179ModuleaImporting Multiple Classes fromImportingImportingImportinganModuleEntire ModuleAll Classes fromModule intoaaaExercise 9-10:Exercise 9-11:Exercise 9-12:Module1811 821 831 84Imported RestaurantImported AdminMultiple ModulesPython Standard Library1841841841 84Exercise 9-13: OrderedDict RewriteExercise 9-14: DiceExercise 9-15:1 801 82ModuleaYour Own WorkflowFindingStylingClassModeling Real-World ObjectsImporting ClassesImporting a Single ClassStoring Multiple Classes inThe1722.7Python Module of the WeekClasses1861867861 86Summary18710FILES AND EXCEPTIONSReadingfroma189FileReading190Entire Filean190File PathsReadingWriting191LinebyLine193Making a List of Lines from a FileWorking with a File's ContentsLarge Files: One Million Digits194Is Your196BirthdayContained in Pi?Exercise 10-1: LearningPythonExercise 10-2:CtoaLearning195197197File197Writing to an Empty FileWriting Multiple LinesAppending194to a197198File199Exercise 10-3: Guest199Exercise 10-4: Guest BookExercise 10-5:199ProgrammingPollExceptionsHandling the199200ZeroDivisionErrorUsing try-except BlocksUsing Exceptions to PreventException200200Crashes201

The else Block202Handling the FileNotFoundError ExceptionAnalyzing TextWorking with Multiple FilesFailing SilentlyDeciding Which Errors to Report203Exercise 10-6: Addition205206207207Exercise 10-7: Addition Calculator208Exercise 10-8: Cats and208DogsExercise 10-9: Silent Cats and208DogsExercise 10-10: Common WordsStoring204208Data208Using json.dump() and json.load()Saving and Reading User-Generated209Data210Refactoring212Exercise 10-11: Favorite Number214Exercise 10-12: Favorite Number Remembered214Exercise 10-13:VerifyUserSummary21421411TESTING YOUR CODETestinga216Unit Tests and Test Cases217A217Passing TestA Failing TestResponding toAddingTestinga215Function218aFailed TestNew Tests219221Exercise 11-1:City, Country222Exercise 11-2:Population222ClassAVariety222of Assert Methods222A Class to Test223Testing the AnonymousSurvey ClassThe setUpf) Method225Exercise 11-3:Employee227228Summary228PART II: PROJECTS231PROJECT 1: ALIEN INVASION12A SHIP THAT FIRES BULLETSPlanning235236YourProjectInstalling PygameInstalling Python PackagesInstalling Pygame on Linux236with pip237238

Installing PygameInstalling PygameStarting theonOS X239onWindows240GameProjectCreating a Pygame Window and RespondingSetting the Background ColorCreating a Settings Class240to UserInput241242243Adding the Ship ImageCreating the Ship ClassDrawing the Ship to the ScreenRefactoring: the game functions ModuleThe check events() FunctionThe update screen() FunctionExercise 12-1: Blue Sky244245246247247248249Exercise 12-2: Game Character249Piloting the ShipResponding to a KeypressAllowing Continuous MovementMoving Both Left and RightAdjusting the Ship's SpeedLimiting the Ship's RangeRefactoring check events()249A Quick 256settings.py256game functions.pyship.py256Exercise 12-3: Rocket257Exercise 12-4:257257KeysBullets257Adding the Bullet SettingsCreating the Bullet ClassStoring Bullets in a GroupFiring Bullets257Deleting Old Bullets261Limiting the Number of BulletsCreating the update bullets() FunctionCreating the fire bullet() Function262Exercise 12-5:258259260263264Sideways Shooter264Summary26413ALIENS!Project266the First e Alien ClassanMaking the Alien AppearBuilding267Instance of the Alien268Onscreen268the Alien FleetDetermining How Many AliensCreating Rows of AliensCreating the Fleet269Fit inaRow269270271

Refactoring create fleet()Adding Rows273Exercise 13-1: Stars276273Exercise 13-2: Better StarsMaking the Fleet MoveMoving the Aliens RightCreating Settings for FleetCheckingto See Whether276276276DirectionanAlien Has Hit theDropping the Fleet and ChangingExercise 13-3:Exercise 13-4:ShootingDirectionRaindropsSteady Rain277Edge278278279279Aliens280Detecting Bullet CollisionsMaking Larger Bullets for Testing280281Repopulating the FleetSpeeding Up the BulletsRefactoring update bullets()282Exercise 13-5: Catch284Ending the283283Game284Detecting Alien-Ship CollisionsResponding to Alien-Ship Collisions284Aliens that Reach the Bottom of the ScreenGame Over!288IdentifyingWhen Parts of the Game Should RunExercise 13-6: Game 1Burton292Creating a Button ClassDrawing the Button to the ScreenStarting the GameResetting the Game292Deactivating the Play297HidingButtonthe Mouse CursorExercise 14-1: Press P toExercise 14-2:294295296298Play298Target Practice298Leveling UpModifying the Speed SettingsResetting the SpeedExercise 14-3: Challenging Target PracticeScoring299299300301301Displaying the ScoreMaking a ScoreboardUpdating the Score as AliensMaking Sure to Score AllIncreasing Point ValuesRounding theHigh ScoresScoreHits301303Are Shot Down304305306307308

Displaying the LevelDisplaying the Number of ShipsExercise 14-4: All-Time High ScoreExercise 14-5: RefactoringExercise 14-6: Expanding Alien Invasion310313317317317317SummaryPROJECT 2: DATA VISUALIZATION15GENERATING DATA321Installing matplotlib322On Linux322On OS X322On Windows323Testing matplotlib323The323matplotlib GalleryPlotting a Simple Line GraphChanging the Label Type and Graph ThicknessCorrecting the PlotPlotting and Styling Individual Points with scatter()Plotting a Series of Points with scatter()Calculating Data AutomaticallyRemoving Outlines fromData PointsDefining Custom ColorsUsing a ColormapSaving Your Plots Automatically324326326328328329330330331Exercise 15-1: Cubes331Exercise 15-2: Colored Cubes33 JRandom Walks331Creating the RandomWalk() ClassChoosing DirectionsPlotting the Random WalkGenerating Multiple Random WalksStyling the WalkColoring the PointsPlotting the Starting and Ending PointsCleaning Up the AxesAdding Plot PointsAltering the Size to Fill the Screen332332333334335335336337337338Exercise 15-3: Molecular Motion339Exercise 15-4: Modified Random Walks339Exercise 15-5:Rolling324RefactoringPygalInstalling PygalThe Pygal GalleryCreating the Die ClassRolling the DieAnalyzing the ResultsDice with339339340340340341341

Making a HistogramRolling Two DiceRolling Dice of Different Sizes342343345Exercise 15-6: Automatic LabelsExercise 15-7: Two D8s346346Exercise 15-8: Three Dice346Exercise 15-9:ExerciseSummaryMultiplication15-10: Practicing with Both346Libraries34634716DOWNLOADING DATA349The CSV File Format350Parsing the CSV File HeadersPrinting the Headers and Their PositionsExtracting and Reading DataPlotting Data in a Temperature Chart352353The datetime Module354Plotting355PlottingDatesaLonger TimeframePlotting a SecondShading an AreaError-Checking356Data Seriesin357the Chart358359Exercise 16-1: San FranciscoExercise 16-2: Sitka-Death ValleyExercise 16-3: Rainfall362Comparison362362Exercise 16-4: ExploreMapping Global Data Sets: JSON FormatDownloading World Population DataExtracting Relevant DataConverting Strings into Numerical ValuesObtaining Two-Digit Country CodesBuilding a World MapPlotting Numerical Data on a World MapPlotting a Complete Population MapGrouping Countries by PopulationStyling World Maps in PygalLightening the Color 2374Exercise 16-5: All Countries375Exercise 16-6: Gross Domestic Product375Exercise 16-7: Choose Your Own Data375Exercise 16-8: Testing the country codes Module37537517WORKING WITH APISUsinga377Web APIGitandGitHubRequesting Data UsingInstalling Requests378378anAPI Call378379

an APIResponseWorking with the Response DictionaryProcessingSummarizing the Top Repositories379380382Monitoring API Rate LimitsVisualizing Repositories Using PygalRefining Pygal ChartsAdding Custom TooltipsPlotting the DataAdding Clickable Links to Our Graph383The Hacker News API390384386387388390Other LanguagesExercise 17-2: Active Discussions393Exercise 17-3:393Exercise17-1:Testing python repos.py393393SummaryPROJECT 3: WEB APPLICATIONS18GETTING STARTED WITH DJANGOSetting Up a ProjectWriting a Spec398398Virtual vating the Virtual EnvironmentInstalling DjangoCreating a Project in Djangothe ing ModelsActivating ModelsThe Django Admin SiteDefining the Entry Model403404406408Migrating the Entry ModelRegistering Entry with the AdminThe Django Shell409SiteExercise 18-2: Short EntriesExercise 18-3: TheDjangoMaking Pages: The Learning LogMapping a URL4094104 72API4/2Exercise 18-4: ise 18-5: Meal PlannerExercise 18-6: Pizzeria ercise 18-1: NewStarting397AdditionalPagesTemplate InheritanceThe Topics PageIndividual Topic Pages4 76Page4 76416416418421

Exercise 18-7:TemplateExercise 18-8: PizzeriaDocumentation424424Pages425Summary19USER ACCOUNTSAllowing Users427Enter DatatoAddingAddingNewEditingEntries428New Entries432Exercise 19-1:Setting Up428Topics435Blog438User AccountsThe439439AppusersThe440Login PageLogging OutThe Registration PageExercise 19-2:Allowing UserstoBlog442443Accounts446Own Their Data446Restricting Access with @login requiredConnecting Data to Certain UsersRestricting Topics Access to Appropriate UsersProtecting a User's TopicsProtecting the edit entry PageAssociating New Topics with the Current UserExercise 19-3: RefactoringExercise 7 9-4; Protecting new entryExercise 19-5: 20STYLING AND DEPLOYING AN APPStyling Learning LogThe django-bootstrap3 AppUsing Bootstrap to Style Learning LogModifyingStyling thebase.htmltheaJumbotrononthe463Topic Page466466AccountInstalling the Heroku ToolbeltInstalling Required PackagesCreating a Packages List with466466466arequirements.txt FileSpecifying the Python RuntimeModifying settings.py for HerokuMakinga464466Stylish BlogDeploying Learning LogMaking a Heroku461463Exercise 20-1: Other FormsExercise 20-2:456457461Topics Pagethe Entries456458HomePage UsingStyling the Login PageStyling the new topic PageStylingStyling455Procfile to Start ProcessesModifying wsgi.pyfor Heroku467468468469470

Making a Directory for Static FilesUsing the gunicorn Server LocallyUsing Git to Track the Project's FilesPushingtoHeroku470471473Setting Up the Databasethe HerokuRefining470onHeroku474475DeploymentSecuring the Live ProjectCommitting and Pushing ChangesCreating Custom Error PagesOngoing DevelopmentThe SECRET KEY SettingDeleting a Project on Heroku476Exercise 20-3: Live482477478480481481BlogExercise 20-4: More 404s482Exercise 20-5: Extended482Learning Log482Summary483AFTERWORDAINSTALLING PYTHONPythonon485485Linux486the Installed VersionFindingInstalling PythonPythonon3486OS XFinding the InstalledUsing Homebrew ling Python3487488WindowsonWindowstheFindingPython InterpreterAdding Python to Your Path VariablePython Keywords and Built-in FunctionsPython KeywordsPython Built-in Functions488488489489489490B491TEXT EDITORS492GeanyLinuxInstalling Geany onInstalling Geany on WindowsRunning Python Programs in GeanyCustomizing Geany SettingsSublime Text492492493493494InstallingSublime TextonOS X494InstallingSublime TextonLinux494InstallingSublime Texton WindowsPrograms in Sublime Text495Running PythonConfiguringSublime TextCustomizingSublime TextSettings495495496

Installing IDLE on LinuxInstalling IDLE on OS XInstalling IDLE on WindowsCustomizing IDLE SettingsEmacs and vim4Vo496497497497GGETTING 500This Book's ResourcesSearching Online501Stack OverflowThe501Official PythonOfficialIRCLibraryr/learnpythonBlog Posts(Internet Relay 501502502502502502Channels to Join503IRC Culture503DUSING GIT FOR VERSION CONTROLInstallingMaking505Git506Installing Git on LinuxInstalling Git on OS XInstalling Git on WindowsConfiguring Git506aProject506506506507Ignoring FilesInitializing a Repository507Checking the StatusAdding Files to the RepositoryMaking a CommitChecking the Log508The Second Commit510507508509509Change511Checking Out Previous CommitsDeleting the Repository512RevertingINDEXa513515

Exercise 9-15: Python Moduleofthe Week 786 Styling Classes 1 86 Summary 187 10 FILES ANDEXCEPTIONS 189 Reading from a File 190 Reading an Entire File 190 File Paths 191 Reading Line byLine 193 Making a List of Lines from a File 194 Working with a File's Contents 194 LargeFiles: OneMillion Digits 195 Is YourBirthdayContained in Pi? 196